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:44 UTC
[01/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Repository: incubator-ranger
Updated Branches:
refs/heads/master 830fe61cd -> 413fcb68f
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/entity/XXPortalUser.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPortalUser.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPortalUser.java
new file mode 100644
index 0000000..2a2b938
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPortalUser.java
@@ -0,0 +1,380 @@
+/*
+ * 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.entity;
+
+/**
+ * User details
+ *
+ */
+
+import java.util.*;
+
+import javax.persistence.*;
+import javax.xml.bind.annotation.*;
+
+import org.apache.ranger.common.*;
+import org.apache.ranger.entity.*;
+
+
+@Entity
+@Table(name="x_portal_user")
+@XmlRootElement
+public class XXPortalUser extends XXDBBase implements java.io.Serializable {
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @SequenceGenerator(name="X_PORTAL_USER_SEQ",sequenceName="X_PORTAL_USER_SEQ",allocationSize=1)
+ @GeneratedValue(strategy=GenerationType.AUTO,generator="X_PORTAL_USER_SEQ")
+ @Column(name="ID")
+ protected Long id;
+ @Override
+ public void setId(Long id) {
+ // TODO Auto-generated method stub
+ this.id=id;
+ }
+ @Override
+ public Long getId() {
+ // TODO Auto-generated method stub
+ return id;
+ }
+ /**
+ * First name of the user
+ * <ul>
+ * <li>The maximum length for this attribute is <b>1022</b>.
+ * </ul>
+ *
+ */
+ @Column(name="FIRST_NAME" , length=1022)
+ protected String firstName;
+
+ /**
+ * Last name of the user
+ * <ul>
+ * <li>The maximum length for this attribute is <b>1022</b>.
+ * </ul>
+ *
+ */
+ @Column(name="LAST_NAME" , length=1022)
+ protected String lastName;
+
+ /**
+ * Public screen name for the user
+ * <ul>
+ * <li>The maximum length for this attribute is <b>2048</b>.
+ * </ul>
+ *
+ */
+ @Column(name="PUB_SCR_NAME" , length=2048)
+ protected String publicScreenName;
+
+ /**
+ * Login ID of the user
+ * <ul>
+ * <li>The maximum length for this attribute is <b>767</b>.
+ * </ul>
+ *
+ */
+ @Column(name="LOGIN_ID" , unique=true , length=767)
+ protected String loginId;
+
+ /**
+ * <ul>
+ * <li>The maximum length for this attribute is <b>512</b>.
+ * </ul>
+ *
+ */
+ @Column(name="PASSWORD" , nullable=false , length=512)
+ protected String password;
+
+ /**
+ * Email address of the user
+ * <ul>
+ * <li>The maximum length for this attribute is <b>512</b>.
+ * </ul>
+ *
+ */
+ @Column(name="EMAIL" , unique=true , length=512)
+ protected String emailAddress;
+
+ /**
+ * Status of the user
+ * <ul>
+ * <li>This attribute is of type enum CommonEnums::ActivationStatus
+ * </ul>
+ *
+ */
+ @Column(name="STATUS" , nullable=false )
+ protected int status = XAConstants.ACT_STATUS_DISABLED;
+
+ /**
+ * Source of the user
+ * <ul>
+ * <li>This attribute is of type enum CommonEnums::UserSource
+ * </ul>
+ *
+ */
+ @Column(name="USER_SRC" , nullable=false )
+ protected int userSource = XAConstants.USER_APP;
+
+ /**
+ * Note
+ * <ul>
+ * <li>The maximum length for this attribute is <b>4000</b>.
+ * </ul>
+ *
+ */
+ @Column(name="NOTES" , length=4000)
+ protected String notes;
+
+ /**
+ * Default constructor. This will set all the attributes to default value.
+ */
+ public XXPortalUser ( ) {
+ status = XAConstants.ACT_STATUS_DISABLED;
+ userSource = XAConstants.USER_APP;
+ }
+
+ @Override
+ public int getMyClassType( ) {
+ return AppConstants.CLASS_TYPE_USER_PROFILE;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>firstName</b>.
+ * You cannot set null to the attribute.
+ * @param firstName Value to set member attribute <b>firstName</b>
+ */
+ public void setFirstName( String firstName ) {
+ this.firstName = firstName;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>firstName</b>
+ * @return String - value of member attribute <b>firstName</b>.
+ */
+ public String getFirstName( ) {
+ return this.firstName;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>lastName</b>.
+ * You cannot set null to the attribute.
+ * @param lastName Value to set member attribute <b>lastName</b>
+ */
+ public void setLastName( String lastName ) {
+ this.lastName = lastName;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>lastName</b>
+ * @return String - value of member attribute <b>lastName</b>.
+ */
+ public String getLastName( ) {
+ return this.lastName;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>publicScreenName</b>.
+ * You cannot set null to the attribute.
+ * @param publicScreenName Value to set member attribute <b>publicScreenName</b>
+ */
+ public void setPublicScreenName( String publicScreenName ) {
+ this.publicScreenName = publicScreenName;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>publicScreenName</b>
+ * @return String - value of member attribute <b>publicScreenName</b>.
+ */
+ public String getPublicScreenName( ) {
+ return this.publicScreenName;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>loginId</b>.
+ * You cannot set null to the attribute.
+ * @param loginId Value to set member attribute <b>loginId</b>
+ */
+ public void setLoginId( String loginId ) {
+ this.loginId = loginId;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>loginId</b>
+ * @return String - value of member attribute <b>loginId</b>.
+ */
+ public String getLoginId( ) {
+ return this.loginId;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>password</b>.
+ * You cannot set null to the attribute.
+ * @param password Value to set member attribute <b>password</b>
+ */
+ public void setPassword( String password ) {
+ this.password = password;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>password</b>
+ * @return String - value of member attribute <b>password</b>.
+ */
+ public String getPassword( ) {
+ return this.password;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>emailAddress</b>.
+ * You cannot set null to the attribute.
+ * @param emailAddress Value to set member attribute <b>emailAddress</b>
+ */
+ public void setEmailAddress( String emailAddress ) {
+ this.emailAddress = emailAddress;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>emailAddress</b>
+ * @return String - value of member attribute <b>emailAddress</b>.
+ */
+ public String getEmailAddress( ) {
+ return this.emailAddress;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>status</b>.
+ * You cannot set null to the attribute.
+ * @param status Value to set member attribute <b>status</b>
+ */
+ public void setStatus( int status ) {
+ this.status = status;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>status</b>
+ * @return int - value of member attribute <b>status</b>.
+ */
+ public int getStatus( ) {
+ return this.status;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>userSource</b>.
+ * You cannot set null to the attribute.
+ * @param userSource Value to set member attribute <b>userSource</b>
+ */
+ public void setUserSource( int userSource ) {
+ this.userSource = userSource;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>userSource</b>
+ * @return int - value of member attribute <b>userSource</b>.
+ */
+ public int getUserSource( ) {
+ return this.userSource;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>notes</b>.
+ * You cannot set null to the attribute.
+ * @param notes Value to set member attribute <b>notes</b>
+ */
+ public void setNotes( String notes ) {
+ this.notes = notes;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>notes</b>
+ * @return String - value of member attribute <b>notes</b>.
+ */
+ public String getNotes( ) {
+ return this.notes;
+ }
+
+ /**
+ * This return the bean content in string format
+ * @return formatedStr
+ */
+ @Override
+ public String toString( ) {
+ String str = "XXPortalUser={";
+ str += super.toString();
+ str += "firstName={" + firstName + "} ";
+ str += "lastName={" + lastName + "} ";
+ str += "publicScreenName={" + publicScreenName + "} ";
+ str += "loginId={" + loginId + "} ";
+ str += "password={***length=" + (password == null? 0 : password.length()) + "***} ";
+ str += "emailAddress={" + emailAddress + "} ";
+ str += "status={" + status + "} ";
+ str += "userSource={" + userSource + "} ";
+ str += "notes={" + notes + "} ";
+ str += "}";
+ return str;
+ }
+
+ /**
+ * Checks for all attributes except referenced db objects
+ * @return true if all attributes match
+ */
+ @Override
+ public boolean equals( Object obj) {
+ if ( !super.equals(obj) ) {
+ return false;
+ }
+ XXPortalUser other = (XXPortalUser) obj;
+ if ((this.firstName == null && other.firstName != null) || (this.firstName != null && !this.firstName.equals(other.firstName))) {
+ return false;
+ }
+ if ((this.lastName == null && other.lastName != null) || (this.lastName != null && !this.lastName.equals(other.lastName))) {
+ return false;
+ }
+ if ((this.publicScreenName == null && other.publicScreenName != null) || (this.publicScreenName != null && !this.publicScreenName.equals(other.publicScreenName))) {
+ return false;
+ }
+ if ((this.loginId == null && other.loginId != null) || (this.loginId != null && !this.loginId.equals(other.loginId))) {
+ return false;
+ }
+ if ((this.password == null && other.password != null) || (this.password != null && !this.password.equals(other.password))) {
+ return false;
+ }
+ if ((this.emailAddress == null && other.emailAddress != null) || (this.emailAddress != null && !this.emailAddress.equals(other.emailAddress))) {
+ return false;
+ }
+ if( this.status != other.status ) return false;
+ if( this.userSource != other.userSource ) return false;
+ if ((this.notes == null && other.notes != null) || (this.notes != null && !this.notes.equals(other.notes))) {
+ return false;
+ }
+ return true;
+ }
+ public static String getEnumName(String fieldName ) {
+ if( fieldName.equals("status") ) {
+ return "CommonEnums.ActivationStatus";
+ }
+ if( fieldName.equals("userSource") ) {
+ return "CommonEnums.UserSource";
+ }
+ //Later TODO
+ //return super.getEnumName(fieldName);
+ return null;
+ }
+
+}
[08/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/biz/AssetMgrBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/AssetMgrBase.java b/security-admin/src/main/java/org/apache/ranger/biz/AssetMgrBase.java
new file mode 100644
index 0000000..55320b8
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/biz/AssetMgrBase.java
@@ -0,0 +1,174 @@
+/*
+ * 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.biz;
+
+import org.apache.ranger.common.*;
+import org.apache.ranger.service.*;
+import org.apache.ranger.view.*;
+import org.springframework.beans.factory.annotation.Autowired;
+public class AssetMgrBase {
+
+ @Autowired
+ RESTErrorUtil restErrorUtil;
+
+ @Autowired
+ XAssetService xAssetService;
+
+ @Autowired
+ XResourceService xResourceService;
+
+ @Autowired
+ XCredentialStoreService xCredentialStoreService;
+
+ @Autowired
+ XPolicyExportAuditService xPolicyExportAuditService;
+ public VXAsset getXAsset(Long id){
+ return (VXAsset)xAssetService.readResource(id);
+ }
+
+ public VXAsset createXAsset(VXAsset vXAsset){
+ vXAsset = (VXAsset)xAssetService.createResource(vXAsset);
+ return vXAsset;
+ }
+
+ public VXAsset updateXAsset(VXAsset vXAsset) {
+ vXAsset = (VXAsset)xAssetService.updateResource(vXAsset);
+ return vXAsset;
+ }
+
+ public void deleteXAsset(Long id, boolean force) {
+ if (force) {
+ xAssetService.deleteResource(id);
+ } else {
+ throw restErrorUtil.createRESTException(
+ "serverMsg.modelMgrBaseDeleteModel",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ }
+
+ public VXAssetList searchXAssets(SearchCriteria searchCriteria) {
+ return xAssetService.searchXAssets(searchCriteria);
+ }
+
+ public VXLong getXAssetSearchCount(SearchCriteria searchCriteria) {
+ return xAssetService.getSearchCount(searchCriteria,
+ xAssetService.searchFields);
+ }
+
+ public VXResource getXResource(Long id){
+ return (VXResource)xResourceService.readResource(id);
+ }
+
+ public VXResource createXResource(VXResource vXResource){
+ vXResource = (VXResource)xResourceService.createResource(vXResource);
+ return vXResource;
+ }
+
+ public VXResource updateXResource(VXResource vXResource) {
+ vXResource = (VXResource)xResourceService.updateResource(vXResource);
+ return vXResource;
+ }
+
+ public void deleteXResource(Long id, boolean force) {
+ if (force) {
+ xResourceService.deleteResource(id);
+ } else {
+ throw restErrorUtil.createRESTException(
+ "serverMsg.modelMgrBaseDeleteModel",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ }
+
+ public VXResourceList searchXResources(SearchCriteria searchCriteria) {
+ return xResourceService.searchXResources(searchCriteria);
+ }
+
+ public VXLong getXResourceSearchCount(SearchCriteria searchCriteria) {
+ return xResourceService.getSearchCount(searchCriteria,
+ xResourceService.searchFields);
+ }
+
+ public VXCredentialStore getXCredentialStore(Long id){
+ return (VXCredentialStore)xCredentialStoreService.readResource(id);
+ }
+
+ public VXCredentialStore createXCredentialStore(VXCredentialStore vXCredentialStore){
+ vXCredentialStore = (VXCredentialStore)xCredentialStoreService.createResource(vXCredentialStore);
+ return vXCredentialStore;
+ }
+
+ public VXCredentialStore updateXCredentialStore(VXCredentialStore vXCredentialStore) {
+ vXCredentialStore = (VXCredentialStore)xCredentialStoreService.updateResource(vXCredentialStore);
+ return vXCredentialStore;
+ }
+
+ public void deleteXCredentialStore(Long id, boolean force) {
+ if (force) {
+ xCredentialStoreService.deleteResource(id);
+ } else {
+ throw restErrorUtil.createRESTException(
+ "serverMsg.modelMgrBaseDeleteModel",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ }
+
+ public VXCredentialStoreList searchXCredentialStores(SearchCriteria searchCriteria) {
+ return xCredentialStoreService.searchXCredentialStores(searchCriteria);
+ }
+
+ public VXLong getXCredentialStoreSearchCount(SearchCriteria searchCriteria) {
+ return xCredentialStoreService.getSearchCount(searchCriteria,
+ xCredentialStoreService.searchFields);
+ }
+
+ public VXPolicyExportAudit getXPolicyExportAudit(Long id){
+ return (VXPolicyExportAudit)xPolicyExportAuditService.readResource(id);
+ }
+
+ public VXPolicyExportAudit createXPolicyExportAudit(VXPolicyExportAudit vXPolicyExportAudit){
+ vXPolicyExportAudit = (VXPolicyExportAudit)xPolicyExportAuditService.createResource(vXPolicyExportAudit);
+ return vXPolicyExportAudit;
+ }
+
+ public VXPolicyExportAudit updateXPolicyExportAudit(VXPolicyExportAudit vXPolicyExportAudit) {
+ vXPolicyExportAudit = (VXPolicyExportAudit)xPolicyExportAuditService.updateResource(vXPolicyExportAudit);
+ return vXPolicyExportAudit;
+ }
+
+ public void deleteXPolicyExportAudit(Long id, boolean force) {
+ if (force) {
+ xPolicyExportAuditService.deleteResource(id);
+ } else {
+ throw restErrorUtil.createRESTException(
+ "serverMsg.modelMgrBaseDeleteModel",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ }
+
+ public VXPolicyExportAuditList searchXPolicyExportAudits(SearchCriteria searchCriteria) {
+ return xPolicyExportAuditService.searchXPolicyExportAudits(searchCriteria);
+ }
+
+ public VXLong getXPolicyExportAuditSearchCount(SearchCriteria searchCriteria) {
+ return xPolicyExportAuditService.getSearchCount(searchCriteria,
+ xPolicyExportAuditService.searchFields);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/biz/BaseMgr.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/BaseMgr.java b/security-admin/src/main/java/org/apache/ranger/biz/BaseMgr.java
new file mode 100644
index 0000000..be808de
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/biz/BaseMgr.java
@@ -0,0 +1,79 @@
+/*
+ * 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.biz;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.common.MessageEnums;
+import org.apache.ranger.common.RESTErrorUtil;
+import org.apache.ranger.common.XAConstants;
+import org.apache.ranger.common.db.BaseDao;
+import org.apache.ranger.db.XADaoManager;
+import org.apache.ranger.entity.XXDBBase;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+@Component
+public abstract class BaseMgr {
+ static final Logger logger = Logger.getLogger(BaseMgr.class);
+
+ @Autowired
+ XADaoManager daoManager;
+
+ @Autowired
+ RESTErrorUtil restErrorUtil;
+
+ public XADaoManager getDaoManager() {
+ return daoManager;
+ }
+
+ public void deleteEntity(BaseDao<? extends XXDBBase> baseDao, Long id,
+ String entityName) {
+ XXDBBase entity = baseDao.getById(id);
+ if (entity != null) {
+ try {
+ baseDao.remove(id);
+ } catch (Exception e) {
+ logger.error("Error deleting " + entityName + ". Id=" + id, e);
+ throw restErrorUtil.createRESTException("This " + entityName
+ + " can't be deleted",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_STATE, id, null, ""
+ + id + ", error=" + e.getMessage());
+ }
+ } else {
+ // Return without error
+ logger.info("Delete ignored for non-existent " + entityName
+ + " id=" + id);
+ }
+ }
+
+ /**
+ * @param objectClassType
+ */
+ protected void validateClassType(int objectClassType) {
+ // objectClassType
+ restErrorUtil.validateMinMax(objectClassType, 1,
+ XAConstants.ClassTypes_MAX, "Invalid classType", null,
+ "objectClassType");
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/biz/HadoopFSMgr.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/HadoopFSMgr.java b/security-admin/src/main/java/org/apache/ranger/biz/HadoopFSMgr.java
new file mode 100644
index 0000000..86e2311
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/biz/HadoopFSMgr.java
@@ -0,0 +1,83 @@
+/*
+ * 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.biz;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.hadoop.client.HadoopFS;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Component;
+
+/**
+ *
+ *
+ */
+
+@Component
+@Scope("singleton")
+public class HadoopFSMgr {
+
+ private HadoopFS fs;
+ private String dataSource;
+ private static Logger logger = Logger.getLogger(HadoopFSMgr.class);
+
+ public HadoopFSMgr() {
+ init();
+ }
+
+ public HadoopFSMgr(String dataSource) {
+ this.dataSource = dataSource;
+ init();
+ }
+
+ private void init() {
+ try {
+// if (dataSource != null) {
+// fs = new HadoopFS(dataSource);
+// } else {
+// fs = new HadoopFS("hadoopdev");
+// }
+ } catch (Exception e) {
+ logger.error("Error connecting hive client", e);
+ }
+ }
+
+ protected HadoopFS getInstance(String dataSourceName) {
+ if (dataSourceName == null) {
+ logger.info("Hadoop client name not provided.");
+ return fs;
+ } else {
+ if (fs.getDataSource() != null) {
+ if (fs.getDataSource().equalsIgnoreCase(dataSourceName)) {
+ return fs;
+ } else {
+ fs = new HadoopFS(dataSourceName);
+ return fs;
+ }
+ } else {
+ fs = new HadoopFS(dataSourceName);
+ return fs;
+ }
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/biz/HiveFSMgr.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/HiveFSMgr.java b/security-admin/src/main/java/org/apache/ranger/biz/HiveFSMgr.java
new file mode 100644
index 0000000..e6924ea
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/biz/HiveFSMgr.java
@@ -0,0 +1,83 @@
+/*
+ * 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.biz;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.hive.client.HiveClient;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Component;
+
+/**
+ *
+ */
+
+// @Component
+// @Scope("singleton")
+
+public class HiveFSMgr {
+
+ private HiveClient fs;
+ private String dataSource;
+ private static Logger logger = Logger.getLogger(HiveFSMgr.class);
+
+ public HiveFSMgr() {
+ init();
+ }
+
+ public HiveFSMgr(String dataSource) {
+ this.dataSource = dataSource;
+ init();
+ }
+
+ private void init() {
+ try {
+ if (dataSource != null) {
+ fs = new HiveClient(dataSource);
+ } else {
+ fs = new HiveClient("dev-hive");
+ }
+ } catch (Exception e) {
+ logger.error("Error connecting hive client", e);
+ }
+ }
+
+ protected HiveClient getInstance(String dataSourceName) {
+ if (dataSourceName == null) {
+ logger.info("Hive client name not provided.");
+ return fs;
+ } else {
+ if (fs.getDataSource() != null) {
+ if (fs.getDataSource().equalsIgnoreCase(dataSourceName)) {
+ return fs;
+ } else {
+ fs = new HiveClient(dataSourceName);
+ return fs;
+ }
+ } else {
+ fs = new HiveClient(dataSourceName);
+ return fs;
+ }
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/biz/SessionMgr.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/SessionMgr.java b/security-admin/src/main/java/org/apache/ranger/biz/SessionMgr.java
new file mode 100644
index 0000000..f273f2b
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/biz/SessionMgr.java
@@ -0,0 +1,340 @@
+/*
+ * 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.biz;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.common.DateUtil;
+import org.apache.ranger.common.HTTPUtil;
+import org.apache.ranger.common.MessageEnums;
+import org.apache.ranger.common.RESTErrorUtil;
+import org.apache.ranger.common.SearchCriteria;
+import org.apache.ranger.common.StringUtil;
+import org.apache.ranger.common.UserSessionBase;
+import org.apache.ranger.common.XACommonEnums;
+import org.apache.ranger.common.XAConstants;
+import org.apache.ranger.db.XADaoManager;
+import org.apache.ranger.entity.XXAuthSession;
+import org.apache.ranger.entity.XXPortalUser;
+import org.apache.ranger.entity.XXPortalUserRole;
+import org.apache.ranger.security.context.XAContextHolder;
+import org.apache.ranger.security.context.XASecurityContext;
+import org.apache.ranger.service.AuthSessionService;
+import org.apache.ranger.util.RestUtil;
+import org.apache.ranger.view.VXAuthSession;
+import org.apache.ranger.view.VXAuthSessionList;
+import org.apache.ranger.view.VXLong;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.web.authentication.WebAuthenticationDetails;
+import org.springframework.stereotype.Component;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+
+@Component
+@Transactional
+public class SessionMgr {
+
+ static final Logger logger = Logger.getLogger(SessionMgr.class);
+
+ @Autowired
+ RESTErrorUtil restErrorUtil;
+
+ @Autowired
+ XADaoManager daoManager;
+
+ @Autowired
+ AuthSessionService authSessionService;
+
+ @Autowired
+ HTTPUtil httpUtil;
+
+ @Autowired
+ StringUtil stringUtil;
+
+ public SessionMgr() {
+ logger.debug("SessionManager created");
+ }
+
+ public UserSessionBase processSuccessLogin(int authType, String userAgent) {
+ return processSuccessLogin(authType, userAgent, null);
+ }
+
+ public UserSessionBase processSuccessLogin(int authType, String userAgent,
+ HttpServletRequest httpRequest) {
+ boolean newSessionCreation = true;
+ UserSessionBase userSession = null;
+
+ XASecurityContext context = XAContextHolder.getSecurityContext();
+ if (context != null) {
+ userSession = context.getUserSession();
+ }
+
+ Authentication authentication = SecurityContextHolder.getContext()
+ .getAuthentication();
+ WebAuthenticationDetails details = (WebAuthenticationDetails) authentication
+ .getDetails();
+
+ String currentLoginId = authentication.getName();
+ if (userSession != null) {
+ if (validateUserSession(userSession, currentLoginId)) {
+ newSessionCreation = false;
+ }
+ }
+
+ if (newSessionCreation) {
+ // Need to build the UserSession
+ XXPortalUser gjUser = daoManager.getXXPortalUser().findByLoginId(currentLoginId);
+ if (gjUser == null) {
+ logger.error(
+ "Error getting user for loginId=" + currentLoginId,
+ new Exception());
+ return null;
+ }
+
+ XXAuthSession gjAuthSession = new XXAuthSession();
+ gjAuthSession.setLoginId(currentLoginId);
+ gjAuthSession.setUserId(gjUser.getId());
+ gjAuthSession.setAuthTime(DateUtil.getUTCDate());
+ gjAuthSession.setAuthStatus(XXAuthSession.AUTH_STATUS_SUCCESS);
+ gjAuthSession.setAuthType(authType);
+ if (details != null) {
+ gjAuthSession.setExtSessionId(details.getSessionId());
+ gjAuthSession.setRequestIP(details.getRemoteAddress());
+ }
+
+ if (userAgent != null) {
+ gjAuthSession.setRequestUserAgent(userAgent);
+ }
+ gjAuthSession.setDeviceType(httpUtil.getDeviceType(userAgent));
+ gjAuthSession = storeAuthSession(gjAuthSession);
+
+ userSession = new UserSessionBase();
+ userSession.setXXPortalUser(gjUser);
+ userSession.setXXAuthSession(gjAuthSession);
+ resetUserSessionForProfiles(userSession);
+
+ if (details != null) {
+ logger.info("Login Success: loginId=" + currentLoginId
+ + ", sessionId=" + gjAuthSession.getId()
+ + ", sessionId=" + details.getSessionId()
+ + ", requestId=" + details.getRemoteAddress());
+ } else {
+ logger.info("Login Success: loginId=" + currentLoginId
+ + ", sessionId=" + gjAuthSession.getId()
+ + ", details is null");
+ }
+
+ }
+
+ return userSession;
+ }
+
+ public void resetUserSessionForProfiles(UserSessionBase userSession) {
+ if (userSession == null) {
+ // Nothing to reset
+ return;
+ }
+
+ // Let's get the Current User Again
+ String currentLoginId = userSession.getLoginId();
+
+ XXPortalUser gjUser = daoManager.getXXPortalUser().findByLoginId(currentLoginId);
+ userSession.setXXPortalUser(gjUser);
+
+ setUserRoles(userSession);
+
+ }
+
+ private void setUserRoles(UserSessionBase userSession) {
+
+ List<String> strRoleList = new ArrayList<String>();
+ List<XXPortalUserRole> roleList = daoManager.getXXPortalUserRole().findByUserId(
+ userSession.getUserId());
+ for (XXPortalUserRole gjUserRole : roleList) {
+ String userRole = gjUserRole.getUserRole();
+
+ strRoleList.add(userRole);
+ if (userRole.equals(XAConstants.ROLE_SYS_ADMIN)) {
+ userSession.setUserAdmin(true);
+ }
+ }
+ userSession.setUserRoleList(strRoleList);
+ }
+
+ public XXAuthSession processFailureLogin(int authStatus, int authType,
+ String loginId, String remoteAddr, String sessionId) {
+ XXAuthSession gjAuthSession = new XXAuthSession();
+ gjAuthSession.setLoginId(loginId);
+ gjAuthSession.setUserId(null);
+ gjAuthSession.setAuthTime(DateUtil.getUTCDate());
+ gjAuthSession.setAuthStatus(authStatus);
+ gjAuthSession.setAuthType(authType);
+ gjAuthSession.setDeviceType(XACommonEnums.DEVICE_UNKNOWN);
+ gjAuthSession.setExtSessionId(sessionId);
+ gjAuthSession.setRequestIP(remoteAddr);
+ gjAuthSession.setRequestUserAgent(null);
+
+ gjAuthSession = storeAuthSession(gjAuthSession);
+ return gjAuthSession;
+ }
+
+ protected boolean validateUserSession(UserSessionBase userSession,
+ String currentLoginId) {
+ if (currentLoginId
+ .equalsIgnoreCase(userSession.getXXPortalUser().getLoginId())) {
+ return true;
+ } else {
+ logger.info(
+ "loginId doesn't match loginId from HTTPSession. Will create new session. loginId="
+ + currentLoginId + ", userSession=" + userSession,
+ new Exception());
+ return false;
+ }
+ }
+
+ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
+ protected XXAuthSession storeAuthSession(XXAuthSession gjAuthSession) {
+ // daoManager.getEntityManager().getTransaction().begin();
+ XXAuthSession dbMAuthSession = daoManager.getXXAuthSession().create(
+ gjAuthSession);
+ // daoManager.getEntityManager().getTransaction().commit();
+ return dbMAuthSession;
+ }
+
+ // non-WEB processing
+ public UserSessionBase processStandaloneSuccessLogin(int authType,
+ String ipAddress) {
+ Authentication authentication = SecurityContextHolder.getContext()
+ .getAuthentication();
+
+ String currentLoginId = authentication.getName();
+
+ // Need to build the UserSession
+ XXPortalUser gjUser = daoManager.getXXPortalUser().findByLoginId(currentLoginId);
+ if (gjUser == null) {
+ logger.error("Error getting user for loginId=" + currentLoginId,
+ new Exception());
+ return null;
+ }
+
+ XXAuthSession gjAuthSession = new XXAuthSession();
+ gjAuthSession.setLoginId(currentLoginId);
+ gjAuthSession.setUserId(gjUser.getId());
+ gjAuthSession.setAuthTime(DateUtil.getUTCDate());
+ gjAuthSession.setAuthStatus(XXAuthSession.AUTH_STATUS_SUCCESS);
+ gjAuthSession.setAuthType(authType);
+ gjAuthSession.setDeviceType(XACommonEnums.DEVICE_UNKNOWN);
+ gjAuthSession.setExtSessionId(null);
+ gjAuthSession.setRequestIP(ipAddress);
+ gjAuthSession.setRequestUserAgent(null);
+
+ gjAuthSession = storeAuthSession(gjAuthSession);
+
+ UserSessionBase userSession = new UserSessionBase();
+ userSession.setXXPortalUser(gjUser);
+ userSession.setXXAuthSession(gjAuthSession);
+
+ // create context with user-session and set in thread-local
+ XASecurityContext context = new XASecurityContext();
+ context.setUserSession(userSession);
+ XAContextHolder.setSecurityContext(context);
+
+ resetUserSessionForProfiles(userSession);
+
+ return userSession;
+ }
+
+ /**
+ * @param searchCriteria
+ * @return
+ */
+ public VXAuthSessionList searchAuthSessions(SearchCriteria searchCriteria) {
+
+ if (searchCriteria != null && searchCriteria.getParamList() != null
+ && searchCriteria.getParamList().size() > 0) {
+
+ int clientTimeOffsetInMinute=RestUtil.getClientTimeOffset();
+ java.util.Date temp = null;
+ DateUtil dateUtil = new DateUtil();
+ if (searchCriteria.getParamList().containsKey("startDate")) {
+ temp = (java.util.Date) searchCriteria.getParamList().get(
+ "startDate");
+ temp = dateUtil.getDateFromGivenDate(temp, 0, 0, 0, 0);
+ temp = dateUtil.addTimeOffset(temp, clientTimeOffsetInMinute);
+ searchCriteria.getParamList().put("startDate", temp);
+ }
+ if (searchCriteria.getParamList().containsKey("endDate")) {
+ temp = (java.util.Date) searchCriteria.getParamList().get(
+ "endDate");
+ temp = dateUtil.getDateFromGivenDate(temp, 0, 23, 59, 59);
+ temp = dateUtil.addTimeOffset(temp, clientTimeOffsetInMinute);
+ searchCriteria.getParamList().put("endDate", temp);
+ }
+ }
+
+ return authSessionService.search(searchCriteria);
+ }
+
+ public VXLong countAuthSessions(SearchCriteria searchCriteria) {
+ return authSessionService.getSearchCount(searchCriteria,
+ AuthSessionService.AUTH_SESSION_SEARCH_FLDS);
+ }
+
+ public VXAuthSession getAuthSession(Long id) {
+ return authSessionService.readResource(id);
+ }
+
+ public VXAuthSession getAuthSessionBySessionId(String authSessionId) {
+ if(stringUtil.isEmpty(authSessionId)){
+ throw restErrorUtil.createRESTException("Please provide the auth session id.",
+ MessageEnums.INVALID_INPUT_DATA);
+ }
+
+ XXAuthSession xXAuthSession = daoManager.getXXAuthSession()
+ .getAuthSessionBySessionId(authSessionId);
+
+ if(xXAuthSession==null){
+ throw restErrorUtil.createRESTException("Please provide a valid "
+ + "session id.", MessageEnums.INVALID_INPUT_DATA);
+ }
+
+ VXAuthSession vXAuthSession = authSessionService.populateViewBean(xXAuthSession);
+ return vXAuthSession;
+ }
+
+ public boolean isValidXAUser(String loginId) {
+ XXPortalUser pUser = daoManager.getXXPortalUser().findByLoginId(loginId);
+ if (pUser == null) {
+ logger.error("Error getting user for loginId=" + loginId);
+ return false;
+ } else {
+ logger.info(loginId+" is a valid user");
+ return true;
+ }
+
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/biz/UserMgr.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/UserMgr.java b/security-admin/src/main/java/org/apache/ranger/biz/UserMgr.java
new file mode 100644
index 0000000..648d80a
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/biz/UserMgr.java
@@ -0,0 +1,1149 @@
+/*
+ * 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.biz;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+
+import javax.persistence.Query;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.common.AppConstants;
+import org.apache.ranger.common.ContextUtil;
+import org.apache.ranger.common.DateUtil;
+import org.apache.ranger.common.GUIDUtil;
+import org.apache.ranger.common.MessageEnums;
+import org.apache.ranger.common.RESTErrorUtil;
+import org.apache.ranger.common.SearchCriteria;
+import org.apache.ranger.common.SearchUtil;
+import org.apache.ranger.common.StringUtil;
+import org.apache.ranger.common.UserSessionBase;
+import org.apache.ranger.common.XACommonEnums;
+import org.apache.ranger.common.XAConfigUtil;
+import org.apache.ranger.common.XAConstants;
+import org.apache.ranger.db.XADaoManager;
+import org.apache.ranger.entity.XXPortalUser;
+import org.apache.ranger.entity.XXPortalUserRole;
+import org.apache.ranger.entity.XXTrxLog;
+import org.apache.ranger.service.XPortalUserService;
+import org.apache.ranger.view.VXPasswordChange;
+import org.apache.ranger.view.VXPortalUser;
+import org.apache.ranger.view.VXPortalUserList;
+import org.apache.ranger.view.VXResponse;
+import org.apache.ranger.view.VXString;
+import org.apache.velocity.Template;
+import org.apache.velocity.app.VelocityEngine;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
+import org.springframework.stereotype.Component;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+
+@Component
+public class UserMgr {
+
+ static final Logger logger = Logger.getLogger(UserMgr.class);
+ private static final Md5PasswordEncoder md5Encoder = new Md5PasswordEncoder();
+
+ @Autowired
+ XADaoManager daoManager;
+
+ @Autowired
+ RESTErrorUtil restErrorUtil;
+
+ @Autowired
+ StringUtil stringUtil;
+
+ @Autowired
+ SearchUtil searchUtil;
+
+ @Autowired
+ XABizUtil msBizUtil;
+
+ @Autowired
+ SessionMgr sessionMgr;
+
+ @Autowired
+ VelocityEngine velocityEngine;
+ Template t;
+
+ @Autowired
+ DateUtil dateUtil;
+
+ @Autowired
+ XAConfigUtil configUtil;
+
+ @Autowired
+ XPortalUserService xPortalUserService;
+
+ String publicRoles[] = new String[] { XAConstants.ROLE_USER,
+ XAConstants.ROLE_OTHER };
+
+ private static final List<String> DEFAULT_ROLE_LIST = new ArrayList<String>(
+ 1);
+
+ private static final List<String> VALID_ROLE_LIST = new ArrayList<String>(2);
+
+ static {
+ DEFAULT_ROLE_LIST.add(XAConstants.ROLE_USER);
+ VALID_ROLE_LIST.add(XAConstants.ROLE_SYS_ADMIN);
+ VALID_ROLE_LIST.add(XAConstants.ROLE_USER);
+ }
+
+ public UserMgr() {
+ if (logger.isDebugEnabled()) {
+ logger.debug("UserMgr()");
+ }
+ }
+
+ public XXPortalUser createUser(VXPortalUser userProfile, int userStatus,
+ Collection<String> userRoleList) {
+ XXPortalUser user = mapVXPortalUserToXXPortalUser(userProfile);
+ user = createUser(user, userStatus, userRoleList);
+
+ return user;
+ }
+
+ public XXPortalUser createUser(XXPortalUser user, int userStatus,
+ Collection<String> userRoleList) {
+ user.setStatus(userStatus);
+ String saltEncodedpasswd = encrypt(user.getLoginId(),
+ user.getPassword());
+ user.setPassword(saltEncodedpasswd);
+ user = daoManager.getXXPortalUser().create(user);
+
+ // Create the UserRole for this user
+ List<XXPortalUserRole> gjUserRoleList = new ArrayList<XXPortalUserRole>();
+ if (userRoleList != null) {
+ for (String userRole : userRoleList) {
+ XXPortalUserRole gjUserRole = addUserRole(user.getId(), userRole);
+ if (gjUserRole != null) {
+ gjUserRoleList.add(gjUserRole);
+ }
+ }
+ }
+
+ return user;
+ }
+
+ public XXPortalUser createUser(VXPortalUser userProfile, int userStatus) {
+ ArrayList<String> roleList = new ArrayList<String>();
+ Collection<String> reqRoleList = userProfile.getUserRoleList();
+ if (reqRoleList != null && reqRoleList.size()>0) {
+ for (String role : reqRoleList) {
+ roleList.add(role);
+ }
+ }else{
+ roleList.add(XAConstants.ROLE_USER);
+ }
+
+ return createUser(userProfile, userStatus, roleList);
+ }
+
+ /**
+ * @param userProfile
+ * @return
+ */
+ public XXPortalUser updateUser(VXPortalUser userProfile) {
+ XXPortalUser gjUser = daoManager.getXXPortalUser().getById(
+ userProfile.getId());
+
+ if (gjUser == null) {
+ logger.error("updateUser(). User not found. userProfile="
+ + userProfile);
+ return null;
+ }
+
+ checkAccess(gjUser);
+
+ boolean updateUser = false;
+ // Selectively update fields
+
+ // status
+ if (userProfile.getStatus() != gjUser.getStatus()) {
+ updateUser = true;
+ }
+
+ // Allowing email address update even when its set to empty.
+ // emailAddress
+ String emailAddress = userProfile.getEmailAddress();
+ if (stringUtil.isEmpty(emailAddress)) {
+ String randomString = GUIDUtil.genGUI();
+ userProfile.setEmailAddress(randomString);
+ updateUser = true;
+ } else {
+ if (stringUtil.validateEmail(emailAddress)) {
+ XXPortalUser checkUser = daoManager.getXXPortalUser()
+ .findByEmailAddress(emailAddress);
+ if (checkUser != null) {
+ String loginId = userProfile.getLoginId();
+ if (loginId == null) {
+ throw restErrorUtil.createRESTException(
+ "Invalid user, please provide valid "
+ + "username.",
+ MessageEnums.INVALID_INPUT_DATA);
+ } else if (!loginId.equals(checkUser.getLoginId())) {
+ throw restErrorUtil
+ .createRESTException(
+ "The email address "
+ + "you've provided already exists in system.",
+ MessageEnums.INVALID_INPUT_DATA);
+ } else {
+ userProfile.setEmailAddress(emailAddress);
+ updateUser = true;
+ }
+ } else {
+ userProfile.setEmailAddress(emailAddress);
+ updateUser = true;
+ }
+ } else {
+ throw restErrorUtil.createRESTException(
+ "Please provide valid email address.",
+ MessageEnums.INVALID_INPUT_DATA);
+ }
+ }
+
+ // loginId
+ // if (!stringUtil.isEmpty(userProfile.getLoginId())
+ // && !userProfile.getLoginId().equals(gjUser.getLoginId())) {
+ // gjUser.setLoginId(userProfile.getLoginId());
+ // updateUser = true;
+ // }
+
+ // firstName
+ if (!stringUtil.isEmpty(userProfile.getFirstName())
+ && !userProfile.getFirstName().equals(gjUser.getFirstName())) {
+ userProfile.setFirstName(stringUtil.toCamelCaseAllWords(userProfile
+ .getFirstName()));
+ updateUser = true;
+ }
+
+ // lastName allowed to be empty
+ if (userProfile.getLastName() != null
+ && !userProfile.getLastName().equals(gjUser.getLastName())) {
+ userProfile.setLastName(stringUtil.toCamelCaseAllWords(userProfile
+ .getLastName()));
+ updateUser = true;
+ }
+
+ // publicScreenName
+ if (!stringUtil.isEmpty(userProfile.getPublicScreenName())
+ && !userProfile.getPublicScreenName().equals(
+ gjUser.getPublicScreenName())) {
+ userProfile.setPublicScreenName(userProfile.getFirstName() + " "
+ + userProfile.getLastName());
+ updateUser = true;
+ }
+
+ // notes
+ /*if (!stringUtil.isEmpty(userProfile.getNotes())
+ && !userProfile.getNotes().equalsIgnoreCase(gjUser.getNotes())) {
+ updateUser = true;
+ }*/
+
+ // userRoleList
+ updateRoles(userProfile.getId(), userProfile.getUserRoleList());
+
+ if (updateUser) {
+
+ List<XXTrxLog> trxLogList = xPortalUserService.getTransactionLog(
+ userProfile, gjUser, "update");
+
+ userProfile.setPassword(gjUser.getPassword());
+ userProfile = xPortalUserService.updateResource(userProfile);
+ sessionMgr.resetUserSessionForProfiles(ContextUtil
+ .getCurrentUserSession());
+
+ msBizUtil.createTrxLog(trxLogList);
+ }
+
+ return gjUser;
+ }
+
+ private boolean updateRoles(Long userId, Collection<String> rolesList) {
+ boolean rolesUpdated = false;
+ if (rolesList == null || rolesList.size() == 0) {
+ return false;
+ }
+
+ // Let's first delete old roles
+ List<XXPortalUserRole> gjUserRoles = daoManager.getXXPortalUserRole().findByUserId(
+ userId);
+
+ for (XXPortalUserRole gjUserRole : gjUserRoles) {
+ boolean found = false;
+ for (String userRole : rolesList) {
+ if (gjUserRole.getUserRole().equalsIgnoreCase(userRole)) {
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ if (deleteUserRole(userId, gjUserRole)) {
+ rolesUpdated = true;
+ }
+ }
+ }
+
+ // Let's add new roles
+ for (String userRole : rolesList) {
+ boolean found = false;
+ for (XXPortalUserRole gjUserRole : gjUserRoles) {
+ if (gjUserRole.getUserRole().equalsIgnoreCase(userRole)) {
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ if (addUserRole(userId, userRole) != null) {
+ rolesUpdated = true;
+ }
+ }
+ }
+ return rolesUpdated;
+ }
+
+ /**
+ * @param userId
+ * @param vStrings
+ */
+ public void setUserRoles(Long userId, List<VXString> vStringRolesList) {
+ List<String> stringRolesList = new ArrayList<String>();
+ for (VXString vXString : vStringRolesList) {
+ stringRolesList.add(vXString.getValue());
+ }
+ updateRoles(userId, stringRolesList);
+ }
+
+ /**
+ * @param pwdChange
+ * @return
+ */
+ public VXResponse changePassword(VXPasswordChange pwdChange) {
+ // First let's get the XXPortalUser for the current logged in user
+ String currentUserLoginId = ContextUtil.getCurrentUserLoginId();
+ XXPortalUser gjUserCurrent = daoManager.getXXPortalUser()
+ .findByLoginId(currentUserLoginId);
+
+ String encryptedOldPwd = encrypt(gjUserCurrent.getLoginId(),
+ pwdChange.getOldPassword());
+
+ VXResponse ret = new VXResponse();
+
+ if (!stringUtil.equals(encryptedOldPwd, gjUserCurrent.getPassword())) {
+ logger.info("changePassword(). Invalid old password. userId="
+ + pwdChange.getId());
+
+ throw restErrorUtil.createRESTException(
+ "serverMsg.userMgrPassword",
+ MessageEnums.OPER_NO_PERMISSION, null, null,
+ "" + pwdChange.getId());
+ }
+
+ // Get the user for whom we want to change the password
+ XXPortalUser gjUser = daoManager.getXXPortalUser().getById(
+ pwdChange.getId());
+ if (gjUser == null) {
+ logger.warn("SECURITY:changePassword(). User not found. userId="
+ + pwdChange.getId());
+ throw restErrorUtil.createRESTException(
+ "serverMsg.userMgrInvalidUser",
+ MessageEnums.DATA_NOT_FOUND, null, null,
+ "" + pwdChange.getId());
+ }
+
+ if (!stringUtil
+ .validatePassword(
+ pwdChange.getUpdPassword(),
+ new String[] { gjUser.getFirstName(),
+ gjUser.getLastName(), gjUser.getLoginId(),
+ gjUserCurrent.getFirstName(),
+ gjUserCurrent.getLastName(),
+ gjUserCurrent.getLoginId() })) {
+ logger.warn("SECURITY:changePassword(). Invalid new password. userId="
+ + pwdChange.getId());
+
+ throw restErrorUtil.createRESTException(
+ "serverMsg.userMgrNewPassword",
+ MessageEnums.INVALID_PASSWORD, null, null,
+ "" + pwdChange.getId());
+ }
+
+ String encryptedNewPwd = encrypt(gjUser.getLoginId(),
+ pwdChange.getUpdPassword());
+
+ String currentPassword = gjUser.getPassword();
+
+ if (!encryptedNewPwd.equals(currentPassword)) {
+
+ List<XXTrxLog> trxLogList = new ArrayList<XXTrxLog>();
+ XXTrxLog xTrxLog = new XXTrxLog();
+
+ xTrxLog.setAttributeName("Password");
+ xTrxLog.setPreviousValue(currentPassword);
+ xTrxLog.setNewValue(encryptedNewPwd);
+ xTrxLog.setAction("password change");
+ xTrxLog.setObjectClassType(AppConstants.CLASS_TYPE_PASSWORD_CHANGE);
+ xTrxLog.setObjectId(pwdChange.getId());
+ xTrxLog.setObjectName(pwdChange.getLoginId());
+ trxLogList.add(xTrxLog);
+
+ msBizUtil.createTrxLog(trxLogList);
+
+ gjUser.setPassword(encryptedNewPwd);
+ gjUser = daoManager.getXXPortalUser().update(gjUser);
+
+ ret.setMsgDesc("Password successfully updated");
+ ret.setStatusCode(VXResponse.STATUS_SUCCESS);
+ } else {
+ ret.setMsgDesc("Password update failed");
+ ret.setStatusCode(VXResponse.STATUS_ERROR);
+ throw restErrorUtil.createRESTException(
+ "serverMsg.userMgrOldPassword",
+ MessageEnums.INVALID_INPUT_DATA, gjUser.getId(),
+ "password", gjUser.toString());
+ }
+ return ret;
+ }
+
+ /**
+ * @param gjUser
+ * @param changeEmail
+ * @return
+ */
+ public VXPortalUser changeEmailAddress(XXPortalUser gjUser,
+ VXPasswordChange changeEmail) {
+
+ if (gjUser.getEmailAddress() != null) {
+ throw restErrorUtil.createRESTException(
+ "serverMsg.userMgrEmailChange",
+ MessageEnums.OPER_NO_PERMISSION, null, null, ""
+ + changeEmail);
+ }
+
+ String encryptedOldPwd = encrypt(gjUser.getLoginId(),
+ changeEmail.getOldPassword());
+
+ if (!stringUtil.validateEmail(changeEmail.getEmailAddress())) {
+ logger.info("Invalid email address." + changeEmail);
+ throw restErrorUtil.createRESTException(
+ "serverMsg.userMgrInvalidEmail",
+ MessageEnums.INVALID_INPUT_DATA, changeEmail.getId(),
+ "emailAddress", changeEmail.toString());
+
+ }
+
+ if (!stringUtil.equals(encryptedOldPwd, gjUser.getPassword())) {
+ logger.info("changeEmailAddress(). Invalid password. changeEmail="
+ + changeEmail);
+
+ throw restErrorUtil.createRESTException(
+ "serverMsg.userMgrWrongPassword",
+ MessageEnums.OPER_NO_PERMISSION, null, null, ""
+ + changeEmail);
+ }
+
+ // Normalize email. Make it lower case
+ gjUser.setEmailAddress(stringUtil.normalizeEmail(changeEmail
+ .getEmailAddress()));
+
+ // loginId
+ gjUser.setLoginId(gjUser.getEmailAddress());
+
+ String saltEncodedpasswd = encrypt(gjUser.getLoginId(),
+ changeEmail.getOldPassword());
+
+ gjUser.setPassword(saltEncodedpasswd);
+
+ daoManager.getXXPortalUser().update(gjUser);
+ return mapXXPortalUserVXPortalUser(gjUser);
+ }
+
+ /**
+ * @param userId
+ */
+ public VXPortalUser deactivateUser(XXPortalUser gjUser) {
+ if (gjUser != null
+ && gjUser.getStatus() != XAConstants.ACT_STATUS_DEACTIVATED) {
+ logger.info("Marking user " + gjUser.getLoginId() + " as deleted");
+ gjUser.setStatus(XAConstants.ACT_STATUS_DEACTIVATED);
+ gjUser = daoManager.getXXPortalUser().update(gjUser);
+ return mapXXPortalUserVXPortalUser(gjUser);
+ }
+ return null;
+ }
+
+ public VXPortalUser getUserProfile(Long id) {
+ XXPortalUser user = daoManager.getXXPortalUser().getById(id);
+ if (user != null) {
+ checkAccessForRead(user);
+ return mapXXPortalUserVXPortalUser(user);
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("User not found. userId=" + id);
+ }
+ return null;
+ }
+ }
+
+ public VXPortalUser getUserProfileByLoginId() {
+ String loginId = ContextUtil.getCurrentUserLoginId();
+ return getUserProfileByLoginId(loginId);
+ }
+
+ public VXPortalUser getUserProfileByLoginId(String loginId) {
+ XXPortalUser user = daoManager.getXXPortalUser().findByLoginId(loginId);
+ if (user != null) {
+ return mapXXPortalUserVXPortalUser(user);
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("User not found. loginId=" + loginId);
+ }
+ return null;
+ }
+ }
+
+ public XXPortalUser mapVXPortalUserToXXPortalUser(VXPortalUser userProfile) {
+ XXPortalUser gjUser = new XXPortalUser();
+ gjUser.setEmailAddress(userProfile.getEmailAddress());
+ gjUser.setFirstName(userProfile.getFirstName());
+ gjUser.setLastName(userProfile.getLastName());
+ gjUser.setLoginId(userProfile.getLoginId());
+ gjUser.setPassword(userProfile.getPassword());
+ gjUser.setUserSource(userProfile.getUserSource());
+ gjUser.setPublicScreenName(userProfile.getPublicScreenName());
+ return gjUser;
+ }
+
+ /**
+ * @param user
+ * @return
+ */
+ public VXPortalUser mapXXPortalUserToVXPortalUser(XXPortalUser user,
+ Collection<String> userRoleList) {
+ if (user == null) {
+ return null;
+ }
+ UserSessionBase sess = ContextUtil.getCurrentUserSession();
+ if (sess == null) {
+ return null;
+ }
+
+ VXPortalUser userProfile = new VXPortalUser();
+ gjUserToUserProfile(user, userProfile);
+ if (sess.isUserAdmin() || sess.getXXPortalUser().getId().equals(user.getId())) {
+ if (userRoleList == null) {
+ userRoleList = new ArrayList<String>();
+ List<XXPortalUserRole> gjUserRoleList = daoManager.getXXPortalUserRole()
+ .findByParentId(user.getId());
+
+ for (XXPortalUserRole userRole : gjUserRoleList) {
+ userRoleList.add(userRole.getUserRole());
+ }
+ }
+
+ userProfile.setUserRoleList(userRoleList);
+ }
+ userProfile.setUserSource(user.getUserSource());
+ return userProfile;
+ }
+
+ private void gjUserToUserProfile(XXPortalUser user, VXPortalUser userProfile) {
+ UserSessionBase sess = ContextUtil.getCurrentUserSession();
+ if (sess == null) {
+ return;
+ }
+
+ // Is accessed by peer from the same account
+ boolean isPeer = false;
+ boolean isAccountAdmin = false;
+
+ // Admin
+ if (sess.isUserAdmin() || sess.getXXPortalUser().getId().equals(user.getId())) {
+ userProfile.setLoginId(user.getLoginId());
+ userProfile.setStatus(user.getStatus());
+ userProfile.setUserRoleList(new ArrayList<String>());
+ String emailAddress = user.getEmailAddress();
+
+ if (emailAddress != null && stringUtil.validateEmail(emailAddress)) {
+ userProfile.setEmailAddress(user.getEmailAddress());
+ }
+
+ if (sess != null) {
+ userProfile.setUserSource(sess.getAuthProvider());
+ }
+
+ List<XXPortalUserRole> gjUserRoleList = daoManager.getXXPortalUserRole()
+ .findByParentId(user.getId());
+
+ for (XXPortalUserRole gjUserRole : gjUserRoleList) {
+ userProfile.getUserRoleList().add(gjUserRole.getUserRole());
+ }
+ }
+
+ if (sess.isUserAdmin() || sess.getXXPortalUser().getId().equals(user.getId())
+ || isPeer) {
+ userProfile.setId(user.getId());
+ userProfile.setFirstName(user.getFirstName());
+ userProfile.setLastName(user.getLastName());
+ userProfile.setPublicScreenName(user.getPublicScreenName());
+ if (isAccountAdmin) {
+ userProfile.setEmailAddress(user.getEmailAddress());
+ }
+ }
+
+ }
+
+ /**
+ * Translates XXPortalUser to VUserProfile. This method should be called in the
+ * same transaction in which the XXPortalUser was retrieved from the database
+ *
+ * @param user
+ * @return
+ */
+ public VXPortalUser mapXXPortalUserVXPortalUser(XXPortalUser user) {
+ return mapXXPortalUserToVXPortalUser(user, null);
+ }
+
+ /**
+ * @param emailId
+ * @return
+ */
+ public XXPortalUser findByEmailAddress(String emailId) {
+ return daoManager.getXXPortalUser().findByEmailAddress(emailId);
+ }
+
+ public XXPortalUser findByLoginId(String loginId) {
+ return daoManager.getXXPortalUser().findByLoginId(loginId);
+ }
+
+ @Transactional(readOnly = true, propagation = Propagation.REQUIRED)
+ public Collection<String> getRolesForUser(XXPortalUser user) {
+ Collection<String> roleList = new ArrayList<String>();
+
+ Collection<XXPortalUserRole> roleCollection = daoManager.getXXPortalUserRole()
+ .findByUserId(user.getId());
+ for (XXPortalUserRole role : roleCollection) {
+ roleList.add(role.getUserRole());
+ }
+ return roleList;
+ }
+
+ /**
+ * @param searchCriteria
+ * @return
+ */
+ public VXPortalUserList searchUsers(SearchCriteria searchCriteria) {
+
+ VXPortalUserList returnList = new VXPortalUserList();
+ ArrayList<VXPortalUser> objectList = new ArrayList<VXPortalUser>();
+ String queryStr = "SELECT u FROM XXPortalUser u ";
+ String countQueryStr = "SELECT COUNT(u) FROM XXPortalUser u ";
+
+ // Get total count first
+ Query query = createUserSearchQuery(countQueryStr, null, searchCriteria);
+ Long count = (Long) query.getSingleResult();
+ if (count == null || count.longValue() == 0) {
+ return returnList;
+ }
+
+ // Get actual data
+
+ // Add sort by
+ String sortBy = searchCriteria.getSortBy();
+ String querySortBy = "u.loginId";
+ if (!stringUtil.isEmpty(sortBy)) {
+ sortBy = sortBy.trim();
+ if (sortBy.equalsIgnoreCase("userId")) {
+ querySortBy = "u.id";
+ } else if (sortBy.equalsIgnoreCase("loginId")) {
+ querySortBy = "ua.loginId";
+ } else if (sortBy.equalsIgnoreCase("emailAddress")) {
+ querySortBy = "u.emailAddress";
+ } else if (sortBy.equalsIgnoreCase("firstName")) {
+ querySortBy = "u.firstName";
+ } else if (sortBy.equalsIgnoreCase("lastName")) {
+ querySortBy = "u.lastName";
+ } else {
+ sortBy = "loginId";
+ logger.error("Invalid sortBy provided. sortBy=" + sortBy);
+ }
+ } else {
+ sortBy = "loginId";
+ }
+
+ // Default sort field
+ String sortClause = " order by " + querySortBy + " ";
+
+ // 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);
+ }
+ }
+ sortClause += querySortType;
+
+ query = createUserSearchQuery(queryStr, sortClause, searchCriteria);
+
+ // Set start index
+ query.setFirstResult(searchCriteria.getStartIndex());
+
+ searchUtil.updateQueryPageSize(query, searchCriteria);
+
+ @SuppressWarnings("rawtypes")
+ List resultList = query.getResultList();
+ // Iterate over the result list and create the return list
+ for (Object object : resultList) {
+ XXPortalUser gjUser = (XXPortalUser) object;
+ VXPortalUser userProfile = new VXPortalUser();
+ gjUserToUserProfile(gjUser, userProfile);
+ objectList.add(userProfile);
+ }
+
+ returnList.setPageSize(query.getMaxResults());
+ returnList.setSortBy(sortBy);
+ returnList.setSortType(querySortType);
+ returnList.setStartIndex(query.getFirstResult());
+ returnList.setTotalCount(count.longValue());
+ returnList.setVXPortalUsers(objectList);
+ return returnList;
+ }
+
+ /**
+ * @param queryStr
+ * @param sortClause
+ * @param searchCriteria
+ * @return
+ */
+ private Query createUserSearchQuery(String queryStr, String sortClause,
+ SearchCriteria searchCriteria) {
+ HashMap<String, Object> paramList = searchCriteria.getParamList();
+
+ String whereClause = "WHERE 1 = 1 ";
+
+ // roles
+ @SuppressWarnings("unchecked")
+ List<String> roleList = (List<String>) paramList.get("roleList");
+ if (roleList != null && roleList.size() > 0) {
+ whereClause = ", XXPortalUserRole ur WHERE u.id = ur.userId";
+ if (roleList.size() == 1) {
+ // For only one role, let's do an equal to
+ whereClause += " and ur.userRole = :role";
+ } else {
+ whereClause += " and ur.userRole in (:roleList)";
+ }
+ }
+
+ // userId
+ Long userId = (Long) paramList.get("userId");
+ if (userId != null) {
+ whereClause += " and u.id = :userId ";
+ }
+
+ // loginId
+ String loginId = (String) paramList.get("loginId");
+ if (loginId != null) {
+ whereClause += " and LOWER(u.loginId) = :loginId ";
+ }
+
+ // emailAddress
+ String emailAddress = (String) paramList.get("emailAddress");
+ if (emailAddress != null) {
+ whereClause += " and LOWER(u.emailAddress) = :emailAddress ";
+ }
+
+ // firstName
+ String firstName = (String) paramList.get("firstName");
+ if (firstName != null) {
+ whereClause += " and LOWER(u.firstName) = :firstName ";
+ }
+
+ // lastName
+ String lastName = (String) paramList.get("lastName");
+ if (lastName != null) {
+ whereClause += " and LOWER(u.lastName) = :lastName ";
+ }
+
+ // status
+ Integer status = null;
+ @SuppressWarnings("unchecked")
+ List<Integer> statusList = (List<Integer>) paramList.get("statusList");
+ if (statusList != null && statusList.size() == 1) {
+ // use == condition
+ whereClause += " and u.status = :status";
+ status = statusList.get(0);
+ } else if (statusList != null && statusList.size() > 1) {
+ // use in operator
+ whereClause += " and u.status in (:statusList) ";
+ }
+
+ // publicScreenName
+ String publicScreenName = (String) paramList.get("publicScreenName");
+ if (publicScreenName != null) {
+ whereClause += " and LOWER(u.publicScreenName) = :publicScreenName ";
+ }
+
+ // familyScreenName
+ String familyScreenName = (String) paramList.get("familyScreenName");
+ if (familyScreenName != null) {
+ whereClause += " and LOWER(u.familyScreenName) = :familyScreenName ";
+ }
+
+ if (sortClause != null) {
+ whereClause += sortClause;
+ }
+
+ Query query = daoManager.getEntityManager().createQuery(
+ queryStr + whereClause);
+
+ if (roleList != null && roleList.size() > 0) {
+ if (roleList.size() == 1) {
+ query.setParameter("role", roleList.get(0));
+ } else {
+ query.setParameter("roleList", roleList);
+ }
+ }
+
+ if (status != null) {
+ query.setParameter("status", status);
+ }
+ if (statusList != null && statusList.size() > 1) {
+ query.setParameter("statusList", statusList);
+ }
+ if (emailAddress != null) {
+ query.setParameter("emailAddress", emailAddress.toLowerCase());
+ }
+
+ // userId
+ if (userId != null) {
+ query.setParameter("userId", userId);
+ }
+ // firstName
+ if (firstName != null) {
+ query.setParameter("firstName", firstName.toLowerCase());
+ }
+ // lastName
+ if (lastName != null) {
+ query.setParameter("lastName", lastName.toLowerCase());
+ }
+
+ // loginId
+ if (loginId != null) {
+ query.setParameter("loginId", loginId.toLowerCase());
+ }
+
+ // publicScreenName
+ if (publicScreenName != null) {
+ query.setParameter("publicScreenName",
+ publicScreenName.toLowerCase());
+ }
+
+ // familyScreenName
+ if (familyScreenName != null) {
+ query.setParameter("familyScreenName",
+ familyScreenName.toLowerCase());
+ }
+
+ return query;
+ }
+
+ public boolean deleteUserRole(Long userId, String userRole) {
+ List<XXPortalUserRole> roleList = daoManager.getXXPortalUserRole().findByUserId(
+ userId);
+ for (XXPortalUserRole gjUserRole : roleList) {
+ if (gjUserRole.getUserRole().equalsIgnoreCase(userRole)) {
+ return deleteUserRole(userId, gjUserRole);
+ }
+ }
+ return false;
+ }
+
+ public boolean deleteUserRole(Long userId, XXPortalUserRole gjUserRole) {
+ /*if (XAConstants.ROLE_USER.equals(gjUserRole.getUserRole())) {
+ return false;
+ }*/
+ boolean publicRole = false;
+ for (int i = 0; i < publicRoles.length; i++) {
+ if (publicRoles[i].equalsIgnoreCase(gjUserRole.getUserRole())) {
+ publicRole = true;
+ break;
+ }
+ }
+ if (!publicRole) {
+ UserSessionBase sess = ContextUtil.getCurrentUserSession();
+ if (sess == null || !sess.isUserAdmin()) {
+ return false;
+ }
+ }
+
+ daoManager.getXXPortalUserRole().remove(gjUserRole.getId());
+ return true;
+ }
+
+ public XXPortalUserRole addUserRole(Long userId, String userRole) {
+ List<XXPortalUserRole> roleList = daoManager.getXXPortalUserRole().findByUserId(
+ userId);
+ boolean publicRole = false;
+ for (int i = 0; i < publicRoles.length; i++) {
+ if (publicRoles[i].equalsIgnoreCase(userRole)) {
+ publicRole = true;
+ break;
+ }
+ }
+ if (!publicRole) {
+ UserSessionBase sess = ContextUtil.getCurrentUserSession();
+ if (sess == null) {
+ return null;
+ }
+ // Admin
+ if (!sess.isUserAdmin()) {
+ logger.error(
+ "SECURITY WARNING: User trying to add non public role. userId="
+ + userId + ", role=" + userRole + ", session="
+ + sess.toString(), new Throwable());
+ return null;
+ }
+ }
+
+ for (XXPortalUserRole gjUserRole : roleList) {
+ if (userRole.equalsIgnoreCase(gjUserRole.getUserRole())) {
+ return gjUserRole;
+ }
+ }
+ XXPortalUserRole userRoleObj = new XXPortalUserRole();
+ userRoleObj.setUserRole(userRole.toUpperCase());
+ userRoleObj.setUserId(userId);
+ userRoleObj.setStatus(XAConstants.STATUS_ENABLED);
+ daoManager.getXXPortalUserRole().create(userRoleObj);
+
+ // If role is not OTHER, then remove OTHER
+ if (!XAConstants.ROLE_OTHER.equalsIgnoreCase(userRole)) {
+ deleteUserRole(userId, XAConstants.ROLE_OTHER);
+ }
+
+ sessionMgr.resetUserSessionForProfiles(ContextUtil
+ .getCurrentUserSession());
+ return null;
+ }
+
+ public void checkAccess(Long userId) {
+ XXPortalUser gjUser = daoManager.getXXPortalUser().getById(userId);
+ if (gjUser == null) {
+ throw restErrorUtil
+ .create403RESTException("serverMsg.userMgrWrongUser"
+ + userId);
+ }
+
+ checkAccess(gjUser);
+ }
+
+ /**
+ * @param gjUser
+ * @return
+ */
+ public void checkAccess(XXPortalUser gjUser) {
+ if (gjUser == null) {
+ throw restErrorUtil
+ .create403RESTException("serverMsg.userMgrWrongUser");
+ }
+ UserSessionBase sess = ContextUtil.getCurrentUserSession();
+ if (sess != null) {
+
+ // Admin
+ if (sess != null && sess.isUserAdmin()) {
+ return;
+ }
+
+ // Self
+ if (sess.getXXPortalUser().getId().equals(gjUser.getId())) {
+ return;
+ }
+
+ }
+ throw restErrorUtil.create403RESTException("User "
+ + " access denied. loggedInUser="
+ + (sess != null ? sess.getXXPortalUser().getId() : "Not Logged In")
+ + ", accessing user=" + gjUser.getId());
+
+ }
+
+ public void checkAccessForRead(XXPortalUser gjUser) {
+ if (gjUser == null) {
+ throw restErrorUtil
+ .create403RESTException("serverMsg.userMgrWrongUser");
+ }
+ UserSessionBase sess = ContextUtil.getCurrentUserSession();
+ if (sess != null) {
+
+ // Admin
+ if (sess != null && sess.isUserAdmin()) {
+ return;
+ }
+
+ // Self
+ if (sess.getXXPortalUser().getId().equals(gjUser.getId())) {
+ return;
+ }
+
+ }
+ throw restErrorUtil.create403RESTException("User "
+ + " access denied. loggedInUser="
+ + (sess != null ? sess.getXXPortalUser().getId() : "Not Logged In")
+ + ", accessing user=" + gjUser.getId());
+
+ }
+
+ public String encrypt(String loginId, String password) {
+ String saltEncodedpasswd = md5Encoder.encodePassword(password, loginId);
+ return saltEncodedpasswd;
+ }
+
+ public VXPortalUser createUser(VXPortalUser userProfile) {
+ XXPortalUser xXPortalUser = this
+ .createUser(userProfile, XACommonEnums.STATUS_ENABLED);
+ return mapXXPortalUserVXPortalUser(xXPortalUser);
+ }
+
+ public VXPortalUser createDefaultAccountUser(VXPortalUser userProfile) {
+ if(userProfile.getPassword()==null||userProfile.getPassword().trim().isEmpty()){
+ userProfile.setUserSource(XACommonEnums.USER_EXTERNAL);
+ }
+ // access control
+ UserSessionBase session = ContextUtil.getCurrentUserSession();
+ if (session != null) {
+ if (!session.isUserAdmin()) {
+ throw restErrorUtil.create403RESTException("User "
+ + "creation denied. LoggedInUser="
+ + (session != null ? session.getXXPortalUser().getId()
+ : "Not Logged In")
+ + " ,isn't permitted to perform the action.");
+
+ }
+ }
+
+ XXPortalUser xXPortalUser = null;
+ String loginId = userProfile.getLoginId();
+ String emailAddress = userProfile.getEmailAddress();
+
+ if (loginId != null && !loginId.isEmpty()) {
+ xXPortalUser = this.findByLoginId(loginId);
+ if (xXPortalUser == null) {
+ if (emailAddress != null && !emailAddress.isEmpty()) {
+ xXPortalUser = this.findByEmailAddress(emailAddress);
+ if (xXPortalUser == null) {
+ xXPortalUser = this.createUser(userProfile,
+ XACommonEnums.STATUS_ENABLED);
+ } else {
+ throw restErrorUtil
+ .createRESTException(
+ "The email address "
+ + emailAddress
+ + " you've provided already exists. Please try again with different "
+ + "email address.",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_STATE);
+ }
+ } else {
+ String randomEmail = GUIDUtil.genGUI();
+ userProfile.setEmailAddress(randomEmail);
+ xXPortalUser = this.createUser(userProfile,
+ XACommonEnums.STATUS_ENABLED);
+ }
+ } else {
+ /*throw restErrorUtil
+ .createRESTException(
+ "The login id "
+ + loginId
+ + " you've provided already exists. Please try again with different "
+ + "login id.",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_STATE);*/
+ }
+ }
+
+ return mapXXPortalUserToVXPortalUserForDefaultAccount(xXPortalUser);
+ }
+
+ private VXPortalUser mapXXPortalUserToVXPortalUserForDefaultAccount(XXPortalUser user) {
+
+ VXPortalUser userProfile = new VXPortalUser();
+
+ userProfile.setLoginId(user.getLoginId());
+ userProfile.setEmailAddress(user.getEmailAddress());
+ userProfile.setStatus(user.getStatus());
+ userProfile.setUserRoleList(new ArrayList<String>());
+ userProfile.setId(user.getId());
+ userProfile.setFirstName(user.getFirstName());
+ userProfile.setLastName(user.getLastName());
+ userProfile.setPublicScreenName(user.getPublicScreenName());
+ userProfile.setEmailAddress(user.getEmailAddress());
+
+ List<XXPortalUserRole> gjUserRoleList = daoManager.getXXPortalUserRole()
+ .findByParentId(user.getId());
+
+ for (XXPortalUserRole gjUserRole : gjUserRoleList) {
+ userProfile.getUserRoleList().add(gjUserRole.getUserRole());
+ }
+
+ return userProfile;
+ }
+
+ public boolean isUserInRole(Long userId, String role) {
+ XXPortalUserRole xXPortalUserRole = daoManager.getXXPortalUserRole().findByRoleUserId(
+ userId, role);
+ if (xXPortalUserRole != null) {
+ String userRole = xXPortalUserRole.getUserRole();
+ if (userRole.equalsIgnoreCase(role)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public XXPortalUser updateUserWithPass(VXPortalUser userProfile) {
+ String updatedPassword = userProfile.getPassword();
+ XXPortalUser xXPortalUser = this.updateUser(userProfile);
+
+ if (updatedPassword != null && !updatedPassword.isEmpty()) {
+ if (!stringUtil.validatePassword(updatedPassword,
+ new String[] { xXPortalUser.getFirstName(), xXPortalUser.getLastName(),
+ xXPortalUser.getLoginId() })) {
+ logger.warn("SECURITY:changePassword(). Invalid new password. userId="
+ + xXPortalUser.getId());
+
+ throw restErrorUtil.createRESTException(
+ "serverMsg.userMgrNewPassword",
+ MessageEnums.INVALID_PASSWORD, null, null,
+ "" + xXPortalUser.getId());
+ }
+
+ String encryptedNewPwd = encrypt(xXPortalUser.getLoginId(),
+ updatedPassword);
+ xXPortalUser.setPassword(encryptedNewPwd);
+ xXPortalUser = daoManager.getXXPortalUser().update(xXPortalUser);
+ }
+ return xXPortalUser;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/biz/UserMgrBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/UserMgrBase.java b/security-admin/src/main/java/org/apache/ranger/biz/UserMgrBase.java
new file mode 100644
index 0000000..568da26
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/biz/UserMgrBase.java
@@ -0,0 +1,66 @@
+/*
+ * 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.biz;
+
+import org.apache.ranger.common.*;
+import org.apache.ranger.service.*;
+import org.apache.ranger.view.*;
+import org.springframework.beans.factory.annotation.Autowired;
+public class UserMgrBase {
+
+ @Autowired
+ RESTErrorUtil restErrorUtil;
+
+ @Autowired
+ XPortalUserService xPortalUserService;
+ public VXPortalUser getXPortalUser(Long id){
+ return (VXPortalUser)xPortalUserService.readResource(id);
+ }
+
+ public VXPortalUser createXPortalUser(VXPortalUser vXPortalUser){
+ vXPortalUser = (VXPortalUser)xPortalUserService.createResource(vXPortalUser);
+ return vXPortalUser;
+ }
+
+ public VXPortalUser updateXPortalUser(VXPortalUser vXPortalUser) {
+ vXPortalUser = (VXPortalUser)xPortalUserService.updateResource(vXPortalUser);
+ return vXPortalUser;
+ }
+
+ public void deleteXPortalUser(Long id, boolean force) {
+ if (force) {
+ xPortalUserService.deleteResource(id);
+ } else {
+ throw restErrorUtil.createRESTException(
+ "serverMsg.modelMgrBaseDeleteModel",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ }
+
+ public VXPortalUserList searchXPortalUsers(SearchCriteria searchCriteria) {
+ return xPortalUserService.searchXPortalUsers(searchCriteria);
+ }
+
+ public VXLong getXPortalUserSearchCount(SearchCriteria searchCriteria) {
+ return xPortalUserService.getSearchCount(searchCriteria,
+ xPortalUserService.searchFields);
+ }
+
+}
[34/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/Crypt.java
----------------------------------------------------------------------
diff --git a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/Crypt.java b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/Crypt.java
new file mode 100644
index 0000000..ded5eb5
--- /dev/null
+++ b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/Crypt.java
@@ -0,0 +1,85 @@
+/*
+ * 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.authorization.hbase;
+
+import javax.crypto.Cipher;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+
+import org.apache.commons.codec.binary.Hex;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class Crypt {
+
+ private static final Log LOG = LogFactory.getLog("SecurityLogger." + RangerAuthorizationCoprocessor.class.getName());
+
+ private static byte[] IV = { 01, 21, 22, 86, 121, 45, 98, 28, 111, 72, 54, 39, 96, 47, 84, 13 };
+ private static final byte[] encryptionKey = "324234sdff3a7d8e".getBytes();
+ private static final String CIPHER_ALGO = "AES/CBC/PKCS5Padding";
+ private static final String CIPHER_INIT_ALGO = "AES";
+
+ private static Crypt me = null ;
+
+ private Cipher encrypter = null;
+ private Cipher descrypter = null;
+
+
+ public static Crypt getInstance() {
+ if (me == null) {
+ synchronized (Crypt.class) {
+ Crypt other = me ;
+ if (other == null) {
+ me = new Crypt() ;
+ }
+ }
+ }
+ return me ;
+ }
+
+ private Crypt() {
+ try {
+ encrypter = Cipher.getInstance(CIPHER_ALGO);
+ SecretKeySpec enckey = new SecretKeySpec(encryptionKey, CIPHER_INIT_ALGO);
+ encrypter.init(Cipher.ENCRYPT_MODE, enckey, new IvParameterSpec(IV));
+
+ descrypter = Cipher.getInstance(CIPHER_ALGO);
+ SecretKeySpec deckey = new SecretKeySpec(encryptionKey, CIPHER_INIT_ALGO);
+ descrypter.init(Cipher.DECRYPT_MODE, deckey, new IvParameterSpec(IV));
+ } catch (Throwable t) {
+ LOG.error("Unable to initialzie Encrypt/Decrypt module - Exiting from HBase", t);
+ System.exit(1);
+ }
+ }
+
+ public synchronized byte[] encrypt(byte[] plainText) throws Exception {
+ byte[] ret = encrypter.doFinal(plainText);
+ LOG.debug("Encrypted plain text: [" + new String(plainText) + "] => {" + Hex.encodeHexString(ret) + "}") ;
+ return ret ;
+ }
+
+ public synchronized byte[] decrypt(byte[] cipherText) throws Exception {
+ byte[] ret = descrypter.doFinal(cipherText);
+ LOG.debug("Decrypted From text: [" + Hex.encodeHexString(cipherText) + "] => {" + new String(ret) + "}") ;
+ return ret ;
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/HBaseAccessController.java
----------------------------------------------------------------------
diff --git a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/HBaseAccessController.java b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/HBaseAccessController.java
new file mode 100644
index 0000000..ab69712
--- /dev/null
+++ b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/HBaseAccessController.java
@@ -0,0 +1,40 @@
+/*
+ * 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.authorization.hbase;
+
+import java.util.List;
+
+import org.apache.hadoop.hbase.security.User;
+import org.apache.hadoop.hbase.security.access.Permission.Action;
+import org.apache.hadoop.hbase.security.access.UserPermission;
+
+public interface HBaseAccessController {
+ public boolean isAccessAllowed(User user, Action accessAction) ;
+ public boolean isAccessAllowed(User user, byte[] tableName, Action accessAction) ;
+ public boolean isAccessAllowed(User user, byte[] tableName, byte[] columnFamily, byte[] qualifier, Action accessAction) ;
+ public boolean isEncrypted(byte[] tableName, byte[] columnFamily, byte[] qualifier) ;
+ public boolean isAudited(byte[] tableName) ;
+ public boolean isTableHasEncryptedColumn(byte[] tableName) ;
+ public List<UserPermission> getUserPermissions(User user) ;
+ public List<UserPermission> getUserPermissions(User user, byte[] tableName) ;
+
+
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/HBaseAccessControllerFactory.java
----------------------------------------------------------------------
diff --git a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/HBaseAccessControllerFactory.java b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/HBaseAccessControllerFactory.java
new file mode 100644
index 0000000..6f4301e
--- /dev/null
+++ b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/HBaseAccessControllerFactory.java
@@ -0,0 +1,61 @@
+/*
+ * 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.authorization.hbase;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.authorization.hadoop.config.RangerConfiguration;
+import org.apache.ranger.authorization.hadoop.constants.RangerHadoopConstants;
+
+public class HBaseAccessControllerFactory {
+
+ private static final Log LOG = LogFactory.getLog(HBaseAccessControllerFactory.class) ;
+
+ private static HBaseAccessController hBaseAccessController = null ;
+
+ public static HBaseAccessController getInstance() {
+ if (hBaseAccessController == null) {
+ synchronized(HBaseAccessControllerFactory.class) {
+ HBaseAccessController temp = hBaseAccessController ;
+ if (temp == null) {
+
+ String hBaseAccessControllerClassName = RangerConfiguration.getInstance().get(RangerHadoopConstants.HBASE_ACCESS_VERIFIER_CLASS_NAME_PROP, RangerHadoopConstants.HBASE_ACCESS_VERIFIER_CLASS_NAME_DEFAULT_VALUE) ;
+ if (hBaseAccessControllerClassName != null) {
+ try {
+ hBaseAccessControllerClassName = hBaseAccessControllerClassName.trim();
+ hBaseAccessController = (HBaseAccessController) (Class.forName(hBaseAccessControllerClassName).newInstance()) ;
+ LOG.info("Created a new instance of class: [" + hBaseAccessControllerClassName + "] for HBase Access verification.");
+ } catch (InstantiationException e) {
+ LOG.error("Unable to create HBaseAccessController : [" + hBaseAccessControllerClassName + "]", e);
+ } catch (IllegalAccessException e) {
+ LOG.error("Unable to create HBaseAccessController : [" + hBaseAccessControllerClassName + "]", e);
+ } catch (ClassNotFoundException e) {
+ LOG.error("Unable to create HBaseAccessController : [" + hBaseAccessControllerClassName + "]", e);
+ }
+ }
+ }
+ }
+ }
+ return hBaseAccessController ;
+
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAccessControlFilter.java
----------------------------------------------------------------------
diff --git a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAccessControlFilter.java b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAccessControlFilter.java
new file mode 100644
index 0000000..9ba5331
--- /dev/null
+++ b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAccessControlFilter.java
@@ -0,0 +1,51 @@
+/*
+ * 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.authorization.hbase;
+
+import java.io.IOException;
+
+import org.apache.hadoop.hbase.Cell;
+import org.apache.hadoop.hbase.filter.FilterBase;
+import org.apache.hadoop.hbase.security.User;
+import org.apache.hadoop.hbase.security.access.TablePermission;
+
+public class RangerAccessControlFilter extends FilterBase {
+
+ private byte[] table = null;
+ private User user = null;
+
+ public RangerAccessControlFilter(User ugi, byte[] tableName) {
+ table = tableName;
+ user = ugi;
+ }
+
+
+ @SuppressWarnings("deprecation")
+ @Override
+ public ReturnCode filterKeyValue(Cell kv) throws IOException {
+ HBaseAccessController accessController = HBaseAccessControllerFactory.getInstance();
+ if (accessController.isAccessAllowed(user, table, kv.getFamily(), kv.getQualifier(), TablePermission.Action.READ)) {
+ return ReturnCode.INCLUDE;
+ } else {
+ return ReturnCode.NEXT_COL;
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessor.java
----------------------------------------------------------------------
diff --git a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessor.java b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessor.java
new file mode 100644
index 0000000..97d17e2
--- /dev/null
+++ b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessor.java
@@ -0,0 +1,1259 @@
+/*
+ * 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.authorization.hbase;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.Collection;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableSet;
+import java.util.Set;
+import java.util.TimeZone;
+
+import org.apache.commons.lang.StringUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.Cell;
+import org.apache.hadoop.hbase.CellUtil;
+import org.apache.hadoop.hbase.CoprocessorEnvironment;
+import org.apache.hadoop.hbase.HColumnDescriptor;
+import org.apache.hadoop.hbase.HRegionInfo;
+import org.apache.hadoop.hbase.HTableDescriptor;
+import org.apache.hadoop.hbase.KeyValue;
+import org.apache.hadoop.hbase.NamespaceDescriptor;
+import org.apache.hadoop.hbase.ServerName;
+import org.apache.hadoop.hbase.TableName;
+import org.apache.hadoop.hbase.client.Append;
+import org.apache.hadoop.hbase.client.Delete;
+import org.apache.hadoop.hbase.client.Durability;
+import org.apache.hadoop.hbase.client.Get;
+import org.apache.hadoop.hbase.client.Increment;
+import org.apache.hadoop.hbase.client.Put;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.client.Scan;
+import org.apache.hadoop.hbase.coprocessor.CoprocessorException;
+import org.apache.hadoop.hbase.coprocessor.CoprocessorService;
+import org.apache.hadoop.hbase.coprocessor.MasterCoprocessorEnvironment;
+import org.apache.hadoop.hbase.coprocessor.ObserverContext;
+import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
+import org.apache.hadoop.hbase.coprocessor.RegionServerCoprocessorEnvironment;
+import org.apache.hadoop.hbase.filter.ByteArrayComparable;
+import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
+import org.apache.hadoop.hbase.filter.FilterList;
+import org.apache.hadoop.hbase.ipc.RequestContext;
+import org.apache.hadoop.hbase.master.RegionPlan;
+import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
+import org.apache.hadoop.hbase.protobuf.ResponseConverter;
+import org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos;
+import org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos.AccessControlService;
+import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
+import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.CleanupBulkLoadRequest;
+import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.PrepareBulkLoadRequest;
+import org.apache.hadoop.hbase.regionserver.HRegion;
+import org.apache.hadoop.hbase.regionserver.InternalScanner;
+import org.apache.hadoop.hbase.regionserver.RegionScanner;
+import org.apache.hadoop.hbase.regionserver.ScanType;
+import org.apache.hadoop.hbase.regionserver.Store;
+import org.apache.hadoop.hbase.regionserver.StoreFile;
+import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
+import org.apache.hadoop.hbase.security.AccessDeniedException;
+import org.apache.hadoop.hbase.security.User;
+import org.apache.hadoop.hbase.security.access.Permission;
+import org.apache.hadoop.hbase.security.access.Permission.Action;
+import org.apache.hadoop.hbase.security.access.TablePermission;
+import org.apache.hadoop.hbase.security.access.UserPermission;
+import org.apache.hadoop.hbase.security.access.RangerAccessControlLists;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.hbase.util.Pair;
+import org.apache.ranger.admin.client.RangerAdminRESTClient;
+import org.apache.ranger.admin.client.datatype.GrantRevokeData;
+import org.apache.ranger.admin.client.datatype.GrantRevokeData.PermMap;
+import org.apache.ranger.audit.model.EnumRepositoryType;
+import org.apache.ranger.audit.model.HBaseAuditEvent;
+import org.apache.ranger.audit.provider.AuditProviderFactory;
+import org.apache.ranger.authorization.hadoop.config.RangerConfiguration;
+import org.apache.ranger.authorization.hadoop.constants.RangerHadoopConstants;
+import org.apache.ranger.authorization.utils.StringUtil;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.MapMaker;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import com.google.protobuf.RpcCallback;
+import com.google.protobuf.RpcController;
+import com.google.protobuf.Service;
+
+public class RangerAuthorizationCoprocessor extends RangerAuthorizationCoprocessorBase implements AccessControlService.Interface, CoprocessorService {
+ private static final Log LOG = LogFactory.getLog(RangerAuthorizationCoprocessor.class.getName());
+ private static final String RangerModuleName = RangerConfiguration.getInstance().get(RangerHadoopConstants.AUDITLOG_RANGER_MODULE_ACL_NAME_PROP , RangerHadoopConstants.DEFAULT_RANGER_MODULE_ACL_NAME) ;
+ private static final short accessGrantedFlag = 1;
+ private static final short accessDeniedFlag = 0;
+ private static final String repositoryName = RangerConfiguration.getInstance().get(RangerHadoopConstants.AUDITLOG_REPOSITORY_NAME_PROP);
+ private static final boolean UpdateRangerPoliciesOnGrantRevoke = RangerConfiguration.getInstance().getBoolean(RangerHadoopConstants.HBASE_UPDATE_RANGER_POLICIES_ON_GRANT_REVOKE_PROP, RangerHadoopConstants.HBASE_UPDATE_RANGER_POLICIES_ON_GRANT_REVOKE_DEFAULT_VALUE);
+ private static final String GROUP_PREFIX = "@";
+
+
+ private static final String SUPERUSER_CONFIG_PROP = "hbase.superuser";
+ private static final String WILDCARD = "*";
+ private static final byte[] WILDCARD_MATCH = "*".getBytes();
+
+ private static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT+0");
+
+ private RegionCoprocessorEnvironment regionEnv;
+ private Map<InternalScanner, String> scannerOwners = new MapMaker().weakKeys().makeMap();
+
+ private HBaseAccessController accessController = HBaseAccessControllerFactory.getInstance();
+ private List<String> superUserList = null;
+ // Utilities Methods
+ protected byte[] getTableName(RegionCoprocessorEnvironment e) {
+ HRegion region = e.getRegion();
+ byte[] tableName = null;
+ if (region != null) {
+ HRegionInfo regionInfo = region.getRegionInfo();
+ if (regionInfo != null) {
+ tableName = regionInfo.getTable().getName() ;
+ }
+ }
+ return tableName;
+ }
+ protected void isSystemOrSuperUser(Configuration conf) throws IOException {
+ User user = User.getCurrent();
+ if (user == null) {
+ throw new IOException("Unable to obtain the current user, authorization checks for internal operations will not work correctly!");
+ }
+ String currentUser = user.getShortName();
+ List<String> superusers = Lists.asList(currentUser, conf.getStrings(SUPERUSER_CONFIG_PROP, new String[0]));
+ User activeUser = getActiveUser();
+ if (!(superusers.contains(activeUser.getShortName()))) {
+ throw new AccessDeniedException("User '" + (user != null ? user.getShortName() : "null") + "is not system or super user.");
+ }
+ }
+ private boolean isSuperUser(User user) {
+ boolean isSuper = false;
+ isSuper = (superUserList != null && superUserList.contains(user.getShortName()));
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("IsSuperCheck on [" + user.getShortName() + "] returns [" + isSuper + "]");
+ }
+ return isSuper;
+ }
+ protected boolean isSpecialTable(HRegionInfo regionInfo) {
+ return isSpecialTable(regionInfo.getTable().getName());
+ }
+ protected boolean isSpecialTable(byte[] tableName) {
+ return isSpecialTable(Bytes.toString(tableName));
+ }
+ protected boolean isSpecialTable(String tableNameStr) {
+ return tableNameStr.equals("hbase:meta") || tableNameStr.equals("-ROOT-") || tableNameStr.equals(".META.");
+ }
+ @SuppressWarnings("unused")
+ private String getUser() {
+ User u = getActiveUser();
+ if (u == null) {
+ return "(user:unknown)";
+ } else {
+ String groups = (u.getGroupNames() == null) ? "" : StringUtils.join(u.getGroupNames(), ",");
+ return "(user:" + u.getShortName() + ", groups: [" + groups + "])";
+ }
+ }
+ private User getActiveUser() {
+ User user = RequestContext.getRequestUser();
+ if (!RequestContext.isInRequestContext()) {
+ // for non-rpc handling, fallback to system user
+ try {
+ user = User.getCurrent();
+ } catch (IOException e) {
+ LOG.error("Unable to find the current user");
+ user = null;
+ }
+ }
+ return user;
+ }
+
+ private String getRemoteAddress() {
+ RequestContext reqContext = RequestContext.get();
+ InetAddress remoteAddr = reqContext != null ? reqContext.getRemoteAddress() : null;
+ String strAddr = remoteAddr != null ? remoteAddr.getHostAddress() : null;
+
+ return strAddr;
+ }
+
+ // Methods that are used within the CoProcessor
+ private void requireScannerOwner(InternalScanner s) throws AccessDeniedException {
+ if (RequestContext.isInRequestContext()) {
+ String requestUserName = RequestContext.getRequestUserName();
+ String owner = scannerOwners.get(s);
+ if (owner != null && !owner.equals(requestUserName)) {
+ throw new AccessDeniedException("User '" + requestUserName + "' is not the scanner owner!");
+ }
+ }
+ }
+ // Methods that are delegated to AUTHManager
+ public boolean isPermissionGranted(User user, Action action) {
+ if (isSuperUser(user)) {
+ return true;
+ } else {
+ return accessController.isAccessAllowed(user, action);
+ }
+ }
+ public boolean isPermissionGranted(User user, byte[] tableName, Action action) {
+ if (isSuperUser(user)) {
+ return true;
+ } else {
+ return accessController.isAccessAllowed(user, tableName, action);
+ }
+ }
+ public boolean isPermissionGranted(User user, byte[] tableName, byte[] colf, Action action) {
+ if (isSuperUser(user)) {
+ return true;
+ } else {
+ return accessController.isAccessAllowed(user, tableName, colf, WILDCARD_MATCH, action);
+ }
+ }
+ public boolean isPermissionGranted(User user, byte[] tableName, byte[] colf, byte[] col, Action action) {
+ if (isSuperUser(user)) {
+ return true;
+ } else {
+ return accessController.isAccessAllowed(user, tableName, colf, col, action);
+ }
+ }
+ // Methods that are internally used by co-processors
+ @SuppressWarnings("unchecked")
+ public void requirePermission(String request, Action action, RegionCoprocessorEnvironment rEnv, Map<byte[], ? extends Collection<?>> families) throws IOException {
+ HRegionInfo hri = rEnv.getRegion().getRegionInfo();
+ byte[] tableName = hri.getTable().getName() ;
+ String tableNameStr = Bytes.toString(tableName);
+ if (hri.isMetaTable() || hri.isMetaRegion()) {
+ if (action == TablePermission.Action.READ) {
+ return;
+ }
+ }
+ User user = getActiveUser();
+ if (user == null) {
+ throw new AccessDeniedException("No user associated with request (" + request + ") for action: " + action + "on table:" + tableName);
+ }
+ if (isSuperUser(user)) {
+ return;
+ }
+ if (action == TablePermission.Action.WRITE && (hri.isMetaTable() || hri.isMetaRegion()) && (isPermissionGranted(user, Permission.Action.CREATE) || isPermissionGranted(user, Permission.Action.ADMIN))) {
+ return;
+ }
+ if (isPermissionGranted(user, tableName, (byte[]) null, action)) {
+ return;
+ }
+ if (families != null && families.size() > 0) {
+ // all families must pass
+ for (Map.Entry<byte[], ? extends Collection<?>> family : families.entrySet()) {
+ // a) check for family level access
+ if (isPermissionGranted(user, tableName, family.getKey(), action)) {
+ continue; // family-level permission overrides per-qualifier
+ }
+ // b) qualifier level access can still succeed
+ if ((family.getValue() != null) && (family.getValue().size() > 0)) {
+ if (family.getValue() instanceof Set) { // Set<byte[]> - Set
+ // of Columns
+ // for each qualifier of the family
+ Set<byte[]> qualifierSet = (Set<byte[]>) family.getValue();
+ for (byte[] qualifier : qualifierSet) {
+ if (!isPermissionGranted(user, tableName, family.getKey(), qualifier, action)) {
+ if (accessController.isAudited(tableName)) {
+ auditEvent(request, tableName, family.getKey(), qualifier, null, null, user, accessDeniedFlag);
+ }
+ throw new AccessDeniedException("Insufficient permissions for user '" + user + "',action: " + action + ", tableName:" + tableNameStr + ", family:" + Bytes.toString(family.getKey()) + ",column: " + Bytes.toString(qualifier));
+ }
+ }
+ } else if (family.getValue() instanceof List) { // List<KeyValue>
+ // - List of
+ // KeyValue
+ // pair
+ List<KeyValue> kvList = (List<KeyValue>) family.getValue();
+ for (KeyValue kv : kvList) {
+ if (!isPermissionGranted(user, tableName, family.getKey(), kv.getQualifier(), action)) {
+ if (accessController.isAudited(tableName)) {
+ auditEvent(request, tableName, family.getKey(), kv.getQualifier(), null, null, user, accessDeniedFlag);
+ }
+ throw new AccessDeniedException("Insufficient permissions for user '" + user + "',action: " + action + ", tableName:" + tableNameStr + ", family:" + Bytes.toString(family.getKey()) + ",column: " + Bytes.toString(kv.getQualifier()));
+ }
+ }
+ }
+ } else {
+ if (accessController.isAudited(tableName)) {
+ auditEvent(request, tableName, family.getKey(), null, null, null, user, accessDeniedFlag);
+ }
+ throw new AccessDeniedException("Insufficient permissions for user '" + user + "',action: " + action + ", tableName:" + tableNameStr + ", family:" + Bytes.toString(family.getKey()) + ", no columns found.");
+ }
+ }
+ return;
+ }
+ if (accessController.isAudited(tableName)) {
+ auditEvent(request, tableName, null, null, null, null, user, accessDeniedFlag);
+ }
+ throw new AccessDeniedException("Insufficient permissions for user '" + user + "',action: " + action + ", tableName:" + tableNameStr);
+ }
+ // Check if the user has global permission ...
+ protected void requireGlobalPermission(String request, String objName, Permission.Action action) throws AccessDeniedException {
+ User user = getActiveUser();
+ if (!isPermissionGranted(user, action)) {
+ if (accessController.isAudited(WILDCARD_MATCH)) {
+ auditEvent(request, objName, null, null, null, null, user, accessDeniedFlag);
+ }
+ throw new AccessDeniedException("Insufficient permissions for user '" + getActiveUser() + "' (global, action=" + action + ")");
+ }
+ }
+ protected void requirePermission(String request, byte[] tableName, Permission.Action action) throws AccessDeniedException {
+ User user = getActiveUser();
+ if (!isPermissionGranted(user, tableName, action)) {
+ if (accessController.isAudited(tableName)) {
+ auditEvent(request, tableName, null, null, null, null, user, accessDeniedFlag);
+ }
+ throw new AccessDeniedException("Insufficient permissions for user '" + getActiveUser() + "' (global, action=" + action + ")");
+ }
+ }
+ protected void requirePermission(String request, byte[] aTableName, byte[] aColumnFamily, byte[] aQualifier, Permission.Action... actions) throws AccessDeniedException {
+ User user = getActiveUser();
+ boolean isAllowed = false;
+
+ for (Action action : actions) {
+ isAllowed = isPermissionGranted(user, aTableName, aColumnFamily, aQualifier, action);
+
+ if(isAllowed) {
+ break;
+ }
+ }
+
+ if (!isAllowed) {
+ if (accessController.isAudited(aTableName)) {
+ auditEvent(request, aTableName, aColumnFamily, aQualifier, null, null, user, accessDeniedFlag);
+ }
+ Permission.Action deniedAction = actions.length > 0 ? actions[0] : null;
+
+ throw new AccessDeniedException("Insufficient permissions for user '" + user + "',action: " + deniedAction + ", tableName:" + Bytes.toString(aTableName) + ", family:" + Bytes.toString(aColumnFamily) + ",column: " + Bytes.toString(aQualifier));
+ }
+ }
+ protected void requirePermission(String request, Permission.Action perm, RegionCoprocessorEnvironment env, Collection<byte[]> families) throws IOException {
+ HashMap<byte[], Set<byte[]>> familyMap = new HashMap<byte[], Set<byte[]>>();
+
+ if(families != null) {
+ for (byte[] family : families) {
+ familyMap.put(family, null);
+ }
+ }
+ requirePermission(request, perm, env, familyMap);
+ }
+ protected boolean isPermissionGranted(String request, User requestUser, Permission.Action perm, RegionCoprocessorEnvironment env, Map<byte[], NavigableSet<byte[]>> familyMap) {
+ boolean ret = true;
+ try {
+ requirePermission(request, perm, env, familyMap);
+ } catch (Throwable t) {
+ ret = false;
+ }
+ return ret;
+ }
+ protected boolean hasFamilyQualifierPermission(User requestUser, Permission.Action perm, RegionCoprocessorEnvironment env, Map<byte[], NavigableSet<byte[]>> familyMap) {
+ User user = requestUser;
+ byte[] tableName = getTableName(env);
+ if (familyMap != null && familyMap.size() > 0) {
+ for (Map.Entry<byte[], NavigableSet<byte[]>> family : familyMap.entrySet()) {
+ if (family.getValue() != null && !family.getValue().isEmpty()) {
+ for (byte[] qualifier : family.getValue()) {
+ boolean isGranted = isPermissionGranted(user, tableName, family.getKey(), qualifier, perm);
+ LOG.info(":=> hasFamilyQualifierPermission: T(" + Bytes.toString(tableName) + "), family: (" + Bytes.toString(family.getKey() ) + "), Q(" + Bytes.toString(qualifier) + "), Permission: [" + perm + "] => [" + isGranted + "]") ;
+ if (isGranted) {
+ return true;
+ }
+ }
+ } else {
+ boolean isGranted = isPermissionGranted(user, tableName, family.getKey(), perm);
+ LOG.info(":=> hasFamilyPermission: T(" + Bytes.toString(tableName) + "), family: (" + Bytes.toString(family.getKey() ) + ", Permission: [" + perm + "] => [" + isGranted + "]") ;
+ if (isGranted) {
+ return true;
+ }
+ }
+ }
+ } else {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Empty family map passed for permission check");
+ }
+ }
+ return false;
+ }
+
+
+ public void checkPermissions(Permission[] permissions) throws IOException {
+ String tableName = regionEnv.getRegion().getTableDesc().getTableName().getNameAsString() ;
+ for (Permission permission : permissions) {
+ if (permission instanceof TablePermission) {
+ TablePermission tperm = (TablePermission) permission;
+ for (Permission.Action action : permission.getActions()) {
+ if (! tperm.getTableName().getNameAsString().equals(tableName)) {
+ throw new AccessDeniedException(String.format("This method can only execute at the table specified in TablePermission. " + "Table of the region:%s , requested table:%s", tableName,
+ tperm.getTableName().getNameAsString()));
+ }
+ HashMap<byte[], Set<byte[]>> familyMap = Maps.newHashMapWithExpectedSize(1);
+ if (tperm.getFamily() != null) {
+ if (tperm.getQualifier() != null) {
+ familyMap.put(tperm.getFamily(), Sets.newHashSet(tperm.getQualifier()));
+ } else {
+ familyMap.put(tperm.getFamily(), null);
+ }
+ }
+ requirePermission("checkPermissions", action, regionEnv, familyMap);
+ }
+ } else {
+ for (Permission.Action action : permission.getActions()) {
+ byte[] tname = regionEnv.getRegion().getTableDesc().getTableName().getName() ;
+ requirePermission("checkPermissions", tname, action);
+ }
+ }
+ }
+ }
+
+ @Override
+ public void postAddColumn(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName, HColumnDescriptor column) throws IOException {
+ auditEvent("addColumn", tableName.getName(), column.getName(), null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ @Override
+ public void postAssign(ObserverContext<MasterCoprocessorEnvironment> c, HRegionInfo regionInfo) throws IOException {
+ auditEvent("assign", regionInfo.getTable().getNameAsString(), null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ @Override
+ public void postBalance(ObserverContext<MasterCoprocessorEnvironment> c,List<RegionPlan> aRegPlanList) throws IOException {
+ auditEvent("balance", (String) null, null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ @Override
+ public void postBalanceSwitch(ObserverContext<MasterCoprocessorEnvironment> c, boolean oldValue, boolean newValue) throws IOException {
+ auditEvent("balanceSwitch", (String) null, null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ @Override
+ public void postCloneSnapshot(ObserverContext<MasterCoprocessorEnvironment> ctx, SnapshotDescription snapshot, HTableDescriptor hTableDescriptor) throws IOException {
+ auditEvent("cloneSnapshot", hTableDescriptor.getNameAsString(), null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ @Override
+ public void postCreateTable(ObserverContext<MasterCoprocessorEnvironment> ctx, HTableDescriptor desc, HRegionInfo[] regions) throws IOException {
+ auditEvent("createTable", desc.getNameAsString(), null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ @Override
+ public void postDelete(ObserverContext<RegionCoprocessorEnvironment> c, Delete delete, WALEdit edit, Durability durability) throws IOException {
+ auditEvent("delete", delete.toString(), null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ @Override
+ public void postDeleteColumn(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName, byte[] col) throws IOException {
+ auditEvent("deleteColumn", tableName.getName(), col, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ @Override
+ public void postDeleteSnapshot(ObserverContext<MasterCoprocessorEnvironment> ctx, SnapshotDescription snapshot) throws IOException {
+ auditEvent("deleteSnapShot", (String) null, null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ @Override
+ public void postDeleteTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName) throws IOException {
+ auditEvent("deleteTable", tableName.getName(), null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ @Override
+ public void postDisableTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName) throws IOException {
+ auditEvent("disableTable", tableName.getName(), null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ @Override
+ public void postEnableTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName) throws IOException {
+ auditEvent("enableTable", tableName.getName(), null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ @Override
+ public void postModifyColumn(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName, HColumnDescriptor descriptor) throws IOException {
+ auditEvent("modifyColumn", tableName.getName(), descriptor.getName(), null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ @Override
+ public void postModifyTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName, HTableDescriptor htd) throws IOException {
+ auditEvent("modifyTable", tableName.getName(), null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ @Override
+ public void postMove(ObserverContext<MasterCoprocessorEnvironment> c, HRegionInfo region, ServerName srcServer, ServerName destServer) throws IOException {
+ auditEvent("move", region.getTable().getName(), null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ @Override
+ public void postOpen(ObserverContext<RegionCoprocessorEnvironment> ctx) {
+ auditEvent("open", (String) null, null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ @Override
+ public void postRestoreSnapshot(ObserverContext<MasterCoprocessorEnvironment> ctx, SnapshotDescription snapshot, HTableDescriptor hTableDescriptor) throws IOException {
+ auditEvent("restoreSnapshot", (String) null, null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ @Override
+ public void postScannerClose(ObserverContext<RegionCoprocessorEnvironment> c, InternalScanner s) throws IOException {
+ try {
+ scannerOwners.remove(s);
+ } finally {
+ byte[] tableName = getTableName(c.getEnvironment());
+
+ if (!isSpecialTable(tableName)) {
+ auditEvent("scannerClose", tableName, null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ }
+ }
+ @Override
+ public RegionScanner postScannerOpen(ObserverContext<RegionCoprocessorEnvironment> c, Scan scan, RegionScanner s) throws IOException {
+ try {
+ User user = getActiveUser();
+ if (user != null && user.getShortName() != null) {
+ scannerOwners.put(s, user.getShortName());
+ }
+ } finally {
+ byte[] tableName = getTableName(c.getEnvironment());
+
+ if (!isSpecialTable(tableName)) {
+ auditEvent("scannerOpen", tableName, null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ }
+ return s;
+ }
+ @Override
+ public void postSnapshot(ObserverContext<MasterCoprocessorEnvironment> ctx, SnapshotDescription snapshot, HTableDescriptor hTableDescriptor) throws IOException {
+ auditEvent("snapshot", hTableDescriptor.getNameAsString(), null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ @Override
+ public void postStartMaster(ObserverContext<MasterCoprocessorEnvironment> ctx) throws IOException {
+ if(UpdateRangerPoliciesOnGrantRevoke) {
+ RangerAccessControlLists.init(ctx.getEnvironment().getMasterServices());
+ }
+
+ auditEvent("startMaster", (String) null, null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ @Override
+ public void postUnassign(ObserverContext<MasterCoprocessorEnvironment> c, HRegionInfo regionInfo, boolean force) throws IOException {
+ auditEvent("unassign", regionInfo.getTable().getName(), null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ @Override
+ public void preAddColumn(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName, HColumnDescriptor column) throws IOException {
+ requirePermission("addColumn", tableName.getName(), null, null, Action.ADMIN, Action.CREATE);
+ }
+ @Override
+ public Result preAppend(ObserverContext<RegionCoprocessorEnvironment> c, Append append) throws IOException {
+ requirePermission("append", TablePermission.Action.WRITE, c.getEnvironment(), append.getFamilyCellMap());
+ return null;
+ }
+ @Override
+ public void preAssign(ObserverContext<MasterCoprocessorEnvironment> c, HRegionInfo regionInfo) throws IOException {
+ requirePermission("assign", regionInfo.getTable().getName(), null, null, Action.ADMIN);
+ }
+ @Override
+ public void preBalance(ObserverContext<MasterCoprocessorEnvironment> c) throws IOException {
+ requirePermission("balance", null, Permission.Action.ADMIN);
+ }
+ @Override
+ public boolean preBalanceSwitch(ObserverContext<MasterCoprocessorEnvironment> c, boolean newValue) throws IOException {
+ requirePermission("balanceSwitch", null, Permission.Action.ADMIN);
+ return newValue;
+ }
+ @Override
+ public void preBulkLoadHFile(ObserverContext<RegionCoprocessorEnvironment> ctx, List<Pair<byte[], String>> familyPaths) throws IOException {
+ List<byte[]> cfs = new LinkedList<byte[]>();
+ for (Pair<byte[], String> el : familyPaths) {
+ cfs.add(el.getFirst());
+ }
+ requirePermission("bulkLoadHFile", Permission.Action.WRITE, ctx.getEnvironment(), cfs);
+ }
+ @Override
+ public boolean preCheckAndDelete(ObserverContext<RegionCoprocessorEnvironment> c, byte[] row, byte[] family, byte[] qualifier, CompareOp compareOp, ByteArrayComparable comparator, Delete delete, boolean result) throws IOException {
+ Collection<byte[]> familyMap = Arrays.asList(new byte[][] { family });
+ requirePermission("checkAndDelete", TablePermission.Action.READ, c.getEnvironment(), familyMap);
+ requirePermission("checkAndDelete", TablePermission.Action.WRITE, c.getEnvironment(), familyMap);
+ return result;
+ }
+ @Override
+ public boolean preCheckAndPut(ObserverContext<RegionCoprocessorEnvironment> c, byte[] row, byte[] family, byte[] qualifier, CompareOp compareOp, ByteArrayComparable comparator, Put put, boolean result) throws IOException {
+ Collection<byte[]> familyMap = Arrays.asList(new byte[][] { family });
+ requirePermission("checkAndPut", TablePermission.Action.READ, c.getEnvironment(), familyMap);
+ requirePermission("checkAndPut", TablePermission.Action.WRITE, c.getEnvironment(), familyMap);
+ return result;
+ }
+ @Override
+ public void preCloneSnapshot(ObserverContext<MasterCoprocessorEnvironment> ctx, SnapshotDescription snapshot, HTableDescriptor hTableDescriptor) throws IOException {
+ requirePermission("cloneSnapshot", null, Permission.Action.ADMIN);
+ }
+ @Override
+ public void preClose(ObserverContext<RegionCoprocessorEnvironment> e, boolean abortRequested) throws IOException {
+ requirePermission("close", getTableName(e.getEnvironment()), Permission.Action.ADMIN);
+ }
+ @Override
+ public InternalScanner preCompact(ObserverContext<RegionCoprocessorEnvironment> e, Store store, InternalScanner scanner,ScanType scanType) throws IOException {
+ requirePermission("compact", getTableName(e.getEnvironment()), null, null, Action.ADMIN, Action.CREATE);
+ return scanner;
+ }
+ @Override
+ public void preCompactSelection(ObserverContext<RegionCoprocessorEnvironment> e, Store store, List<StoreFile> candidates) throws IOException {
+ requirePermission("compactSelection", getTableName(e.getEnvironment()), null, null, Action.ADMIN, Action.CREATE);
+ }
+
+ @Override
+ public void preCreateTable(ObserverContext<MasterCoprocessorEnvironment> c, HTableDescriptor desc, HRegionInfo[] regions) throws IOException {
+ requirePermission("createTable", desc.getName(), Permission.Action.CREATE);
+ }
+ @Override
+ public void preDelete(ObserverContext<RegionCoprocessorEnvironment> c, Delete delete, WALEdit edit, Durability durability) throws IOException {
+ requirePermission("delete", TablePermission.Action.WRITE, c.getEnvironment(), delete.getFamilyCellMap());
+ }
+ @Override
+ public void preDeleteColumn(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName, byte[] col) throws IOException {
+ requirePermission("deleteColumn", tableName.getName(), null, null, Action.ADMIN, Action.CREATE);
+ }
+ @Override
+ public void preDeleteSnapshot(ObserverContext<MasterCoprocessorEnvironment> ctx, SnapshotDescription snapshot) throws IOException {
+ requirePermission("deleteSnapshot", null, Permission.Action.ADMIN);
+ }
+ @Override
+ public void preDeleteTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName) throws IOException {
+ requirePermission("deleteTable", tableName.getName(), null, null, Action.ADMIN, Action.CREATE);
+ }
+ @Override
+ public void preDisableTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName) throws IOException {
+ requirePermission("disableTable", tableName.getName(), null, null, Action.ADMIN, Action.CREATE);
+ }
+ @Override
+ public void preEnableTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName) throws IOException {
+ requirePermission("enableTable", tableName.getName(), null, null, Action.ADMIN, Action.CREATE);
+ }
+ @Override
+ public boolean preExists(ObserverContext<RegionCoprocessorEnvironment> c, Get get, boolean exists) throws IOException {
+ requirePermission("exists", TablePermission.Action.READ, c.getEnvironment(), get.familySet());
+ return exists;
+ }
+ @Override
+ public void preFlush(ObserverContext<RegionCoprocessorEnvironment> e) throws IOException {
+ requirePermission("flush", getTableName(e.getEnvironment()), null, null, Action.ADMIN, Action.CREATE);
+ }
+ @Override
+ public void preGetClosestRowBefore(ObserverContext<RegionCoprocessorEnvironment> c, byte[] row, byte[] family, Result result) throws IOException {
+ requirePermission("getClosestRowBefore", TablePermission.Action.READ, c.getEnvironment(), (family != null ? Lists.newArrayList(family) : null));
+ }
+ @Override
+ public Result preIncrement(ObserverContext<RegionCoprocessorEnvironment> c, Increment increment) throws IOException {
+ requirePermission("increment", TablePermission.Action.WRITE, c.getEnvironment(), increment.getFamilyCellMap().keySet());
+
+ return null;
+ }
+ @Override
+ public long preIncrementColumnValue(ObserverContext<RegionCoprocessorEnvironment> c, byte[] row, byte[] family, byte[] qualifier, long amount, boolean writeToWAL) throws IOException {
+ requirePermission("incrementColumnValue", TablePermission.Action.READ, c.getEnvironment(), Arrays.asList(new byte[][] { family }));
+ requirePermission("incrementColumnValue", TablePermission.Action.WRITE, c.getEnvironment(), Arrays.asList(new byte[][] { family }));
+ return -1;
+ }
+ @Override
+ public void preModifyColumn(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName, HColumnDescriptor descriptor) throws IOException {
+ requirePermission("modifyColumn", tableName.getName(), null, null, Action.ADMIN, Action.CREATE);
+ }
+ @Override
+ public void preModifyTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName, HTableDescriptor htd) throws IOException {
+ requirePermission("modifyTable", tableName.getName(), null, null, Action.ADMIN, Action.CREATE);
+ }
+ @Override
+ public void preMove(ObserverContext<MasterCoprocessorEnvironment> c, HRegionInfo region, ServerName srcServer, ServerName destServer) throws IOException {
+ requirePermission("move", region.getTable().getName() , null, null, Action.ADMIN);
+ }
+ @Override
+ public void preOpen(ObserverContext<RegionCoprocessorEnvironment> e) throws IOException {
+ RegionCoprocessorEnvironment env = e.getEnvironment();
+ final HRegion region = env.getRegion();
+ if (region == null) {
+ LOG.error("NULL region from RegionCoprocessorEnvironment in preOpen()");
+ return;
+ } else {
+ HRegionInfo regionInfo = region.getRegionInfo();
+ if (isSpecialTable(regionInfo)) {
+ isSystemOrSuperUser(regionEnv.getConfiguration());
+ } else {
+ requirePermission("open", getTableName(e.getEnvironment()), Action.ADMIN);
+ }
+ }
+ }
+ @Override
+ public void preRestoreSnapshot(ObserverContext<MasterCoprocessorEnvironment> ctx, SnapshotDescription snapshot, HTableDescriptor hTableDescriptor) throws IOException {
+ requirePermission("restoreSnapshot", hTableDescriptor.getName(), Permission.Action.ADMIN);
+ }
+
+ @Override
+ public void preScannerClose(ObserverContext<RegionCoprocessorEnvironment> c, InternalScanner s) throws IOException {
+ requireScannerOwner(s);
+ }
+ @Override
+ public boolean preScannerNext(ObserverContext<RegionCoprocessorEnvironment> c, InternalScanner s, List<Result> result, int limit, boolean hasNext) throws IOException {
+ requireScannerOwner(s);
+ return hasNext;
+ }
+ @Override
+ public RegionScanner preScannerOpen(ObserverContext<RegionCoprocessorEnvironment> c, Scan scan, RegionScanner s) throws IOException {
+ RegionCoprocessorEnvironment e = c.getEnvironment();
+ User user = getActiveUser();
+ boolean isGranted = isPermissionGranted("scannerOpen", user, TablePermission.Action.READ, e, scan.getFamilyMap());
+ if (!isGranted) {
+ if (hasFamilyQualifierPermission(user, TablePermission.Action.READ, e, scan.getFamilyMap())) {
+ byte[] table = getTableName(e);
+ RangerAccessControlFilter filter = new RangerAccessControlFilter(user, table);
+ if (scan.hasFilter()) {
+ FilterList wrapper = new FilterList(FilterList.Operator.MUST_PASS_ALL, Lists.newArrayList(filter, scan.getFilter()));
+ scan.setFilter(wrapper);
+ } else {
+ scan.setFilter(filter);
+ }
+ } else {
+ throw new AccessDeniedException("Insufficient permissions for user '" + (user != null ? user.getShortName() : "null") + "' for scanner open on table " + Bytes.toString(getTableName(e)));
+ }
+ }
+ return s;
+ }
+ @Override
+ public void preShutdown(ObserverContext<MasterCoprocessorEnvironment> c) throws IOException {
+ requirePermission("shutdown", null, Permission.Action.ADMIN);
+ }
+ @Override
+ public void preSnapshot(ObserverContext<MasterCoprocessorEnvironment> ctx, SnapshotDescription snapshot, HTableDescriptor hTableDescriptor) throws IOException {
+ requirePermission("snapshot", hTableDescriptor.getName(), Permission.Action.ADMIN);
+ }
+ @Override
+ public void preSplit(ObserverContext<RegionCoprocessorEnvironment> e) throws IOException {
+ requirePermission("split", getTableName(e.getEnvironment()), null, null, Action.ADMIN);
+ }
+ @Override
+ public void preStopMaster(ObserverContext<MasterCoprocessorEnvironment> c) throws IOException {
+ requirePermission("stopMaster", null, Permission.Action.ADMIN);
+ }
+ @Override
+ public void preStopRegionServer(ObserverContext<RegionServerCoprocessorEnvironment> env) throws IOException {
+ requirePermission("stop", null, Permission.Action.ADMIN);
+ }
+ @Override
+ public void preUnassign(ObserverContext<MasterCoprocessorEnvironment> c, HRegionInfo regionInfo, boolean force) throws IOException {
+ requirePermission("unassign", regionInfo.getTable().getName(), null, null, Action.ADMIN);
+ }
+ private String coprocessorType = "unknown";
+ private static final String MASTER_COPROCESSOR_TYPE = "master";
+ private static final String REGIONAL_COPROCESSOR_TYPE = "regional";
+ private static final String REGIONAL_SERVER_COPROCESSOR_TYPE = "regionalServer";
+ @Override
+ public void start(CoprocessorEnvironment env) throws IOException {
+ AuditProviderFactory.ApplicationType appType = AuditProviderFactory.ApplicationType.Unknown;
+
+ if (env instanceof MasterCoprocessorEnvironment) {
+ coprocessorType = MASTER_COPROCESSOR_TYPE;
+ appType = AuditProviderFactory.ApplicationType.HBaseMaster;
+ } else if (env instanceof RegionServerCoprocessorEnvironment) {
+ coprocessorType = REGIONAL_SERVER_COPROCESSOR_TYPE;
+ appType = AuditProviderFactory.ApplicationType.HBaseRegionalServer;
+ } else if (env instanceof RegionCoprocessorEnvironment) {
+ regionEnv = (RegionCoprocessorEnvironment) env;
+ coprocessorType = REGIONAL_COPROCESSOR_TYPE;
+ appType = AuditProviderFactory.ApplicationType.HBaseRegionalServer;
+ }
+
+ RangerConfiguration.getInstance().initAudit(appType);
+
+ if (superUserList == null) {
+ superUserList = new ArrayList<String>();
+ Configuration conf = env.getConfiguration();
+ String[] users = conf.getStrings(SUPERUSER_CONFIG_PROP);
+ if (users != null) {
+ for (String user : users) {
+ user = user.trim();
+ LOG.info("Start() - Adding Super User(" + user + ")");
+ superUserList.add(user);
+ }
+ }
+ }
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Start of Coprocessor: [" + coprocessorType + "] with superUserList [" + superUserList + "]");
+ }
+ }
+ @Override
+ public void stop(CoprocessorEnvironment env) {
+ }
+ @Override
+ public void prePut(ObserverContext<RegionCoprocessorEnvironment> c, Put put, WALEdit edit, Durability durability) throws IOException {
+ requirePermission("put", TablePermission.Action.WRITE, c.getEnvironment(), put.getFamilyCellMap());
+ }
+
+ @Override
+ public void postPut(ObserverContext<RegionCoprocessorEnvironment> c, Put put, WALEdit edit, Durability durability) {
+ byte[] tableName = getTableName(c.getEnvironment());
+ if (!isSpecialTable(tableName)) {
+ if (accessController.isAudited(tableName)) {
+ Map<byte[], List<Cell>> colf2KeyValMap = put.getFamilyCellMap() ;
+ for (byte[] colf : colf2KeyValMap.keySet()) {
+ if (colf != null) {
+ List<Cell> kvList = colf2KeyValMap.get(colf);
+ for (Cell kv : kvList) {
+ auditEvent("Put", tableName, CellUtil.cloneFamily(kv), CellUtil.cloneQualifier(kv) , CellUtil.cloneRow(kv), CellUtil.cloneValue(kv), getActiveUser(), accessGrantedFlag);
+ }
+ }
+ }
+
+
+ }
+ }
+ }
+
+ @Override
+ public void preGetOp(final ObserverContext<RegionCoprocessorEnvironment> rEnv, final Get get, final List<Cell> result) throws IOException {
+ RegionCoprocessorEnvironment e = rEnv.getEnvironment();
+ User requestUser = getActiveUser();
+
+
+ if (LOG.isDebugEnabled())
+ {
+ StringBuilder fields = new StringBuilder() ;
+ Map<byte[], NavigableSet<byte[]>> familyMap = get.getFamilyMap() ;
+ if (familyMap != null && familyMap.size() > 0) {
+ for(byte[] columnfamily : familyMap.keySet() ) {
+ if (columnfamily != null && columnfamily.length > 0) {
+ NavigableSet<byte[]> columnNameSet = familyMap.get(columnfamily) ;
+ if (columnNameSet != null && columnNameSet.size() > 0) {
+ for(byte[] columnname : columnNameSet) {
+ fields.append("Field[" + Bytes.toString(columnfamily) + ":" + Bytes.toString(columnname) + "],") ;
+ }
+ }
+ else {
+ fields.append("Field[" + Bytes.toString(columnfamily) + ":null],") ;
+ }
+ }
+ }
+ }
+ else {
+ if (familyMap == null){
+ fields.append("{null}") ;
+ }
+ else {
+ fields.append("{empty}") ;
+ }
+ }
+ LOG.debug("preGet is checking permission for the following fields: {" + fields.toString() + "}");
+ }
+
+ boolean isPermGranted = isPermissionGranted("get", requestUser, TablePermission.Action.READ, e, get.getFamilyMap());
+
+ if (!isPermGranted) {
+ isPermGranted = hasFamilyQualifierPermission(requestUser, TablePermission.Action.READ, e, get.getFamilyMap());
+ if (isPermGranted) {
+ byte[] table = getTableName(e);
+ RangerAccessControlFilter filter = new RangerAccessControlFilter(requestUser, table);
+ if (get.getFilter() != null) {
+ FilterList wrapper = new FilterList(FilterList.Operator.MUST_PASS_ALL, Lists.newArrayList(filter, get.getFilter()));
+ get.setFilter(wrapper);
+ } else {
+ get.setFilter(filter);
+ }
+ } else {
+ throw new AccessDeniedException("Insufficient permissions (table=" + e.getRegion().getTableDesc().getNameAsString() + ", action=READ)");
+ }
+ }
+ }
+ @Override
+ public void postGetOp(final ObserverContext<RegionCoprocessorEnvironment> env, final Get get, final List<Cell> results) throws IOException {
+ HRegionInfo hri = env.getEnvironment().getRegion().getRegionInfo();
+
+ byte[] tableName = hri.getTable().getName() ;
+
+ if (!isSpecialTable(tableName)) {
+ try {
+ if (accessController.isAudited(tableName)) {
+ for (Cell cell : results) {
+ auditEvent("Get", tableName, cell.getFamily(), cell.getQualifier(), cell.getRow(), cell.getValue(), getActiveUser(), accessGrantedFlag);
+ }
+ }
+ } catch (Throwable t) {
+ }
+ }
+ }
+
+ @Override
+ public void preRegionOffline(ObserverContext<MasterCoprocessorEnvironment> c, HRegionInfo regionInfo) throws IOException {
+ requirePermission("regionOffline", regionInfo.getTable().getName(), null, null, Action.ADMIN);
+ }
+ @Override
+ public void postRegionOffline(ObserverContext<MasterCoprocessorEnvironment> c, HRegionInfo regionInfo) throws IOException {
+ auditEvent("regionOffline", regionInfo.getTable().getName(), null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ @Override
+ public void preCreateNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx, NamespaceDescriptor ns) throws IOException {
+ requireGlobalPermission("createNamespace", ns.getName(), Action.ADMIN);
+ }
+ @Override
+ public void postCreateNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx, NamespaceDescriptor ns) throws IOException {
+ if (accessController.isAudited(WILDCARD_MATCH)) {
+ auditEvent("createNamespace", ns.getName(), null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ }
+ @Override
+ public void preDeleteNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx, String namespace) throws IOException {
+ requireGlobalPermission("deleteNamespace", namespace, Action.ADMIN);
+ }
+ @Override
+ public void postDeleteNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx, String namespace) throws IOException {
+ if (accessController.isAudited(WILDCARD_MATCH)) {
+ auditEvent("deleteNamespace", namespace, null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ }
+ @Override
+ public void preModifyNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx, NamespaceDescriptor ns) throws IOException {
+ requireGlobalPermission("modifyNamespace", ns.getName(), Action.ADMIN);
+ }
+ @Override
+ public void postModifyNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx, NamespaceDescriptor ns) throws IOException {
+ if (accessController.isAudited(WILDCARD_MATCH)) {
+ auditEvent("modifyNamespace", ns.getName(), null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ }
+ @Override
+ public void preGetTableDescriptors(ObserverContext<MasterCoprocessorEnvironment> ctx, List<TableName> tableNamesList, List<HTableDescriptor> descriptors) throws IOException {
+ if (tableNamesList == null || tableNamesList.isEmpty()) { // If the list is empty, this is a request for all table descriptors and requires GLOBAL ADMIN privs.
+ requireGlobalPermission("getTableDescriptors", WILDCARD, Action.ADMIN);
+ } else { // Otherwise, if the requestor has ADMIN or CREATE privs for all listed tables, the request can be granted.
+ for (TableName tableName: tableNamesList) {
+ requirePermission("getTableDescriptors", tableName.getName(), null, null, Action.ADMIN, Action.CREATE);
+ }
+ }
+ }
+ @Override
+ public void postGetTableDescriptors(ObserverContext<MasterCoprocessorEnvironment> ctx, List<HTableDescriptor> descriptors) throws IOException {
+ if (descriptors == null || descriptors.isEmpty()) { // If the list is empty, this is a request for all table descriptors and requires GLOBAL ADMIN privs.
+ auditEvent("getTableDescriptors", WILDCARD, null, null, null, null, getActiveUser(), accessGrantedFlag);
+ } else { // Otherwise, if the requestor has ADMIN or CREATE privs for all listed tables, the request can be granted.
+ for (HTableDescriptor descriptor : descriptors) {
+ auditEvent("getTableDescriptors", descriptor.getName(), null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+ }
+ }
+ @Override
+ public void preMerge(ObserverContext<RegionServerCoprocessorEnvironment> ctx, HRegion regionA, HRegion regionB) throws IOException {
+ requirePermission("mergeRegions", regionA.getTableDesc().getTableName().getName(), null, null, Action.ADMIN);
+ }
+
+ @Override
+ public void postMerge(ObserverContext<RegionServerCoprocessorEnvironment> c, HRegion regionA, HRegion regionB, HRegion mergedRegion) throws IOException {
+ auditEvent("mergeRegions", regionA.getTableDesc().getTableName().getName(), null, null, null, null, getActiveUser(), accessGrantedFlag);
+ }
+
+ public void prePrepareBulkLoad(ObserverContext<RegionCoprocessorEnvironment> ctx, PrepareBulkLoadRequest request) throws IOException {
+ List<byte[]> cfs = null;
+
+ requirePermission("prePrepareBulkLoad", Permission.Action.WRITE, ctx.getEnvironment(), cfs);
+ }
+
+ public void preCleanupBulkLoad(ObserverContext<RegionCoprocessorEnvironment> ctx, CleanupBulkLoadRequest request) throws IOException {
+ List<byte[]> cfs = null;
+
+ requirePermission("preCleanupBulkLoad", Permission.Action.WRITE, ctx.getEnvironment(), cfs);
+ }
+
+ private void auditEvent(String eventName, byte[] tableName, byte[] columnFamilyName, byte[] qualifierName, byte[] row, byte[] value, User user, short accessFlag) {
+ auditEvent(eventName, Bytes.toString(tableName), Bytes.toString(columnFamilyName), Bytes.toString(qualifierName), row, value, user, accessFlag);
+ }
+
+ private void auditEvent(String eventName, String tableName, String columnFamilyName, String qualifierName, byte[] row, byte[] value, User user, short accessFlag) {
+
+ if (tableName != null && accessController.isAudited(tableName.getBytes())) {
+
+ String resourceType = "table";
+ String resourceName = tableName;
+ if (columnFamilyName != null && columnFamilyName.length() > 0) {
+ resourceName += "/" + columnFamilyName;
+ resourceType = "columnFamily";
+ }
+ if (qualifierName != null && qualifierName.length() > 0) {
+ resourceName += "/" + qualifierName;
+ resourceType = "column";
+ }
+
+ HBaseAuditEvent auditEvent = new HBaseAuditEvent();
+
+ auditEvent.setAclEnforcer(RangerModuleName);
+ auditEvent.setResourceType(resourceType);
+ auditEvent.setResourcePath(resourceName);
+ auditEvent.setAction(eventName);
+ auditEvent.setAccessType(eventName);
+ auditEvent.setUser(user == null ? RangerHadoopConstants.AUDITLOG_EMPTY_STRING : user.getShortName());
+ auditEvent.setAccessResult(accessFlag);
+ auditEvent.setClientIP(getRemoteAddress());
+ auditEvent.setEventTime(getUTCDate());
+ auditEvent.setRepositoryType(EnumRepositoryType.HBASE);
+ auditEvent.setRepositoryName(repositoryName);
+
+ try {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Writing audit log [" + auditEvent + "] - START.");
+ }
+ AuditProviderFactory.getAuditProvider().log(auditEvent);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Writing audit log [" + auditEvent + "] - END.");
+ }
+ }
+ catch(Throwable t) {
+ LOG.error("ERROR during audit log [" + auditEvent + "]", t);
+ }
+
+ }
+ }
+
+ public static Date getUTCDate() {
+ Calendar local=Calendar.getInstance();
+ int offset = local.getTimeZone().getOffset(local.getTimeInMillis());
+ GregorianCalendar utc = new GregorianCalendar(gmtTimeZone);
+ utc.setTimeInMillis(local.getTimeInMillis());
+ utc.add(Calendar.MILLISECOND, -offset);
+ return utc.getTime();
+ }
+
+ @Override
+ public void grant(RpcController controller, AccessControlProtos.GrantRequest request, RpcCallback<AccessControlProtos.GrantResponse> done) {
+ boolean isSuccess = false;
+
+ if(UpdateRangerPoliciesOnGrantRevoke) {
+ GrantRevokeData grData = null;
+
+ try {
+ grData = createGrantData(request);
+
+ RangerAdminRESTClient xaAdmin = new RangerAdminRESTClient();
+
+ xaAdmin.grantPrivilege(grData);
+
+ isSuccess = true;
+ } catch(IOException excp) {
+ LOG.warn("grant() failed", excp);
+
+ ResponseConverter.setControllerException(controller, excp);
+ } catch (Exception excp) {
+ LOG.warn("grant() failed", excp);
+
+ ResponseConverter.setControllerException(controller, new CoprocessorException(excp.getMessage()));
+ } finally {
+ byte[] tableName = grData == null ? null : StringUtil.getBytes(grData.getTables());
+
+ if(accessController.isAudited(tableName)) {
+ byte[] colFamily = grData == null ? null : StringUtil.getBytes(grData.getColumnFamilies());
+ byte[] qualifier = grData == null ? null : StringUtil.getBytes(grData.getColumns());
+
+ // Note: failed return from REST call will be logged as 'DENIED'
+ auditEvent("grant", tableName, colFamily, qualifier, null, null, getActiveUser(), isSuccess ? accessGrantedFlag : accessDeniedFlag);
+ }
+ }
+ }
+
+ AccessControlProtos.GrantResponse response = isSuccess ? AccessControlProtos.GrantResponse.getDefaultInstance() : null;
+
+ done.run(response);
+ }
+
+ @Override
+ public void revoke(RpcController controller, AccessControlProtos.RevokeRequest request, RpcCallback<AccessControlProtos.RevokeResponse> done) {
+ boolean isSuccess = false;
+
+ if(UpdateRangerPoliciesOnGrantRevoke) {
+ GrantRevokeData grData = null;
+
+ try {
+ grData = createRevokeData(request);
+
+ RangerAdminRESTClient xaAdmin = new RangerAdminRESTClient();
+
+ xaAdmin.revokePrivilege(grData);
+
+ isSuccess = true;
+ } catch(IOException excp) {
+ LOG.warn("revoke() failed", excp);
+
+ ResponseConverter.setControllerException(controller, excp);
+ } catch (Exception excp) {
+ LOG.warn("revoke() failed", excp);
+
+ ResponseConverter.setControllerException(controller, new CoprocessorException(excp.getMessage()));
+ } finally {
+ byte[] tableName = grData == null ? null : StringUtil.getBytes(grData.getTables());
+
+ if(accessController.isAudited(tableName)) {
+ byte[] colFamily = grData == null ? null : StringUtil.getBytes(grData.getColumnFamilies());
+ byte[] qualifier = grData == null ? null : StringUtil.getBytes(grData.getColumns());
+
+ // Note: failed return from REST call will be logged as 'DENIED'
+ auditEvent("revoke", tableName, colFamily, qualifier, null, null, getActiveUser(), isSuccess ? accessGrantedFlag : accessDeniedFlag);
+ }
+ }
+ }
+
+ AccessControlProtos.RevokeResponse response = isSuccess ? AccessControlProtos.RevokeResponse.getDefaultInstance() : null;
+
+ done.run(response);
+ }
+
+ @Override
+ public void checkPermissions(RpcController controller, AccessControlProtos.CheckPermissionsRequest request, RpcCallback<AccessControlProtos.CheckPermissionsResponse> done) {
+ LOG.debug("checkPermissions(): ");
+ }
+
+ @Override
+ public void getUserPermissions(RpcController controller, AccessControlProtos.GetUserPermissionsRequest request, RpcCallback<AccessControlProtos.GetUserPermissionsResponse> done) {
+ LOG.debug("getUserPermissions(): ");
+ }
+
+ @Override
+ public Service getService() {
+ return AccessControlProtos.AccessControlService.newReflectiveService(this);
+ }
+
+ private GrantRevokeData createGrantData(AccessControlProtos.GrantRequest request) throws Exception {
+ org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos.UserPermission up = request.getUserPermission();
+ org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos.Permission perm = up == null ? null : up.getPermission();
+
+ UserPermission userPerm = up == null ? null : ProtobufUtil.toUserPermission(up);
+ Permission.Action[] actions = userPerm == null ? null : userPerm.getActions();
+ String userName = userPerm == null ? null : Bytes.toString(userPerm.getUser());
+ String tableName = null;
+ String colFamily = null;
+ String qualifier = null;
+
+ if(perm == null) {
+ throw new Exception("grant(): invalid data - permission is null");
+ }
+
+ if(StringUtil.isEmpty(userName)) {
+ throw new Exception("grant(): invalid data - username empty");
+ }
+
+ if ((actions == null) || (actions.length == 0)) {
+ throw new Exception("grant(): invalid data - no action specified");
+ }
+
+ switch(perm.getType()) {
+ case Global:
+ tableName = colFamily = qualifier = "*";
+ break;
+
+ case Table:
+ tableName = Bytes.toString(userPerm.getTableName().getName());
+ colFamily = Bytes.toString(userPerm.getFamily());
+ qualifier = Bytes.toString(userPerm.getQualifier());
+ break;
+
+ case Namespace:
+ default:
+ LOG.warn("grant(): ignoring type '" + perm.getType().name() + "'");
+ break;
+ }
+
+ if(StringUtil.isEmpty(tableName) && StringUtil.isEmpty(colFamily) && StringUtil.isEmpty(qualifier)) {
+ throw new Exception("grant(): table/columnFamily/columnQualifier not specified");
+ }
+
+ PermMap permMap = new PermMap();
+
+ if(userName.startsWith(GROUP_PREFIX)) {
+ permMap.addGroup(userName.substring(GROUP_PREFIX.length()));
+ } else {
+ permMap.addUser(userName);
+ }
+
+ for (int i = 0; i < actions.length; i++) {
+ switch(actions[i].code()) {
+ case 'R':
+ case 'W':
+ case 'C':
+ case 'A':
+ permMap.addPerm(actions[i].name());
+ break;
+
+ default:
+ LOG.warn("grant(): ignoring action '" + actions[i].name() + "' for user '" + userName + "'");
+ }
+ }
+
+ User activeUser = getActiveUser();
+ String grantor = activeUser != null ? activeUser.getShortName() : null;
+
+ GrantRevokeData grData = new GrantRevokeData();
+
+ grData.setHBaseData(grantor, repositoryName, tableName, qualifier, colFamily, permMap);
+
+ return grData;
+ }
+
+ private GrantRevokeData createRevokeData(AccessControlProtos.RevokeRequest request) throws Exception {
+ org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos.UserPermission up = request.getUserPermission();
+ org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos.Permission perm = up == null ? null : up.getPermission();
+
+ UserPermission userPerm = up == null ? null : ProtobufUtil.toUserPermission(up);
+ String userName = userPerm == null ? null : Bytes.toString(userPerm.getUser());
+ String tableName = null;
+ String colFamily = null;
+ String qualifier = null;
+
+ if(perm == null) {
+ throw new Exception("revoke(): invalid data - permission is null");
+ }
+
+ if(StringUtil.isEmpty(userName)) {
+ throw new Exception("revoke(): invalid data - username empty");
+ }
+
+ switch(perm.getType()) {
+ case Global :
+ tableName = colFamily = qualifier = "*";
+ break;
+
+ case Table :
+ tableName = Bytes.toString(userPerm.getTableName().getName());
+ colFamily = Bytes.toString(userPerm.getFamily());
+ qualifier = Bytes.toString(userPerm.getQualifier());
+ break;
+
+ case Namespace:
+ default:
+ LOG.warn("revoke(): ignoring type '" + perm.getType().name() + "'");
+ break;
+ }
+
+ if(StringUtil.isEmpty(tableName) && StringUtil.isEmpty(colFamily) && StringUtil.isEmpty(qualifier)) {
+ throw new Exception("revoke(): table/columnFamily/columnQualifier not specified");
+ }
+
+ PermMap permMap = new PermMap();
+
+ if(userName.startsWith(GROUP_PREFIX)) {
+ permMap.addGroup(userName.substring(GROUP_PREFIX.length()));
+ } else {
+ permMap.addUser(userName);
+ }
+
+ // revoke removes all permissions
+ permMap.addPerm(Permission.Action.READ.name());
+ permMap.addPerm(Permission.Action.WRITE.name());
+ permMap.addPerm(Permission.Action.CREATE.name());
+ permMap.addPerm(Permission.Action.ADMIN.name());
+
+ User activeUser = getActiveUser();
+ String grantor = activeUser != null ? activeUser.getShortName() : null;
+
+ GrantRevokeData grData = new GrantRevokeData();
+
+ grData.setHBaseData(grantor, repositoryName, tableName, qualifier, colFamily, permMap);
+
+ return grData;
+ }
+}
[46/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-common/src/main/java/com/xasecure/admin/client/XaAdminRESTClient.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/com/xasecure/admin/client/XaAdminRESTClient.java b/agents-common/src/main/java/com/xasecure/admin/client/XaAdminRESTClient.java
deleted file mode 100644
index c64b02d..0000000
--- a/agents-common/src/main/java/com/xasecure/admin/client/XaAdminRESTClient.java
+++ /dev/null
@@ -1,390 +0,0 @@
-/*
- * 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 com.xasecure.admin.client;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.List;
-import java.security.KeyManagementException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.SecureRandom;
-import java.security.UnrecoverableKeyException;
-import java.security.cert.CertificateException;
-
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
-
-import com.sun.jersey.api.client.Client;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.WebResource;
-import com.sun.jersey.api.client.config.ClientConfig;
-import com.sun.jersey.api.client.config.DefaultClientConfig;
-import com.sun.jersey.client.urlconnection.HTTPSProperties;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.conf.Configuration;
-
-import com.xasecure.admin.client.datatype.GrantRevokeData;
-import com.xasecure.admin.client.datatype.RESTResponse;
-import com.xasecure.authorization.utils.StringUtil;
-import com.xasecure.authorization.hadoop.config.XaSecureConfiguration;
-import com.xasecure.authorization.hadoop.utils.XaSecureCredentialProvider;
-
-
-public class XaAdminRESTClient implements XaAdminClient {
- private static final Log LOG = LogFactory.getLog(XaAdminRESTClient.class);
-
- public static final String XASECURE_PROP_POLICYMGR_URL = "xasecure.policymgr.url";
- public static final String XASECURE_PROP_POLICYMGR_SSLCONFIG_FILENAME = "xasecure.policymgr.sslconfig.filename";
-
- public static final String XASECURE_POLICYMGR_CLIENT_KEY_FILE = "xasecure.policymgr.clientssl.keystore";
- public static final String XASECURE_POLICYMGR_CLIENT_KEY_FILE_PASSWORD = "xasecure.policymgr.clientssl.keystore.password";
- public static final String XASECURE_POLICYMGR_CLIENT_KEY_FILE_TYPE = "xasecure.policymgr.clientssl.keystore.type";
- public static final String XASECURE_POLICYMGR_CLIENT_KEY_FILE_CREDENTIAL = "xasecure.policymgr.clientssl.keystore.credential.file";
- public static final String XASECURE_POLICYMGR_CLIENT_KEY_FILE_CREDENTIAL_ALIAS = "sslKeyStore";
- public static final String XASECURE_POLICYMGR_CLIENT_KEY_FILE_TYPE_DEFAULT = "jks";
-
- public static final String XASECURE_POLICYMGR_TRUSTSTORE_FILE = "xasecure.policymgr.clientssl.truststore";
- public static final String XASECURE_POLICYMGR_TRUSTSTORE_FILE_PASSWORD = "xasecure.policymgr.clientssl.truststore.password";
- public static final String XASECURE_POLICYMGR_TRUSTSTORE_FILE_TYPE = "xasecure.policymgr.clientssl.truststore.type";
- public static final String XASECURE_POLICYMGR_TRUSTSTORE_FILE_CREDENTIAL = "xasecure.policymgr.clientssl.truststore.credential.file";
- public static final String XASECURE_POLICYMGR_TRUSTSTORE_FILE_CREDENTIAL_ALIAS = "sslTrustStore";
- public static final String XASECURE_POLICYMGR_TRUSTSTORE_FILE_TYPE_DEFAULT = "jks";
-
- public static final String XASECURE_SSL_KEYMANAGER_ALGO_TYPE = "SunX509" ;
- public static final String XASECURE_SSL_TRUSTMANAGER_ALGO_TYPE = "SunX509" ;
- public static final String XASECURE_SSL_CONTEXT_ALGO_TYPE = "SSL" ;
-
- public static final String REST_EXPECTED_MIME_TYPE = "application/json" ;
-
- private static final String REST_URL_PATH_POLICYLIST = "/service/assets/policyList/";
- private static final String REST_URL_PATH_GRANT = "/service/assets/resources/grant";
- private static final String REST_URL_PATH_REVOKE = "/service/assets/resources/revoke";
- private static final String REST_URL_PARAM_LASTUPDATED_TIME = "epoch";
- private static final String REST_URL_PARAM_POLICY_COUNT = "policyCount";
- private static final String REST_URL_PARAM_AGENT_NAME = "agentId";
-
- private String mUrl = null;
- private String mSslConfigFileName = null;
- private boolean mIsSSL = false;
-
- private String mKeyStoreURL = null;
- private String mKeyStoreAlias = null;
- private String mKeyStoreFile = null;
- private String mKeyStoreType = null;
- private String mTrustStoreURL = null;
- private String mTrustStoreAlias = null;
- private String mTrustStoreFile = null;
- private String mTrustStoreType = null;
-
-
- public XaAdminRESTClient() {
- mUrl = XaSecureConfiguration.getInstance().get(XASECURE_PROP_POLICYMGR_URL);
- mSslConfigFileName = XaSecureConfiguration.getInstance().get(XASECURE_PROP_POLICYMGR_SSLCONFIG_FILENAME);
-
- init();
- }
-
- public XaAdminRESTClient(String url, String sslConfigFileName) {
- mUrl = url;
- mSslConfigFileName = sslConfigFileName;
-
- init();
- }
-
- @Override
- public String getPolicies(String repositoryName, long lastModifiedTime, int policyCount, String agentName) {
- String ret = null;
- Client client = null;
-
- try {
- client = buildClient();
-
- WebResource webResource = client.resource(mUrl + REST_URL_PATH_POLICYLIST + repositoryName)
- .queryParam(REST_URL_PARAM_LASTUPDATED_TIME, String.valueOf(lastModifiedTime))
- .queryParam(REST_URL_PARAM_POLICY_COUNT, String.valueOf(policyCount))
- .queryParam(REST_URL_PARAM_AGENT_NAME, agentName);
-
- ClientResponse response = webResource.accept(REST_EXPECTED_MIME_TYPE).get(ClientResponse.class);
-
- if(response != null && response.getStatus() == 200) {
- ret = response.getEntity(String.class);
- }
- } finally {
- destroy(client);
- }
-
- return ret;
- }
-
- @Override
- public void grantPrivilege(GrantRevokeData grData) throws Exception {
- Client client = null;
-
- try {
- client = buildClient();
-
- WebResource webResource = client.resource(mUrl + REST_URL_PATH_GRANT);
-
- ClientResponse response = webResource.accept(REST_EXPECTED_MIME_TYPE).type(REST_EXPECTED_MIME_TYPE).post(ClientResponse.class, grData.toJson());
-
- if(response == null || response.getStatus() != 200) {
- RESTResponse resp = RESTResponse.fromClientResponse(response);
-
- throw new Exception(resp.getMessage());
- }
- } finally {
- destroy(client);
- }
- }
-
- @Override
- public void revokePrivilege(GrantRevokeData grData) throws Exception {
- Client client = null;
-
- try {
- client = buildClient();
-
- WebResource webResource = client.resource(mUrl + REST_URL_PATH_REVOKE);
-
- ClientResponse response = webResource.accept(REST_EXPECTED_MIME_TYPE).type(REST_EXPECTED_MIME_TYPE).post(ClientResponse.class, grData.toJson());
-
- if(response == null || response.getStatus() != 200) {
- RESTResponse resp = RESTResponse.fromClientResponse(response);
-
- throw new Exception(resp.getMessage());
- }
- } finally {
- destroy(client);
- }
- }
- private void init() {
- mIsSSL = StringUtil.containsIgnoreCase(mUrl, "https");
-
- InputStream in = null ;
-
- try {
- Configuration conf = new Configuration() ;
-
- in = getFileInputStream(mSslConfigFileName) ;
-
- if (in != null) {
- conf.addResource(in);
- }
-
- mKeyStoreURL = conf.get(XASECURE_POLICYMGR_CLIENT_KEY_FILE_CREDENTIAL);
- mKeyStoreAlias = XASECURE_POLICYMGR_CLIENT_KEY_FILE_CREDENTIAL_ALIAS;
- mKeyStoreType = conf.get(XASECURE_POLICYMGR_CLIENT_KEY_FILE_TYPE, XASECURE_POLICYMGR_CLIENT_KEY_FILE_TYPE_DEFAULT);
- mKeyStoreFile = conf.get(XASECURE_POLICYMGR_CLIENT_KEY_FILE);
-
- mTrustStoreURL = conf.get(XASECURE_POLICYMGR_TRUSTSTORE_FILE_CREDENTIAL);
- mTrustStoreAlias = XASECURE_POLICYMGR_TRUSTSTORE_FILE_CREDENTIAL_ALIAS;
- mTrustStoreType = conf.get(XASECURE_POLICYMGR_TRUSTSTORE_FILE_TYPE, XASECURE_POLICYMGR_TRUSTSTORE_FILE_TYPE_DEFAULT);
- mTrustStoreFile = conf.get(XASECURE_POLICYMGR_TRUSTSTORE_FILE);
- }
- catch(IOException ioe) {
- LOG.error("Unable to load SSL Config FileName: [" + mSslConfigFileName + "]", ioe);
- }
- finally {
- close(in, mSslConfigFileName);
- }
- }
-
- private synchronized Client buildClient() {
- Client client = null;
-
- if (mIsSSL) {
- KeyManager[] kmList = getKeyManagers();
- TrustManager[] tmList = getTrustManagers();
- SSLContext sslContext = getSSLContext(kmList, tmList);
- ClientConfig config = new DefaultClientConfig();
-
- HostnameVerifier hv = new HostnameVerifier() {
- public boolean verify(String urlHostName, SSLSession session) {
- return session.getPeerHost().equals(urlHostName);
- }
- };
-
- config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(hv, sslContext));
-
- client = Client.create(config);
- }
-
- if(client == null) {
- client = Client.create();
- }
-
- return client;
- }
-
- private KeyManager[] getKeyManagers() {
- KeyManager[] kmList = null;
-
- String keyStoreFilepwd = getCredential(mKeyStoreURL, mKeyStoreAlias);
-
- if (!StringUtil.isEmpty(mKeyStoreFile) && !StringUtil.isEmpty(keyStoreFilepwd)) {
- InputStream in = null ;
-
- try {
- in = getFileInputStream(mKeyStoreFile) ;
-
- if (in != null) {
- KeyStore keyStore = KeyStore.getInstance(mKeyStoreType);
-
- keyStore.load(in, keyStoreFilepwd.toCharArray());
-
- KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(XASECURE_SSL_KEYMANAGER_ALGO_TYPE);
-
- keyManagerFactory.init(keyStore, keyStoreFilepwd.toCharArray());
-
- kmList = keyManagerFactory.getKeyManagers();
- } else {
- LOG.error("Unable to obtain keystore from file [" + mKeyStoreFile + "]");
- }
- } catch (KeyStoreException e) {
- LOG.error("Unable to obtain from KeyStore", e);
- } catch (NoSuchAlgorithmException e) {
- LOG.error("SSL algorithm is available in the environment", e);
- } catch (CertificateException e) {
- LOG.error("Unable to obtain the requested certification ", e);
- } catch (FileNotFoundException e) {
- LOG.error("Unable to find the necessary SSL Keystore and TrustStore Files", e);
- } catch (IOException e) {
- LOG.error("Unable to read the necessary SSL Keystore and TrustStore Files", e);
- } catch (UnrecoverableKeyException e) {
- LOG.error("Unable to recover the key from keystore", e);
- } finally {
- close(in, mKeyStoreFile);
- }
- }
-
- return kmList;
- }
-
- private TrustManager[] getTrustManagers() {
- TrustManager[] tmList = null;
-
- String trustStoreFilepwd = getCredential(mTrustStoreURL, mTrustStoreAlias);
-
- if (!StringUtil.isEmpty(mTrustStoreFile) && !StringUtil.isEmpty(trustStoreFilepwd)) {
- InputStream in = null ;
-
- try {
- in = getFileInputStream(mTrustStoreFile) ;
-
- if (in != null) {
- KeyStore trustStore = KeyStore.getInstance(mTrustStoreType);
-
- trustStore.load(in, trustStoreFilepwd.toCharArray());
-
- TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(XASECURE_SSL_TRUSTMANAGER_ALGO_TYPE);
-
- trustManagerFactory.init(trustStore);
-
- tmList = trustManagerFactory.getTrustManagers();
- } else {
- LOG.error("Unable to obtain keystore from file [" + mTrustStoreFile + "]");
- }
- } catch (KeyStoreException e) {
- LOG.error("Unable to obtain from KeyStore", e);
- } catch (NoSuchAlgorithmException e) {
- LOG.error("SSL algorithm is available in the environment", e);
- } catch (CertificateException e) {
- LOG.error("Unable to obtain the requested certification ", e);
- } catch (FileNotFoundException e) {
- LOG.error("Unable to find the necessary SSL Keystore and TrustStore Files", e);
- } catch (IOException e) {
- LOG.error("Unable to read the necessary SSL Keystore and TrustStore Files", e);
- } finally {
- close(in, mTrustStoreFile);
- }
- }
-
- return tmList;
- }
-
- private SSLContext getSSLContext(KeyManager[] kmList, TrustManager[] tmList) {
- try {
- if(kmList != null && tmList != null) {
- SSLContext sslContext = SSLContext.getInstance(XASECURE_SSL_CONTEXT_ALGO_TYPE);
-
- sslContext.init(kmList, tmList, new SecureRandom());
-
- return sslContext;
- }
- } catch (NoSuchAlgorithmException e) {
- LOG.error("SSL algorithm is available in the environment", e);
- } catch (KeyManagementException e) {
- LOG.error("Unable to initials the SSLContext", e);
- }
-
- return null;
- }
-
- private String getCredential(String url, String alias) {
- char[] credStr = XaSecureCredentialProvider.getInstance().getCredentialString(url, alias);
-
- return credStr == null ? null : new String(credStr);
- }
-
- private InputStream getFileInputStream(String fileName) throws IOException {
- InputStream in = null ;
-
- if(! StringUtil.isEmpty(fileName)) {
- File f = new File(fileName) ;
-
- if (f.exists()) {
- in = new FileInputStream(f) ;
- }
- else {
- in = ClassLoader.getSystemResourceAsStream(fileName) ;
- }
- }
-
- return in ;
- }
-
- private void close(InputStream str, String filename) {
- if (str != null) {
- try {
- str.close() ;
- } catch (IOException excp) {
- LOG.error("Error while closing file: [" + filename + "]", excp) ;
- }
- }
- }
-
- private void destroy(Client client) {
- if(client != null) {
- client.destroy();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-common/src/main/java/com/xasecure/admin/client/datatype/GrantRevokeData.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/com/xasecure/admin/client/datatype/GrantRevokeData.java b/agents-common/src/main/java/com/xasecure/admin/client/datatype/GrantRevokeData.java
deleted file mode 100644
index b5228db..0000000
--- a/agents-common/src/main/java/com/xasecure/admin/client/datatype/GrantRevokeData.java
+++ /dev/null
@@ -1,273 +0,0 @@
-/*
- * 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 com.xasecure.admin.client.datatype;
-
-
-import java.io.IOException;
-import java.util.List;
-import java.util.ArrayList;
-
-import org.codehaus.jackson.JsonGenerationException;
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-import org.codehaus.jackson.map.JsonMappingException;
-import org.codehaus.jackson.map.ObjectMapper;
-
-import com.xasecure.authorization.utils.StringUtil;
-
-
-@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY)
-@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
-@JsonIgnoreProperties(ignoreUnknown = true)
-public class GrantRevokeData implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
- private String grantor;
- private String repositoryName;
- private String repositoryType;
- private String databases;
- private String tables;
- private String columns;
- private String columnFamilies;
- private boolean isEnabled;
- private boolean isAuditEnabled;
- private boolean replacePerm;
- private List<PermMap> permMapList = new ArrayList<PermMap>();
-
- private static String WILDCARD_ASTERISK = "*";
-
-
- public GrantRevokeData() {
- }
-
- public String getGrantor() {
- return grantor;
- }
-
- public void setGrantor(String grantor) {
- this.grantor = grantor;
- }
-
- public String getRepositoryName() {
- return repositoryName;
- }
-
- public void setRepositoryName(String repositoryName) {
- this.repositoryName = repositoryName;
- }
-
- public String getRepositoryType() {
- return repositoryType;
- }
-
- public void setRepositoryType(String repositoryType) {
- this.repositoryType = repositoryType;
- }
-
- public String getDatabases() {
- return databases;
- }
-
- public void setDatabases(String databases) {
- this.databases = databases;
- }
-
- public String getTables() {
- return tables;
- }
-
- public void setTables(String tables) {
- this.tables = tables;
- }
-
- public String getColumns() {
- return columns;
- }
-
- public void setColumns(String columns) {
- this.columns = columns;
- }
-
- public String getColumnFamilies() {
- return columnFamilies;
- }
-
- public void setColumnFamilies(String columnFamilies) {
- this.columnFamilies = columnFamilies;
- }
-
- public List<PermMap> getPermMapList() {
- return permMapList;
- }
-
- public void setPermMapList(List<PermMap> permMapList) {
- this.permMapList = permMapList;
- }
-
-
- public void setHiveData(String grantor,
- String repositoryName,
- String databases,
- String tables,
- String columns,
- PermMap permMap) {
- this.grantor = grantor;
- this.repositoryName = repositoryName;
- this.repositoryType = "hive";
- this.databases = StringUtil.isEmpty(databases) ? WILDCARD_ASTERISK : databases;
- this.tables = StringUtil.isEmpty(tables) ? WILDCARD_ASTERISK : tables;
- this.columns = StringUtil.isEmpty(columns) ? WILDCARD_ASTERISK : columns;
- this.isAuditEnabled = true;
- this.isEnabled = true;
- this.replacePerm = false;
- this.permMapList.add(permMap);
- }
-
- public void setHBaseData(String grantor,
- String repositoryName,
- String tables,
- String columns,
- String columnFamilies,
- PermMap permMap) {
- this.grantor = grantor;
- this.repositoryName = repositoryName;
- this.repositoryType = "hbase";
- this.tables = StringUtil.isEmpty(tables) ? WILDCARD_ASTERISK : tables;
- this.columns = StringUtil.isEmpty(columns) ? WILDCARD_ASTERISK : columns;
- this.columnFamilies = StringUtil.isEmpty(columnFamilies) ? WILDCARD_ASTERISK : columnFamilies;
- this.isAuditEnabled = true;
- this.isEnabled = true;
- this.replacePerm = true;
- this.permMapList.add(permMap);
- }
-
- public String toJson() {
- try {
- ObjectMapper om = new ObjectMapper();
-
- return om.writeValueAsString(this);
- } catch (JsonGenerationException e) {
- e.printStackTrace();
- } catch (JsonMappingException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- return "";
- }
-
- @Override
- public String toString() {
- return toJson();
- }
-
-
- @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY)
- @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
- @JsonIgnoreProperties(ignoreUnknown = true)
- public static class PermMap {
- private List<String> userList = new ArrayList<String>();
- private List<String> groupList = new ArrayList<String>();
- private List<String> permList = new ArrayList<String>();
-
- public PermMap() {
- }
-
- public PermMap(String user, String group, String perm) {
- addUser(user);
- addGroup(group);
- addPerm(perm);
- }
-
- public PermMap(List<String> userList, List<String> groupList, List<String> permList) {
- copyList(userList, this.userList);
- copyList(groupList, this.groupList);
- copyList(permList, this.permList);
- }
-
- public List<String> getUserList() {
- return userList;
- }
-
- public List<String> getGroupList() {
- return groupList;
- }
-
- public List<String> getPermList() {
- return permList;
- }
-
- public void addUser(String user) {
- addToList(user, userList);
- }
-
- public void addGroup(String group) {
- addToList(group, groupList);
- }
-
- public void addPerm(String perm) {
- addToList(perm, permList);
- }
-
- private void addToList(String str, List<String> list) {
- if(list != null && !StringUtil.isEmpty(str)) {
- list.add(str);
- }
- }
-
- private void copyList(List<String> fromList, List<String> toList) {
- if(fromList != null && toList != null) {
- for(String str : fromList) {
- addToList(str, toList);
- }
- }
- }
-
- public String toJson() {
- try {
- ObjectMapper om = new ObjectMapper();
-
- return om.writeValueAsString(this);
- } catch (JsonGenerationException e) {
- e.printStackTrace();
- } catch (JsonMappingException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- return "";
- }
-
- @Override
- public String toString() {
- return toJson();
- }
- }
-
- public static void main(String[] args) {
- GrantRevokeData grData = new GrantRevokeData();
-
- System.out.println(grData.toString());
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-common/src/main/java/com/xasecure/admin/client/datatype/RESTResponse.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/com/xasecure/admin/client/datatype/RESTResponse.java b/agents-common/src/main/java/com/xasecure/admin/client/datatype/RESTResponse.java
deleted file mode 100644
index 389b547..0000000
--- a/agents-common/src/main/java/com/xasecure/admin/client/datatype/RESTResponse.java
+++ /dev/null
@@ -1,208 +0,0 @@
-/**
- *
- * 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 com.xasecure.admin.client.datatype;
-
-import java.util.List;
-
-import org.apache.log4j.Logger;
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.map.ObjectMapper;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-import com.sun.jersey.api.client.ClientResponse;
-import com.xasecure.authorization.utils.StringUtil;
-
-
-@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY)
-@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
-@JsonIgnoreProperties(ignoreUnknown = true)
-public class RESTResponse {
- private static Logger LOG = Logger.getLogger(RESTResponse.class);
-
- private int httpStatusCode;
- private int statusCode;
- private String msgDesc;
- private List<Message> messageList;
-
-
- public int getHttpStatusCode() {
- return httpStatusCode;
- }
-
- public void setHttpStatusCode(int httpStatusCode) {
- this.httpStatusCode = httpStatusCode;
- }
-
- public int getStatusCode() {
- return statusCode;
- }
-
- public void setStatusCode(int statusCode) {
- this.statusCode = statusCode;
- }
-
- public String getMsgDesc() {
- return msgDesc;
- }
-
- public void setMsgDesc(String msgDesc) {
- this.msgDesc = msgDesc;
- }
-
- public List<Message> getMessageList() {
- return messageList;
- }
-
- public void setMessageList(List<Message> messageList) {
- this.messageList = messageList;
- }
-
- public String getMessage() {
- return StringUtil.isEmpty(msgDesc) ? ("HTTP " + httpStatusCode) : msgDesc;
- }
-
- public static RESTResponse fromClientResponse(ClientResponse response) {
- RESTResponse ret = null;
-
- String jsonString = response == null ? null : response.getEntity(String.class);
- int httpStatus = response == null ? 0 : response.getStatus();
-
- if(! StringUtil.isEmpty(jsonString)) {
- ret = RESTResponse.fromJson(jsonString);
- }
-
- if(ret == null) {
- ret = new RESTResponse();
- }
-
- ret.setHttpStatusCode(httpStatus);
-
- return ret;
- }
-
- public String toJson() {
- try {
- ObjectMapper om = new ObjectMapper();
-
- return om.writeValueAsString(this);
- } catch (Exception e) {
- if(LOG.isDebugEnabled()) {
- LOG.debug("toJson() failed", e);
- }
- }
-
- return "";
- }
-
- public static RESTResponse fromJson(String jsonString) {
- try {
- ObjectMapper om = new ObjectMapper();
-
- return om.readValue(jsonString, RESTResponse.class);
- } catch (Exception e) {
- if(LOG.isDebugEnabled()) {
- LOG.debug("fromJson('" + jsonString + "') failed", e);
- }
- }
-
- return null;
- }
-
- @Override
- public String toString() {
- return toJson();
- }
-
- @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY)
- @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
- @JsonIgnoreProperties(ignoreUnknown = true)
- public static class Message {
- private String name;
- private String rbKey;
- private String message;
- private Long objectId;
- private String fieldName;
-
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getRbKey() {
- return rbKey;
- }
- public void setRbKey(String rbKey) {
- this.rbKey = rbKey;
- }
- public String getMessage() {
- return message;
- }
- public void setMessage(String message) {
- this.message = message;
- }
- public Long getObjectId() {
- return objectId;
- }
- public void setObjectId(Long objectId) {
- this.objectId = objectId;
- }
- public String getFieldName() {
- return fieldName;
- }
- public void setFieldName(String fieldName) {
- this.fieldName = fieldName;
- }
-
- public String toJson() {
- try {
- ObjectMapper om = new ObjectMapper();
-
- return om.writeValueAsString(this);
- } catch (Exception e) {
- if(LOG.isDebugEnabled()) {
- LOG.debug("toJson() failed", e);
- }
- }
-
- return "";
- }
-
- public static RESTResponse fromJson(String jsonString) {
- try {
- ObjectMapper om = new ObjectMapper();
-
- return om.readValue(jsonString, RESTResponse.class);
- } catch (Exception e) {
- if(LOG.isDebugEnabled()) {
- LOG.debug("fromJson('" + jsonString + "') failed", e);
- }
- }
-
- return null;
- }
-
- @Override
- public String toString() {
- return toJson();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-common/src/main/java/com/xasecure/authorization/hadoop/config/XaSecureConfiguration.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/com/xasecure/authorization/hadoop/config/XaSecureConfiguration.java b/agents-common/src/main/java/com/xasecure/authorization/hadoop/config/XaSecureConfiguration.java
deleted file mode 100644
index f32c5b7..0000000
--- a/agents-common/src/main/java/com/xasecure/authorization/hadoop/config/XaSecureConfiguration.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * 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 com.xasecure.authorization.hadoop.config;
-
-import java.io.File;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.Properties;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.log4j.Logger;
-
-import com.xasecure.audit.provider.AuditProviderFactory;
-import com.xasecure.authorization.hadoop.constants.XaSecureHadoopConstants;
-
-public class XaSecureConfiguration extends Configuration {
-
- private static final Logger LOG = Logger.getLogger(XaSecureConfiguration.class) ;
-
- private static XaSecureConfiguration config = null;
-
- private XaSecureConfiguration() {
- super(false) ;
-
- //
- // WorkAround for having all Hadoop Configuration in the CLASSPATH first, even if it is invoked by Hive Engine.
- //
- // So, we look for "hive-site.xml", if it is available, take the xasecure-audit.xml file from the same location.
- // If we do not see "hive-site.xml", we look for "hbase-site.xml", if found, take the xasecure-audit.xml file from the same location.
- // If we do not see "hbase-site.xml", we look for "hdfs-site.xml", if found, take the xasecure-audit.xml file from the same location.
- // If we do not see, we let the CLASSPATH based search to find xasecure-audit.xml file.
-
-
- URL auditFileLocation = getXAAuditXMLFileLocation() ;
-
- if (auditFileLocation != null) {
- addResource(auditFileLocation) ;
- }
- else {
- addResourceIfReadable(XaSecureHadoopConstants.XASECURE_AUDIT_FILE) ;
- }
- addResourceIfReadable(XaSecureHadoopConstants.XASECURE_HDFS_SECURITY_FILE);
- addResourceIfReadable(XaSecureHadoopConstants.XASECURE_KNOX_SECURITY_FILE);
- addResourceIfReadable(XaSecureHadoopConstants.XASECURE_HBASE_SECURITY_FILE) ;
- addResourceIfReadable(XaSecureHadoopConstants.XASECURE_HIVE_SECURITY_FILE) ;
- addResourceIfReadable(XaSecureHadoopConstants.XASECURE_STORM_SECURITY_FILE);
-
- }
-
- @SuppressWarnings("deprecation")
- private void addResourceIfReadable(String aResourceName) {
- String fName = getFileLocation(aResourceName) ;
- if (fName != null) {
- File f = new File(fName) ;
- if (f.exists() && f.canRead()) {
- URL fUrl = null ;
- try {
- fUrl = f.toURL() ;
- addResource(fUrl) ;
- } catch (MalformedURLException e) {
- LOG.debug("Unable to find URL for the resource name [" + aResourceName +"]. Ignoring the resource:" + aResourceName);
- }
- }
- }
- }
-
-
- public static XaSecureConfiguration getInstance() {
- if (config == null) {
- synchronized (XaSecureConfiguration.class) {
- XaSecureConfiguration temp = config;
- if (temp == null) {
- config = new XaSecureConfiguration();
- }
- }
- }
- return config;
- }
-
- public void initAudit(AuditProviderFactory.ApplicationType appType) {
- AuditProviderFactory auditFactory = AuditProviderFactory.getInstance();
-
- if(auditFactory == null) {
- LOG.error("Unable to find the AuditProviderFactory. (null) found") ;
- return;
- }
-
- Properties props = getProps();
-
- if(props == null) {
- return;
- }
-
- if(! auditFactory.isInitDone()) {
- auditFactory.init(props, appType);
- }
- }
-
- public boolean isAuditInitDone() {
- AuditProviderFactory auditFactory = AuditProviderFactory.getInstance();
-
- return auditFactory != null && auditFactory.isInitDone();
- }
-
-
- @SuppressWarnings("deprecation")
- public URL getXAAuditXMLFileLocation() {
- URL ret = null ;
-
- try {
- for(String cfgFile : new String[] { "hive-site.xml", "hbase-site.xml", "hdfs-site.xml" } ) {
- String loc = getFileLocation(cfgFile) ;
- if (loc != null) {
- if (new File(loc).canRead()) {
- File parentFile = new File(loc).getParentFile() ;
- ret = new File(parentFile, XaSecureHadoopConstants.XASECURE_AUDIT_FILE).toURL() ;
- break ;
- }
- }
- }
- }
- catch(Throwable t) {
- LOG.error("Unable to locate audit file location." , t) ;
- ret = null ;
- }
-
- return ret ;
- }
-
- private String getFileLocation(String fileName) {
-
- String ret = null ;
-
- URL lurl = XaSecureConfiguration.class.getClassLoader().getResource(fileName) ;
-
- if (lurl == null ) {
- lurl = XaSecureConfiguration.class.getClassLoader().getResource("/" + fileName) ;
- }
-
- if (lurl != null) {
- ret = lurl.getFile() ;
- }
-
- return ret ;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-common/src/main/java/com/xasecure/authorization/hadoop/constants/XaSecureHadoopConstants.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/com/xasecure/authorization/hadoop/constants/XaSecureHadoopConstants.java b/agents-common/src/main/java/com/xasecure/authorization/hadoop/constants/XaSecureHadoopConstants.java
deleted file mode 100644
index 64794d1..0000000
--- a/agents-common/src/main/java/com/xasecure/authorization/hadoop/constants/XaSecureHadoopConstants.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/**
- * 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 com.xasecure.authorization.hadoop.constants;
-
-public class XaSecureHadoopConstants {
-
- public static final String XASECURE_AUDIT_FILE = "xasecure-audit.xml" ;
- public static final String XASECURE_HDFS_SECURITY_FILE = "xasecure-hdfs-security.xml" ;
- public static final String XASECURE_KNOX_SECURITY_FILE = "xasecure-knox-security.xml" ;
- public static final String XASECURE_HBASE_SECURITY_FILE = "xasecure-hbase-security.xml" ;
- public static final String XASECURE_HIVE_SECURITY_FILE = "xasecure-hive-security.xml" ;
- public static final String XASECURE_POLICYMGR_SSL_FILE = "xasecure-policymgr-ssl.xml" ;
- public static final String XASECURE_STORM_SECURITY_FILE = "xasecure-storm-security.xml" ;
-
- public static final String XASECURE_ADD_HDFS_PERMISSION_PROP = "xasecure.add-hadoop-authorization" ;
- public static final boolean XASECURE_ADD_HDFS_PERMISSION_DEFAULT = false ;
- public static final String READ_ACCCESS_TYPE = "read";
- public static final String WRITE_ACCCESS_TYPE = "write";
- public static final String EXECUTE_ACCCESS_TYPE = "execute";
-
- public static final String HDFS_ROOT_FOLDER_PATH_ALT = "";
- public static final String HDFS_ROOT_FOLDER_PATH = "/";
-
- public static final String HDFS_ACCESS_VERIFIER_CLASS_NAME_PROP = "hdfs.authorization.verifier.classname" ;
- public static final String HDFS_ACCESS_VERIFIER_CLASS_NAME_DEFAULT_VALUE = "com.xasecure.pdp.hdfs.XASecureAuthorizer" ;
-
- public static final String HIVE_ACCESS_VERIFIER_CLASS_NAME_PROP = "hive.authorization.verifier.classname" ;
- public static final String HIVE_ACCESS_VERIFIER_CLASS_NAME_DEFAULT_VALUE = "com.xasecure.pdp.hive.XASecureAuthorizer" ;
-
- public static final String HIVE_UPDATE_XAPOLICIES_ON_GRANT_REVOKE_PROP = "xasecure.hive.update.xapolicies.on.grant.revoke" ;
- public static final boolean HIVE_UPDATE_XAPOLICIES_ON_GRANT_REVOKE_DEFAULT_VALUE = true;
-
- public static final String HBASE_UPDATE_XAPOLICIES_ON_GRANT_REVOKE_PROP = "xasecure.hbase.update.xapolicies.on.grant.revoke" ;
- public static final boolean HBASE_UPDATE_XAPOLICIES_ON_GRANT_REVOKE_DEFAULT_VALUE = true;
-
- public static final String KNOX_ACCESS_VERIFIER_CLASS_NAME_PROP = "knox.authorization.verifier.classname" ;
- public static final String KNOX_ACCESS_VERIFIER_CLASS_NAME_DEFAULT_VALUE = "com.xasecure.pdp.knox.XASecureAuthorizer" ;
-
- public static final String HBASE_ACCESS_VERIFIER_CLASS_NAME_PROP = "hbase.authorization.verifier.classname" ;
- public static final String HBASE_ACCESS_VERIFIER_CLASS_NAME_DEFAULT_VALUE = "com.xasecure.pdp.hbase.XASecureAuthorizer" ;
-
- public static final String STORM_ACCESS_VERIFIER_CLASS_NAME_PROP = "storm.authorization.verifier.classname" ;
- public static final String STORM_ACCESS_VERIFIER_CLASS_NAME_DEFAULT_VALUE = "com.xasecure.pdp.storm.XASecureAuthorizer" ;
-
- //
- // Loging constants
- //
- public static final String AUDITLOG_FIELD_DELIMITER_PROP = "xasecure.auditlog.fieldDelimiterString";
- public static final String AUDITLOG_XASECURE_MODULE_ACL_NAME_PROP = "xasecure.auditlog.xasecureAcl.name" ;
- public static final String AUDITLOG_HADOOP_MODULE_ACL_NAME_PROP = "xasecure.auditlog.hadoopAcl.name" ;
-
- public static final String DEFAULT_LOG_FIELD_DELIMITOR = "|" ;
- public static final String DEFAULT_XASECURE_MODULE_ACL_NAME = "xasecure-acl" ;
- public static final String DEFAULT_HADOOP_MODULE_ACL_NAME = "hadoop-acl" ;
-
-
- public static final String AUDITLOG_FIELDINFO_VISIBLE_PROP = "xasecure.auditlog.fieldInfoVisible" ;
- public static final boolean DEFAULT_AUDITLOG_FIELDINFO_VISIBLE = false ;
-
- public static final String AUDITLOG_ACCESS_GRANTED_TEXT_PROP = "xasecure.auditlog.accessgranted.text" ;
- public static final String AUDITLOG_ACCESS_DENIED_TEXT_PROP = "xasecure.auditlog.accessdenied.text" ;
-
- public static final String DEFAULT_ACCESS_GRANTED_TEXT = "granted" ;
- public static final String DEFAULT_ACCESS_DENIED_TEXT = "denied" ;
-
- public static final String AUDITLOG_EMPTY_STRING = "" ;
-
- public static final String AUDITLOG_HDFS_EXCLUDE_LIST_PROP = "xasecure.auditlog.hdfs.excludeusers" ;
- public static final String AUDITLOG_REPOSITORY_NAME_PROP = "xasecure.audit.repository.name" ;
- public static final String AUDITLOG_IS_ENABLED_PROP = "xasecure.audit.is.enabled" ;
-
- public static final String KEYMGR_URL_PROP = "hdfs.keymanager.url" ;
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-common/src/main/java/com/xasecure/authorization/hadoop/log/HdfsFileAppender.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/com/xasecure/authorization/hadoop/log/HdfsFileAppender.java b/agents-common/src/main/java/com/xasecure/authorization/hadoop/log/HdfsFileAppender.java
deleted file mode 100644
index 973897f..0000000
--- a/agents-common/src/main/java/com/xasecure/authorization/hadoop/log/HdfsFileAppender.java
+++ /dev/null
@@ -1,1376 +0,0 @@
-/*
- * 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 com.xasecure.authorization.hadoop.log;
-
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.FilenameFilter;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.Writer;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.security.PrivilegedExceptionAction;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.Locale;
-import java.util.TimeZone;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.FSDataOutputStream;
-import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.fs.FileUtil;
-import org.apache.hadoop.security.UserGroupInformation;
-import org.apache.log4j.FileAppender;
-import org.apache.log4j.Layout;
-import org.apache.log4j.spi.LoggingEvent;
-import org.apache.log4j.helpers.LogLog;
-
-
-/********************************
-* HdfsFileAppender
-*
-**********************************/
-public class HdfsFileAppender extends FileAppender {
-
-
- // Constants for checking the DatePattern
- public static final String MINUTES ="Min";
- public static final String HOURS ="Hr";
- public static final String DAYS ="Day";
- public static final String WEEKS ="Week";
- public static final String MONTHS ="Month";
-
- // The code assumes that the following constants are in a increasing sequence.
- public static final int TOP_OF_TROUBLE = -1;
- public static final int TOP_OF_MINUTE = 0;
- public static final int TOP_OF_HOUR = 1;
- public static final int HALF_DAY = 2;
- public static final int TOP_OF_DAY = 3;
- public static final int TOP_OF_WEEK = 4;
- public static final int TOP_OF_MONTH = 5;
-
- /**
- * The date pattern. By default, the pattern is set to "1Day" meaning daily rollover.
- */
- private String hdfsFileRollingInterval = "1Day";
-
- private String fileRollingInterval = "1Day";
-
-
- private String scheduledFileCache;
-
- /**
- * The next time we estimate a rollover should occur.
- */
- private long nextCheck = System.currentTimeMillis() - 1;
-
- private long prevnextCheck = nextCheck;
-
- private long nextCheckLocal = System.currentTimeMillis() -1;
-
- private long prevnextCheckLocal = nextCheckLocal;
-
- private Date now = new Date();
-
- private Date nowLocal = now;
-
- private SimpleDateFormat sdf;
-
- private RollingCalendar rc = new RollingCalendar();
-
- private RollingCalendar rcLocal = new RollingCalendar();
-
- private FileOutputStream ostream = null;
-
- private String fileSystemName;
-
- private Layout layout = null;
-
- private String encoding = null;
-
- private String hdfsfileName = null;
-
- private String actualHdfsfileName = null;
-
- private String scheduledHdfsFileName = null;
-
- private String fileCache = null;
-
- private HdfsSink hs = null;
-
- private Writer cacheWriter = null;
-
- private FileOutputStream cacheOstream = null;
-
- private boolean hdfsAvailable = false;
-
- private long hdfsNextCheck = System.currentTimeMillis() - 1;
-
- private boolean timeCheck = false;
-
- private int hdfsFileRollOffset = 0;
-
- private int fileRollOffset = 0;
-
- private boolean firstTime = true;
-
- private boolean firstTimeLocal = true;
-
- private String hdfsLiveUpdate = "true";
-
- boolean hdfsUpdateAllowed = true;
-
- private String hdfsCheckInterval=null;
-
- private String processUser = null;
-
- private String datePattern = "'.'yyyy-MM-dd-HH-mm";
-
- /**
- * The gmtTimeZone is used only in computeCheckPeriod() method.
- */
- private static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT+0");
-
- private static final String DEFAULT_HDFSCHECKINTERVAL = "2min";
-
- /**
- * The default constructor does nothing.
- */
- public HdfsFileAppender() {
-
- }
-
-
- /**
- * The <b>hdfsFileRollingInterval</b> takes a string like 1min, 5min,... 1hr, 2hrs,.. 1day, 2days... 1week, 2weeks.. 1month, 2months.. for hdfs File rollover schedule.
- */
- public void setHdfsFileRollingInterval(String pattern) {
- hdfsFileRollingInterval = pattern;
- }
-
- /** Returns the value of the <b>hdfsFileRollingInterval</b> option. */
- public String getHdfsFileRollingInterval() {
- return hdfsFileRollingInterval;
- }
-
- /**
- * The <b>LocalDatePattern</b> takes a string like 1min, 5min,... 1hr, 2hrs,.. 1day, 2days... 1week, 2weeks.. 1month, 2months.. for local cache File rollover schedule.
- */
- public void setFileRollingInterval(String pattern) {
- fileRollingInterval = pattern;
- }
-
- /** Returns the value of the <b>FileRollingInterval</b> option. */
- public String getFileRollingInterval() {
- return fileRollingInterval;
- }
-
- /**
- * This will set liveHdfsUpdate flag , where true will update hdfs live else false will create local cache files and copy the files to hdfs
- */
- public void setHdfsLiveUpdate(String val) {
- hdfsLiveUpdate=val;
- }
-
- /** Returns the value of the <b>FileRollingInterval</b> option. */
- public String getHdfsLiveUpdate() {
- return hdfsLiveUpdate;
- }
-
- public String getHdfsCheckInterval() {
- return hdfsCheckInterval;
- }
-
- public void setHdfsCheckInterval(String val){
- hdfsCheckInterval = ( hdfsCheckInterval != null) ? val : DEFAULT_HDFSCHECKINTERVAL;
- }
-
- public String getEncoding() {
- return encoding;
- }
-
- public void setEncoding(String value) {
- encoding = value;
- }
-
- public void activateOptions() {
- super.activateOptions();
-
- sdf = new SimpleDateFormat(datePattern);
- processUser=System.getProperties().getProperty("user.name");
-
- if(hdfsFileRollingInterval != null && fileName != null) {
- now.setTime(System.currentTimeMillis());
- int type = computeCheckPeriod(hdfsFileRollingInterval);
- hdfsFileRollOffset = getTimeOffset(hdfsFileRollingInterval);
- printHdfsPeriodicity(type,hdfsFileRollOffset);
- rc.setType(type);
- LogLog.debug("File name: " + fileName);
- File file = new File(fileName);
- scheduledHdfsFileName = hdfsfileName+sdf.format(new Date(file.lastModified()));
- firstTime = true;
- LogLog.debug("Local and hdfs Files" + scheduledHdfsFileName + " " +scheduledHdfsFileName) ;
-
- } else {
- LogLog.error("Either File or hdfsFileRollingInterval options are not set for appender [" + name + "].");
- }
-
- // Local Cache File
-
- if (fileRollingInterval != null && fileCache != null){
- nowLocal.setTime(System.currentTimeMillis());
- int localtype = computeCheckPeriod(fileRollingInterval);
- fileRollOffset = getTimeOffset(fileRollingInterval);
- printLocalPeriodicity(localtype,fileRollOffset);
- rcLocal.setType(localtype);
- LogLog.debug("LocalCacheFile name: " + fileCache);
- File fileCachehandle = new File(fileCache);
- scheduledFileCache = fileCache+sdf.format(new Date(fileCachehandle.lastModified()));
- firstTimeLocal = true;
-
- } else {
- LogLog.error("Either File or LocalDatePattern options are not set for appender [" + name + "].");
- }
-
- hdfsUpdateAllowed = Boolean.parseBoolean(hdfsLiveUpdate);
- actualHdfsfileName = hdfsfileName + sdf.format(System.currentTimeMillis());
- }
-
- public static int containsIgnoreCase(String str1, String str2) {
- return str1.toLowerCase().indexOf(str2.toLowerCase());
- }
-
-
- public int computeCheckPeriod(String timePattern){
-
- if(containsIgnoreCase(timePattern, MINUTES) > 0) {
- return TOP_OF_MINUTE;
- }
-
- if(containsIgnoreCase(timePattern, HOURS) > 0) {
- return TOP_OF_HOUR;
- }
-
- if(containsIgnoreCase(timePattern, DAYS) > 0) {
- return TOP_OF_DAY;
- }
-
- if(containsIgnoreCase(timePattern, WEEKS) > 0) {
- return TOP_OF_WEEK;
- }
-
- if(containsIgnoreCase(timePattern, MONTHS) > 0) {
- return TOP_OF_MONTH;
- }
-
- return TOP_OF_TROUBLE;
- }
-
-
- private void printHdfsPeriodicity(int type, int offset) {
- switch(type) {
- case TOP_OF_MINUTE:
- LogLog.debug("Appender [" + name + "] to be rolled every " + offset + " minute.");
- break;
- case TOP_OF_HOUR:
- LogLog.debug("Appender [" + name + "] to be rolled on top of every " + offset + " hour.");
- break;
- case HALF_DAY:
- LogLog.debug("Appender [" + name + "] to be rolled at midday and midnight.");
- break;
- case TOP_OF_DAY:
- LogLog.debug("Appender [" + name + "] to be rolled on top of every " + offset + " day.");
- break;
- case TOP_OF_WEEK:
- LogLog.debug("Appender [" + name + "] to be rolled on top of every " + offset + " week.");
- break;
- case TOP_OF_MONTH:
- LogLog.debug("Appender [" + name + "] to be rolled at start of every " + offset + " month.");
- break;
- default:
- LogLog.warn("Unknown periodicity for appender [" + name + "].");
- }
- }
-
-
- public int getTimeOffset(String timePattern){
- int index;
- int offset=-1;
-
- if ((index = containsIgnoreCase(timePattern, MINUTES)) > 0) {
- offset = Integer.parseInt(timePattern.substring(0,index));
- }
-
- if ((index = containsIgnoreCase(timePattern, HOURS)) > 0) {
- offset = Integer.parseInt(timePattern.substring(0,index));
-
- }
-
- if ((index = containsIgnoreCase(timePattern, DAYS)) > 0) {
- offset = Integer.parseInt(timePattern.substring(0,index));
-
- }
-
- if ((index = containsIgnoreCase(timePattern, WEEKS)) > 0) {
- offset = Integer.parseInt(timePattern.substring(0,index));
-
- }
-
- if ((index = containsIgnoreCase(timePattern, MONTHS)) > 0) {
- offset = Integer.parseInt(timePattern.substring(0,index));
-
- }
-
- return offset;
- }
-
- private void printLocalPeriodicity(int type, int offset) {
- switch(type) {
- case TOP_OF_MINUTE:
- LogLog.debug("Appender [" + name + "] Local File to be rolled every " + offset + " minute.");
- break;
- case TOP_OF_HOUR:
- LogLog.debug("Appender [" + name + "] Local File to be rolled on top of every " + offset + " hour.");
- break;
- case HALF_DAY:
- LogLog.debug("Appender [" + name + "] Local File to be rolled at midday and midnight.");
- break;
- case TOP_OF_DAY:
- LogLog.debug("Appender [" + name + "] Local File to be rolled on top of every " + offset + " day.");
- break;
- case TOP_OF_WEEK:
- LogLog.debug("Appender [" + name + "] Local File to be rolled on top of every " + offset + " week.");
- break;
- case TOP_OF_MONTH:
- LogLog.debug("Appender [" + name + "] Local File to be rolled at start of every " + offset + " month.");
- break;
- default:
- LogLog.warn("Unknown periodicity for appender [" + name + "].");
- }
- }
-
-
-
-
- /**
- * Rollover the current file to a new file.
- */
- private void rollOver() throws IOException {
- /* Compute filename, but only if hdfsFileRollingInterval is specified */
- if(hdfsFileRollingInterval == null) {
- errorHandler.error("Missing hdfsFileRollingInterval option in rollOver().");
- return;
- }
-
- long epochNow = System.currentTimeMillis();
-
- String datedhdfsFileName = hdfsfileName+sdf.format(epochNow);
-
- LogLog.debug("In rollOver epochNow" + epochNow + " " + "nextCheck: " + prevnextCheck );
-
-
- // It is too early to roll over because we are still within the bounds of the current interval. Rollover will occur once the next interval is reached.
-
- if (epochNow < prevnextCheck) {
- return;
- }
-
- // close current file, and rename it to datedFilename
- this.closeFile();
-
- LogLog.debug("Rolling Over hdfs file to " + scheduledHdfsFileName);
-
-
- if ( hdfsAvailable ) {
- // for hdfs file we don't rollover the fike, we rename the file.
- actualHdfsfileName = hdfsfileName + sdf.format(System.currentTimeMillis());
- }
-
- try {
- // This will also close the file. This is OK since multiple close operations are safe.
- this.setFile(fileName, false, this.bufferedIO, this.bufferSize);
- } catch(IOException e) {
- errorHandler.error("setFile(" + fileName + ", false) call failed.");
- }
- scheduledHdfsFileName = datedhdfsFileName;
- }
-
-
- /**
- * Rollover the current Local file to a new file.
- */
- private void rollOverLocal() throws IOException {
- /* Compute filename, but only if datePattern is specified */
- if(fileRollingInterval == null) {
- errorHandler.error("Missing LocalDatePattern option in rollOverLocal().");
- return;
- }
-
- long epochNow = System.currentTimeMillis();
-
- String datedCacheFileName = fileCache+sdf.format(epochNow);
- LogLog.debug("In rollOverLocal() epochNow" + epochNow + " " + "nextCheckLocal: " + prevnextCheckLocal );
-
- // It is too early to roll over because we are still within the bounds of the current interval. Rollover will occur once the next interval is reached.
- if (epochNow < prevnextCheckLocal ) {
- return;
- }
-
- if (new File(fileCache).length() != 0 ) {
- LogLog.debug("Rolling Local cache to " + scheduledFileCache);
-
- this.closeCacheWriter();
-
- File target = new File(scheduledFileCache);
- if (target.exists()) {
- target.delete();
- }
-
- File file = new File(fileCache);
-
- boolean result = file.renameTo(target);
-
- if(result) {
- LogLog.debug(fileCache +" -> "+ scheduledFileCache);
- } else {
- LogLog.error("Failed to rename cache file ["+fileCache+"] to ["+scheduledFileCache+"].");
- }
- setFileCacheWriter();
- scheduledFileCache = datedCacheFileName;
- }
- }
-
-
- /**
- * <p>
- * Sets and <i>opens</i> the file where the log output will go. The specified file must be writable.
- * <p>
- * If there was already an opened file, then the previous file is closed first.
- * <p>
- * <b>Do not use this method directly. To configure a FileAppender or one of its subclasses, set its properties one by one and then call
- * activateOptions.</b>
- *
- * @param fileName The path to the log file.
- * @param append If true will append to fileName. Otherwise will truncate fileName.
- */
- public void setFile(String file) {
- // Trim spaces from both ends. The users probably does not want
- // trailing spaces in file names.
- String val = file.trim();
-
- fileName=val;
- fileCache=val+".cache";
-
- }
-
- @Override
- public synchronized void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize) throws IOException {
- LogLog.debug("setFile called: "+fileName+", "+append);
-
- // It does not make sense to have immediate flush and bufferedIO.
- if(bufferedIO) {
- setImmediateFlush(false);
- }
-
- reset();
-
- try {
- //
- // attempt to create file
- //
- ostream = new FileOutputStream(fileName, append);
- } catch(FileNotFoundException ex) {
- //
- // if parent directory does not exist then
- // attempt to create it and try to create file
- // see bug 9150
- //
- File umFile = new File(fileName);
- String parentName = umFile.getParent();
-
- if (parentName != null) {
- File parentDir = new File(parentName);
- if(!parentDir.exists() && parentDir.mkdirs()) {
- ostream = new FileOutputStream(fileName, append);
- } else {
- throw ex;
- }
- } else {
- throw ex;
- }
- }
-
- Writer fw = createWriter(ostream);
- if(bufferedIO) {
- fw = new BufferedWriter(fw, bufferSize);
- }
- this.setQWForFiles(fw);
- this.fileName = fileName;
- this.fileAppend = append;
- this.bufferedIO = bufferedIO;
- this.bufferSize = bufferSize;
-
- //set cache file
- setFileCacheWriter();
-
- writeHeader();
-
- LogLog.debug("setFile ended");
- }
-
- public void setHdfsDestination(final String name) {
- //Setting the fileSystemname
-
- String hostName = null;
-
- String val = name.trim();
-
- try {
-
- hostName = InetAddress.getLocalHost().getHostName();
- val=val.replaceAll("%hostname%", hostName);
- String hostStr[] = val.split(":");
- if ( hostStr.length > 0 ) {
- fileSystemName = hostStr[0]+":"+hostStr[1]+":"+hostStr[2];
-
- hdfsfileName = hostStr[3];
-
- } else {
- LogLog.error("Failed to set HdfsSystem and File");
- }
-
- } catch (UnknownHostException uhe) {
- LogLog.error("Setting the Hdfs Desitination Failed", uhe);
- }
-
- LogLog.debug("FileSystemName:" + fileSystemName + "fileName:"+ hdfsfileName);
-
- }
-
- /**
- * This method differentiates HdfsFileAppender from its super class.
- * <p>
- * Before actually logging, this method will check whether it is time to do a rollover. If it is, it will schedule the next rollover time and then rollover.
- */
- @Override
- protected void subAppend(LoggingEvent event) {
- LogLog.debug("Called subAppend for logging into hdfs...");
-
- long n = System.currentTimeMillis();
- if(n >= nextCheck) {
- now.setTime(n);
- prevnextCheck = nextCheck;
- nextCheck = rc.getNextCheckMillis(now,hdfsFileRollOffset);
- if ( firstTime) {
- prevnextCheck = nextCheck;
- firstTime = false;
- }
- try {
- if (hdfsUpdateAllowed) {
- rollOver();
- }
- } catch(IOException e) {
- LogLog.error("rollOver() failed.", e);
- }
- }
-
- long nLocal = System.currentTimeMillis();
- if ( nLocal > nextCheckLocal ) {
- nowLocal.setTime(nLocal);
- prevnextCheckLocal = nextCheckLocal;
- nextCheckLocal = rcLocal.getNextCheckMillis(nowLocal, fileRollOffset);
- if ( firstTimeLocal) {
- prevnextCheckLocal = nextCheckLocal;
- firstTimeLocal = false;
- }
- try {
- rollOverLocal();
- } catch(IOException e) {
- LogLog.error("rollOverLocal() failed.", e);
- }
- }
-
- this.layout = this.getLayout();
- this.encoding = this.getEncoding();
-
- // Append HDFS
- appendHDFSFileSystem(event);
-
-
- //super.subAppend(event);
- }
-
- @Override
- protected
- void reset() {
- closeWriter();
- this.qw = null;
- //this.
- this.closeHdfsWriter();
- this.closeCacheWriter();
- }
-
- @Override
- public synchronized void close() {
- LogLog.debug("Closing all resource..");
- this.closeFile();
- this.closeHdfsWriter();
- this.closeHdfsOstream();
- this.closeFileSystem();
- }
-
- @Override
- protected void closeFile() {
- try {
- if(this.ostream != null) {
- this.ostream.close();
- this.ostream = null;
- }
- } catch(IOException ie) {
- LogLog.error("unable to close output stream", ie);
- }
- this.closeHdfsWriter();
- this.closeHdfsOstream();
- }
-
- @Override
- protected void closeWriter() {
- try {
- if(this.qw != null) {
- this.qw.close();
- this.qw = null;
- }
- } catch(IOException ie) {
- LogLog.error("unable to close writer", ie);
- }
- }
-
- @Override
- public void finalize() {
- super.finalize();
- close();
- }
-
-
- /******* HDFS Appender methods ***********/
-
- private void appendHDFSFileSystem(LoggingEvent event) {
-
- long currentTime = System.currentTimeMillis();
-
- try {
-
- if ( currentTime >= hdfsNextCheck ) {
-
- LogLog.debug("About to Open fileSystem" + fileSystemName+" "+actualHdfsfileName) ;
- hs = openHdfsSink(fileSystemName,actualHdfsfileName,fileCache,fileAppend,bufferedIO,bufferSize,layout,encoding,scheduledFileCache,cacheWriter,hdfsUpdateAllowed,processUser);
- if (hdfsUpdateAllowed) {
- // stream into hdfs only when liveHdfsUpdate flag is true else write to cache file.
- hs.setOsteam();
- hs.setWriter();
- hs.append(event);
- } else {
- writeToCache(event);
- }
- hdfsAvailable = true;
-
- } else {
- // Write the Log To cache file util time to check hdfs availability
- hdfsAvailable = false;
- LogLog.debug("Hdfs Down..Will check hdfs vailability after " + hdfsNextCheck + "Current Time :" +hdfsNextCheck ) ;
- writeToCache(event);
- }
- }
- catch(Throwable t) {
- // Write the Log To cache file if hdfs connect error out.
- hdfsAvailable = false;
- if ( !timeCheck ) {
- int hdfscheckInterval = getTimeOffset(hdfsCheckInterval);
- hdfsNextCheck = System.currentTimeMillis()+(1000*60*hdfscheckInterval);
- timeCheck = true;
- LogLog.debug("Hdfs Down..Will check hdfs vailability after " + hdfsCheckInterval , t) ;
-
- }
- writeToCache(event);
- }
-
- }
-
-
- private HdfsSink openHdfsSink(String fileSystemName,String filename, String fileCache, boolean append, boolean bufferedIO,int bufferSize,Layout layout, String encoding, String scheduledCacheFile, Writer cacheWriter,boolean hdfsUpdateAllowed,String processUser) throws Throwable {
-
- HdfsSink hs = null;
- hs = HdfsSink.getInstance();
- if ( hs != null)
-
- LogLog.debug("Hdfs Sink successfully instatiated");
- try {
- hs.init(fileSystemName, filename, fileCache, append, bufferedIO, bufferSize, layout, encoding,scheduledCacheFile,cacheWriter,hdfsUpdateAllowed,processUser);
-
- } catch (Throwable t) {
- throw t;
- }
- return hs;
-
- }
-
- private void closeHdfsOstream() {
- if (hs != null ){
- LogLog.debug("Closing hdfs outstream") ;
- hs.closeHdfsOstream();
- }
- }
-
- private void closeHdfsWriter() {
-
- if (hs != null) {
- LogLog.debug("Closing hdfs Writer") ;
- hs.closeHdfsWriter();
- }
- }
-
- private void closeFileSystem() {
- hs.closeHdfsSink();
- }
-
-
-
- /****** Cache File Methods **/
-
-
- public void setFileCacheWriter() {
-
- try {
- setFileCacheOstream(fileCache);
- } catch(IOException ie) {
- LogLog.error("Logging failed while tring to write into Cache File..", ie);
- }
- LogLog.debug("Setting Cache Writer..");
- cacheWriter = createCacheFileWriter(cacheOstream);
- if(bufferedIO) {
- cacheWriter = new BufferedWriter(cacheWriter, bufferSize);
- }
- }
-
-
- private void setFileCacheOstream(String fileCache) throws IOException {
-
- try {
- cacheOstream = new FileOutputStream(fileCache, true);
- } catch(FileNotFoundException ex) {
- String parentName = new File(fileCache).getParent();
- if (parentName != null) {
- File parentDir = new File(parentName);
- if(!parentDir.exists() && parentDir.mkdirs()) {
- cacheOstream = new FileOutputStream(fileName, true);
- } else {
- throw ex;
- }
- } else {
- throw ex;
- }
- }
- }
-
-
- public OutputStreamWriter createCacheFileWriter(OutputStream os ) {
- OutputStreamWriter retval = null;
-
- if(encoding != null) {
- try {
- retval = new OutputStreamWriter(os, encoding);
- } catch(IOException ie) {
- LogLog.warn("Error initializing output writer.");
- LogLog.warn("Unsupported encoding?");
- }
- }
- if(retval == null) {
- retval = new OutputStreamWriter(os);
- }
- return retval;
- }
-
-
- public void writeToCache(LoggingEvent event) {
-
- try {
- LogLog.debug("Writing log to Cache.." + "layout: "+ this.layout.format(event) + "ignoresThowable: "+layout.ignoresThrowable() + "Writer:" + cacheWriter.toString());
-
- cacheWriter.write(this.layout.format(event));
- cacheWriter.flush();
-
- if(layout.ignoresThrowable()) {
- String[] s = event.getThrowableStrRep();
- if (s != null) {
- int len = s.length;
- for(int i = 0; i < len; i++) {
- LogLog.debug("Log:" + s[i]);
- cacheWriter.write(s[i]);
- cacheWriter.write(Layout.LINE_SEP);
- cacheWriter.flush();
- }
- }
- }
- } catch (IOException ie) {
- LogLog.error("Unable to log event message to hdfs:", ie);
- }
- }
-
- public void rollOverCacheFile() {
-
- if (new File(fileCache).length() != 0 ) {
-
- long epochNow = System.currentTimeMillis();
-
- String datedCacheFileName = fileCache + "." + epochNow;
- LogLog.debug("Rolling over remaining cache File to new file"+ datedCacheFileName);
- closeCacheWriter();
-
- File target = new File(datedCacheFileName);
- if (target.exists()) {
- target.delete();
- }
-
- File file = new File(fileCache);
-
- boolean result = file.renameTo(target);
-
- if(result) {
- LogLog.debug(fileCache +" -> "+ datedCacheFileName);
- } else {
- LogLog.error("Failed to rename cache file ["+fileCache+"] to ["+datedCacheFileName+"].");
- }
- }
- }
-
- public void closeCacheWriter() {
- try {
- if(cacheWriter != null) {
- cacheWriter.close();
- cacheWriter = null;
- }
- } catch(IOException ie) {
- LogLog.error("unable to close cache writer", ie);
- }
- }
-}
-
-/**
- * RollingCalendar is a helper class to HdfsFileAppender. Given a periodicity type and the current time, it computes the start of the next interval.
- */
-
-class RollingCalendar extends GregorianCalendar {
- private static final long serialVersionUID = 1L;
-
- private int type = HdfsFileAppender.TOP_OF_TROUBLE;
-
- RollingCalendar() {
- super();
- }
-
- RollingCalendar(TimeZone tz, Locale locale) {
- super(tz, locale);
- }
-
- void setType(int type) {
- this.type = type;
- }
-
- public long getNextCheckMillis(Date now, int offset) {
- return getNextCheckDate(now,offset).getTime();
- }
-
- public Date getNextCheckDate(Date now,int offset) {
- this.setTime(now);
-
- switch(this.type) {
- case HdfsFileAppender.TOP_OF_MINUTE:
- this.set(Calendar.SECOND, 0);
- this.set(Calendar.MILLISECOND, 0);
- this.add(Calendar.MINUTE, offset);
- break;
- case HdfsFileAppender.TOP_OF_HOUR:
- this.set(Calendar.MINUTE, 0);
- this.set(Calendar.SECOND, 0);
- this.set(Calendar.MILLISECOND, 0);
- this.add(Calendar.HOUR_OF_DAY, offset);
- break;
- case HdfsFileAppender.HALF_DAY:
- this.set(Calendar.MINUTE, 0);
- this.set(Calendar.SECOND, 0);
- this.set(Calendar.MILLISECOND, 0);
- int hour = get(Calendar.HOUR_OF_DAY);
- if(hour < 12) {
- this.set(Calendar.HOUR_OF_DAY, 12);
- } else {
- this.set(Calendar.HOUR_OF_DAY, 0);
- this.add(Calendar.DAY_OF_MONTH, 1);
- }
- break;
- case HdfsFileAppender.TOP_OF_DAY:
- this.set(Calendar.HOUR_OF_DAY, 0);
- this.set(Calendar.MINUTE, 0);
- this.set(Calendar.SECOND, 0);
- this.set(Calendar.MILLISECOND, 0);
- this.add(Calendar.DATE, offset);
- break;
- case HdfsFileAppender.TOP_OF_WEEK:
- this.set(Calendar.DAY_OF_WEEK, getFirstDayOfWeek());
- this.set(Calendar.HOUR_OF_DAY, 0);
- this.set(Calendar.SECOND, 0);
- this.set(Calendar.MILLISECOND, 0);
- this.add(Calendar.WEEK_OF_YEAR, offset);
- break;
- case HdfsFileAppender.TOP_OF_MONTH:
- this.set(Calendar.DATE, 1);
- this.set(Calendar.HOUR_OF_DAY, 0);
- this.set(Calendar.SECOND, 0);
- this.set(Calendar.MILLISECOND, 0);
- this.add(Calendar.MONTH, offset);
- break;
- default:
- throw new IllegalStateException("Unknown periodicity type.");
- }
- return getTime();
- }
-
-
-}
-
-
-/*************
- * Hdfs Sink
- *
- *************/
-
-class HdfsSink {
-
- private static final String DS_REPLICATION_VAL = "1";
- private static final String DS_REPLICATION_KEY = "dfs.replication";
- private static final String FS_DEFAULT_NAME_KEY = "fs.default.name";
- private Configuration conf = null;
- private FileSystem fs= null;
- private Path pt = null;
- private FSDataOutputStream hdfsostream = null;
- private String fsName = null;
- private String fileName = null;
- private String fileCache = null;
- private Layout layout = null;
- private String encoding = null;
- private Writer hdfswriter = null;
- private int bufferSize;
- private boolean bufferedIO=false;
- private static int fstime=0;
- private CacheFileWatcher cfw = null;
- private boolean hdfsUpdateAllowed=true;
- private String processUser=null;
-
-
- HdfsSink() {
- }
-
- private static final ThreadLocal<HdfsSink> hdfssink = new ThreadLocal<HdfsSink>() {
- protected HdfsSink initialValue() {
- return new HdfsSink();
- }
- };
-
- public static HdfsSink getInstance() {
- return hdfssink.get();
- }
-
- public void init(String fileSystemName, String fileName, String fileCache,boolean append, boolean bufferedIO, int bufferSize, Layout layout, String encoding, String scheduledCacheFile, Writer cacheWriter, boolean hdfsUpdateAllowed, String processUser) throws Exception{
-
- this.fsName=fileSystemName;
- this.fileName=fileName;
- this.layout=layout;
- this.encoding=encoding;
- this.bufferSize=bufferSize;
- this.bufferedIO=bufferedIO;
- this.fileCache=fileCache;
- this.hdfsUpdateAllowed=hdfsUpdateAllowed;
- this.processUser=processUser;
-
- final Configuration conf= new Configuration();
- conf.set(DS_REPLICATION_KEY,DS_REPLICATION_VAL);
- conf.set(FS_DEFAULT_NAME_KEY, fsName);
-
- try {
- if ( fs == null) {
- LogLog.debug("Opening Connection to hdfs Sytem" + this.fsName);
-
- UserGroupInformation ugi = UserGroupInformation.createProxyUser(this.processUser, UserGroupInformation.getLoginUser());
- fs = ugi.doAs( new PrivilegedExceptionAction<FileSystem>() {
- public FileSystem run() throws Exception {
- FileSystem filesystem = FileSystem.get(conf);
- LogLog.debug("Inside UGI.." + fsName + " " + filesystem);
- return filesystem;
- }
- });
-
- if ( cfw == null) {
- // Start the CacheFileWatcher to move the Cache file.
-
- LogLog.debug("About to run CacheFilWatcher...");
- Path hdfsfilePath = getParent();
- cfw = new CacheFileWatcher(this.fs,this.fileCache,hdfsfilePath,cacheWriter,this.hdfsUpdateAllowed,conf);
- cfw.start();
- }
-
- }
-
- } catch(Exception ie) {
-
- LogLog.error("Unable to Create hdfs logfile:" + ie.getMessage());
- throw ie;
- }
-
- LogLog.debug("HdfsSystem up: " + fsName + "FS Object:" + fs);
- }
-
- public int getfstime() {
- return fstime;
- }
- public FileSystem getFileSystem() {
- return fs;
- }
-
- public Path getPath() {
- return pt;
- }
-
- public Path getParent() {
- Path pt = new Path(this.fileName);
- return pt.getParent();
- }
-
- public void setOsteam() throws IOException {
- try {
- pt = new Path(this.fileName);
- // if file Exist append it
- if(fs.exists(pt)) {
- LogLog.debug("Appending File: "+ this.fsName+":"+this.fileName+fs);
- if (hdfsostream !=null) {
- hdfsostream.close();
- }
- hdfsostream=fs.append(pt);
-
- } else {
- LogLog.debug("Creating File directories in hdfs if not present.."+ this.fsName+":"+this.fileName + fs);
- String parentName = new Path(this.fileName).getParent().toString();
- if(parentName != null) {
- Path parentDir = new Path(parentName);
- if (!fs.exists(parentDir) ) {
- LogLog.debug("Creating Parent Directory: " + parentDir );
- fs.mkdirs(parentDir);
- }
- }
- hdfsostream = fs.create(pt);
- }
- } catch (IOException ie) {
- LogLog.debug("Error While appending hdfsd file." + ie);
- throw ie;
- }
- }
-
- public void setWriter() {
- LogLog.debug("Setting Writer..");
- hdfswriter = createhdfsWriter(hdfsostream);
- if(bufferedIO) {
- hdfswriter = new BufferedWriter(hdfswriter, bufferSize);
- }
- }
-
- public Writer getWriter() {
- return hdfswriter;
- }
-
- public void append(LoggingEvent event) throws IOException {
- try {
- LogLog.debug("Writing log to HDFS." + "layout: "+ this.layout.format(event) + "ignoresThowable: "+layout.ignoresThrowable() + "Writer:" + hdfswriter.toString());
-
- hdfswriter.write(this.layout.format(event));
- hdfswriter.flush();
- if(layout.ignoresThrowable()) {
- String[] s = event.getThrowableStrRep();
- if (s != null) {
- int len = s.length;
- for(int i = 0; i < len; i++) {
- LogLog.debug("Log:" + s[i]);
- hdfswriter.write(s[i]);
- hdfswriter.write(Layout.LINE_SEP);
- hdfswriter.flush();
- }
- }
- }
- } catch (IOException ie) {
- LogLog.error("Unable to log event message to hdfs:", ie);
- throw ie;
- }
- }
-
- public void writeHeader() throws IOException {
- LogLog.debug("Writing log header...");
- try {
- if(layout != null) {
- String h = layout.getHeader();
- if(h != null && hdfswriter != null)
- LogLog.debug("Log header:" + h);
- hdfswriter.write(h);
- hdfswriter.flush();
- }
- } catch (IOException ie) {
- LogLog.error("Unable to log header message to hdfs:", ie);
- throw ie;
- }
- }
-
- public
- void writeFooter() throws IOException{
- LogLog.debug("Writing footer header...");
- try {
- if(layout != null) {
- String f = layout.getFooter();
- if(f != null && hdfswriter != null) {
- LogLog.debug("Log:" + f);
- hdfswriter.write(f);
- hdfswriter.flush();
- }
- }
- } catch (IOException ie) {
- LogLog.debug("Unable to log header message to hdfs:", ie);
- throw ie;
- }
-
- }
-
- public void closeHdfsOstream() {
- try {
- if(this.hdfsostream != null) {
- this.hdfsostream.close();
- this.hdfsostream = null;
- }
- } catch(IOException ie) {
- LogLog.error("unable to close output stream", ie);
- }
-
- }
-
- public void closeHdfsWriter() {
- try {
- if(hdfswriter != null) {
- hdfswriter.close();
- hdfswriter = null;
- }
- } catch(IOException ie) {
- LogLog.error("unable to hfds writer", ie);
- }
- }
-
- public void closeHdfsSink() {
- try {
- if (fs !=null) {
- fs.close();
- }
- } catch (IOException ie) {
- LogLog.error("Unable to close hdfs " + fs ,ie);
- }
- }
-
-
- public OutputStreamWriter createhdfsWriter(FSDataOutputStream os ) {
- OutputStreamWriter retval = null;
-
- if(encoding != null) {
- try {
- retval = new OutputStreamWriter(os, encoding);
- } catch(IOException ie) {
- LogLog.warn("Error initializing output writer.");
- LogLog.warn("Unsupported encoding?");
- }
- }
- if(retval == null) {
- retval = new OutputStreamWriter(os);
- }
- return retval;
- }
-
-
- }
-
-
-// CacheFileWatcher Thread
-
-class CacheFileWatcher extends Thread {
-
- long CACHEFILE_WATCHER_SLEEP_TIME = 1000*60*2;
-
- Configuration conf = null;
- private FileSystem fs = null;
- private String cacheFile = null;
- private File parentDir = null;
- private File[] files = null;
- private Path fsPath = null;
- private Path hdfsfilePath = null;
- private Writer cacheWriter = null;
-
- private boolean hdfsUpdateAllowed=true;
- private boolean cacheFilesCopied = false;
-
- CacheFileWatcher(FileSystem fs, String cacheFile, Path hdfsfilePath, Writer cacheWriter, boolean hdfsUpdateAllowed, Configuration conf) {
- this.fs = fs;
- this.cacheFile = cacheFile;
- this.conf = conf;
- this.hdfsfilePath = hdfsfilePath;
- this.cacheWriter = cacheWriter;
- this.hdfsUpdateAllowed = hdfsUpdateAllowed;
- }
-
-
- public void run(){
-
- LogLog.debug("CacheFileWatcher Started");
-
- while (!cacheFilesCopied ){
-
- if (hdfsUpdateAllowed) {
- rollRemainingCacheFile();
- }
-
- if ( !cacheFilePresent(cacheFile) ) {
-
- try {
- Thread.sleep(CACHEFILE_WATCHER_SLEEP_TIME);
- } catch (InterruptedException ie) {
- LogLog.error("Unable to complete the CatchFileWatcher Sleep", ie);
- }
- } else {
- try {
- copyCacheFilesToHdfs();
- if (hdfsUpdateAllowed) {
- cacheFilesCopied = true;
- } else {
- cacheFilesCopied = false;
- }
- } catch (Throwable t) {
- // Error While copying the file to hdfs and thread goes for sleep and check later
- cacheFilesCopied = false;
- LogLog. error("Error while copying Cache Files to hdfs..Sleeping for next try",t);
-
- try {
- Thread.sleep(CACHEFILE_WATCHER_SLEEP_TIME);
- } catch (InterruptedException ie) {
- LogLog.error("Unable to complete the CatchFileWatcher Sleep", ie);
- }
- }
- }
- }
- }
-
- public boolean cacheFilePresent(String filename) {
- String parent = new File(filename).getParent();
- if ( parent != null ) {
- parentDir = new File(parent);
- fsPath = new Path(parent);
- files = parentDir.listFiles(new FilenameFilter() {
- @Override
- public boolean accept(File parentDir, String name) {
- return name.matches(".*cache.+");
- }
- });
- if ( files.length > 0) {
- LogLog.debug("CacheFile Present..");
- return true;
- }
- }
- return false;
- }
-
-
- public void copyCacheFilesToHdfs() throws Throwable{
-
- try {
-
- if (!fs.exists(hdfsfilePath) ) {
- LogLog.debug("Creating Parent Directory: " + hdfsfilePath );
- fs.mkdirs(hdfsfilePath);
- }
- } catch ( Throwable t) {
- throw t;
- }
-
-
- for ( File cacheFile : files) {
- try {
- LogLog.debug("Copying Files..." + "File Path: " + fsPath + "CacheFile: " +cacheFile + "HDFS Path:" + hdfsfilePath);
- FileUtil.copy(cacheFile, this.fs, this.hdfsfilePath, true, this.conf);
- } catch (Throwable t) {
-
- throw t;
- }
- }
- }
-
- public void rollRemainingCacheFile() {
- String datePattern = "'.'yyyy-MM-dd-HH-mm";
- SimpleDateFormat sdf = new SimpleDateFormat(datePattern);
- if (new File(cacheFile).length() != 0 ) {
- long epochNow = System.currentTimeMillis();
-
- String datedCacheFileName = cacheFile + sdf.format(epochNow);
-
- LogLog.debug("Rolling over remaining cache File "+ datedCacheFileName);
- closeCacheFile();
-
- File target = new File(datedCacheFileName);
- if (target.exists()) {
- target.delete();
- }
-
- File file = new File(cacheFile);
-
- boolean result = file.renameTo(target);
-
- if(result) {
- LogLog.debug(cacheFile +" -> "+ datedCacheFileName);
- } else {
- LogLog.error("Failed to rename cache file ["+cacheFile+"] to ["+datedCacheFileName+"].");
- }
-
- }
- }
-
- public void closeCacheFile() {
- try {
- if(cacheWriter != null) {
- cacheWriter.close();
- cacheWriter = null;
- }
- } catch(IOException ie) {
- LogLog.error("unable to close cache writer", ie);
- }
- }
-}
-
-
[33/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessorBase.java
----------------------------------------------------------------------
diff --git a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessorBase.java b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessorBase.java
new file mode 100644
index 0000000..2dab171
--- /dev/null
+++ b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessorBase.java
@@ -0,0 +1,671 @@
+/**
+ *
+ * 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.authorization.hbase;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.apache.hadoop.hbase.HColumnDescriptor;
+import org.apache.hadoop.hbase.HRegionInfo;
+import org.apache.hadoop.hbase.HTableDescriptor;
+import org.apache.hadoop.hbase.NamespaceDescriptor;
+import org.apache.hadoop.hbase.ServerName;
+import org.apache.hadoop.hbase.TableName;
+import org.apache.hadoop.hbase.client.Mutation;
+import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
+import org.apache.hadoop.hbase.coprocessor.BulkLoadObserver;
+import org.apache.hadoop.hbase.coprocessor.MasterCoprocessorEnvironment;
+import org.apache.hadoop.hbase.coprocessor.MasterObserver;
+import org.apache.hadoop.hbase.coprocessor.ObserverContext;
+import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
+import org.apache.hadoop.hbase.coprocessor.RegionServerCoprocessorEnvironment;
+import org.apache.hadoop.hbase.coprocessor.RegionServerObserver;
+import org.apache.hadoop.hbase.master.RegionPlan;
+import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
+import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.CleanupBulkLoadRequest;
+import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.PrepareBulkLoadRequest;
+import org.apache.hadoop.hbase.regionserver.HRegion;
+import org.apache.hadoop.hbase.replication.ReplicationEndpoint;
+import org.apache.hadoop.hbase.security.access.Permission;
+import org.apache.hadoop.hbase.security.access.Permission.Action;
+
+public class RangerAuthorizationCoprocessorBase extends BaseRegionObserver
+ implements MasterObserver, RegionServerObserver, BulkLoadObserver {
+
+ @Override
+ public void preStopRegionServer(
+ ObserverContext<RegionServerCoprocessorEnvironment> env)
+ throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preMerge(
+ ObserverContext<RegionServerCoprocessorEnvironment> ctx,
+ HRegion regionA, HRegion regionB) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postMerge(
+ ObserverContext<RegionServerCoprocessorEnvironment> c,
+ HRegion regionA, HRegion regionB, HRegion mergedRegion)
+ throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preMergeCommit(
+ ObserverContext<RegionServerCoprocessorEnvironment> ctx,
+ HRegion regionA, HRegion regionB, List<Mutation> metaEntries)
+ throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postMergeCommit(
+ ObserverContext<RegionServerCoprocessorEnvironment> ctx,
+ HRegion regionA, HRegion regionB, HRegion mergedRegion)
+ throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preRollBackMerge(
+ ObserverContext<RegionServerCoprocessorEnvironment> ctx,
+ HRegion regionA, HRegion regionB) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postRollBackMerge(
+ ObserverContext<RegionServerCoprocessorEnvironment> ctx,
+ HRegion regionA, HRegion regionB) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preCreateTable(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ HTableDescriptor desc, HRegionInfo[] regions) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postCreateTable(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ HTableDescriptor desc, HRegionInfo[] regions) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preCreateTableHandler(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ HTableDescriptor desc, HRegionInfo[] regions) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postCreateTableHandler(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ HTableDescriptor desc, HRegionInfo[] regions) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preDeleteTable(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postDeleteTable(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preDeleteTableHandler(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postDeleteTableHandler(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preModifyTable(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName, HTableDescriptor htd) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postModifyTable(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName, HTableDescriptor htd) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preModifyTableHandler(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName, HTableDescriptor htd) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postModifyTableHandler(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName, HTableDescriptor htd) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preAddColumn(ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName, HColumnDescriptor column) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postAddColumn(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName, HColumnDescriptor column) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preAddColumnHandler(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName, HColumnDescriptor column) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postAddColumnHandler(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName, HColumnDescriptor column) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preModifyColumn(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName, HColumnDescriptor descriptor)
+ throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postModifyColumn(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName, HColumnDescriptor descriptor)
+ throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preModifyColumnHandler(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName, HColumnDescriptor descriptor)
+ throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postModifyColumnHandler(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName, HColumnDescriptor descriptor)
+ throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preDeleteColumn(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName, byte[] c) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postDeleteColumn(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName, byte[] c) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preDeleteColumnHandler(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName, byte[] c) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postDeleteColumnHandler(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName, byte[] c) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preEnableTable(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postEnableTable(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preEnableTableHandler(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postEnableTableHandler(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preDisableTable(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postDisableTable(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preDisableTableHandler(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postDisableTableHandler(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ TableName tableName) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preMove(ObserverContext<MasterCoprocessorEnvironment> ctx,
+ HRegionInfo region, ServerName srcServer, ServerName destServer)
+ throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postMove(ObserverContext<MasterCoprocessorEnvironment> ctx,
+ HRegionInfo region, ServerName srcServer, ServerName destServer)
+ throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preAssign(ObserverContext<MasterCoprocessorEnvironment> ctx,
+ HRegionInfo regionInfo) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postAssign(ObserverContext<MasterCoprocessorEnvironment> ctx,
+ HRegionInfo regionInfo) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preUnassign(ObserverContext<MasterCoprocessorEnvironment> ctx,
+ HRegionInfo regionInfo, boolean force) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postUnassign(ObserverContext<MasterCoprocessorEnvironment> ctx,
+ HRegionInfo regionInfo, boolean force) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preRegionOffline(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ HRegionInfo regionInfo) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postRegionOffline(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ HRegionInfo regionInfo) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preBalance(ObserverContext<MasterCoprocessorEnvironment> ctx)
+ throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postBalance(ObserverContext<MasterCoprocessorEnvironment> ctx,
+ List<RegionPlan> plans) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public boolean preBalanceSwitch(
+ ObserverContext<MasterCoprocessorEnvironment> ctx, boolean newValue)
+ throws IOException {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public void postBalanceSwitch(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ boolean oldValue, boolean newValue) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preShutdown(ObserverContext<MasterCoprocessorEnvironment> ctx)
+ throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preStopMaster(ObserverContext<MasterCoprocessorEnvironment> ctx)
+ throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postStartMaster(
+ ObserverContext<MasterCoprocessorEnvironment> ctx)
+ throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preMasterInitialization(
+ ObserverContext<MasterCoprocessorEnvironment> ctx)
+ throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preSnapshot(ObserverContext<MasterCoprocessorEnvironment> ctx,
+ SnapshotDescription snapshot, HTableDescriptor hTableDescriptor)
+ throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postSnapshot(ObserverContext<MasterCoprocessorEnvironment> ctx,
+ SnapshotDescription snapshot, HTableDescriptor hTableDescriptor)
+ throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preCloneSnapshot(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ SnapshotDescription snapshot, HTableDescriptor hTableDescriptor)
+ throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postCloneSnapshot(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ SnapshotDescription snapshot, HTableDescriptor hTableDescriptor)
+ throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preRestoreSnapshot(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ SnapshotDescription snapshot, HTableDescriptor hTableDescriptor)
+ throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postRestoreSnapshot(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ SnapshotDescription snapshot, HTableDescriptor hTableDescriptor)
+ throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preDeleteSnapshot(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ SnapshotDescription snapshot) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postDeleteSnapshot(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ SnapshotDescription snapshot) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preGetTableDescriptors(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ List<TableName> tableNamesList, List<HTableDescriptor> descriptors)
+ throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postGetTableDescriptors(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ List<HTableDescriptor> descriptors) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preCreateNamespace(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ NamespaceDescriptor ns) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postCreateNamespace(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ NamespaceDescriptor ns) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preDeleteNamespace(
+ ObserverContext<MasterCoprocessorEnvironment> ctx, String namespace)
+ throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postDeleteNamespace(
+ ObserverContext<MasterCoprocessorEnvironment> ctx, String namespace)
+ throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void preModifyNamespace(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ NamespaceDescriptor ns) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void postModifyNamespace(
+ ObserverContext<MasterCoprocessorEnvironment> ctx,
+ NamespaceDescriptor ns) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ public void preRollWALWriterRequest(ObserverContext<RegionServerCoprocessorEnvironment> ctx) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ public void postRollWALWriterRequest(ObserverContext<RegionServerCoprocessorEnvironment> ctx) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ public void preTableFlush(final ObserverContext<MasterCoprocessorEnvironment> ctx, final TableName tableName) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ public void postTableFlush(ObserverContext<MasterCoprocessorEnvironment> ctx, TableName tableName) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ public void preTruncateTableHandler(final ObserverContext<MasterCoprocessorEnvironment> ctx, TableName tableName) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ public void postTruncateTableHandler(final ObserverContext<MasterCoprocessorEnvironment> ctx, TableName tableName) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ public void preTruncateTable(final ObserverContext<MasterCoprocessorEnvironment> ctx, TableName tableName) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ public void postTruncateTable(final ObserverContext<MasterCoprocessorEnvironment> ctx, TableName tableName) throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+
+ public ReplicationEndpoint postCreateReplicationEndPoint(ObserverContext<RegionServerCoprocessorEnvironment> ctx, ReplicationEndpoint endpoint) {
+ return endpoint;
+ }
+
+ public void prePrepareBulkLoad(ObserverContext<RegionCoprocessorEnvironment> ctx, PrepareBulkLoadRequest request) throws IOException {
+ }
+
+ public void preCleanupBulkLoad(ObserverContext<RegionCoprocessorEnvironment> ctx, CleanupBulkLoadRequest request) throws IOException {
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hbase-agent/src/test/java/org/apache/hadoop/hbase/security/access/RangerAccessControlListsTest.java
----------------------------------------------------------------------
diff --git a/hbase-agent/src/test/java/org/apache/hadoop/hbase/security/access/RangerAccessControlListsTest.java b/hbase-agent/src/test/java/org/apache/hadoop/hbase/security/access/RangerAccessControlListsTest.java
new file mode 100644
index 0000000..aa66d08
--- /dev/null
+++ b/hbase-agent/src/test/java/org/apache/hadoop/hbase/security/access/RangerAccessControlListsTest.java
@@ -0,0 +1,61 @@
+/*
+ * 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.hadoop.hbase.security.access;
+
+import java.io.IOException;
+
+import org.apache.hadoop.hbase.master.MasterServices;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class RangerAccessControlListsTest {
+
+ @BeforeClass
+ public static void setUpBeforeClass() throws Exception {
+ }
+
+ @AfterClass
+ public static void tearDownAfterClass() throws Exception {
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ }
+
+ @Test
+ public void testInit() {
+ IOException exceptionFound = null ;
+ try {
+ MasterServices service = null ;
+ RangerAccessControlLists.init(service) ;
+ } catch (IOException e) {
+ exceptionFound = e ;
+ }
+ Assert.assertFalse("Expected to get a NullPointerExecution after init method Execution - Found [" + exceptionFound + "]", (!(exceptionFound != null && exceptionFound.getCause() instanceof NullPointerException))) ;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hbase-agent/src/test/java/org/apache/hadoop/hbase/security/access/XaAccessControlListsTest.java
----------------------------------------------------------------------
diff --git a/hbase-agent/src/test/java/org/apache/hadoop/hbase/security/access/XaAccessControlListsTest.java b/hbase-agent/src/test/java/org/apache/hadoop/hbase/security/access/XaAccessControlListsTest.java
deleted file mode 100644
index 0b8afbb..0000000
--- a/hbase-agent/src/test/java/org/apache/hadoop/hbase/security/access/XaAccessControlListsTest.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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.hadoop.hbase.security.access;
-
-import java.io.IOException;
-
-import org.apache.hadoop.hbase.master.MasterServices;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-public class XaAccessControlListsTest {
-
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {
- }
-
- @AfterClass
- public static void tearDownAfterClass() throws Exception {
- }
-
- @Before
- public void setUp() throws Exception {
- }
-
- @After
- public void tearDown() throws Exception {
- }
-
- @Test
- public void testInit() {
- IOException exceptionFound = null ;
- try {
- MasterServices service = null ;
- XaAccessControlLists.init(service) ;
- } catch (IOException e) {
- exceptionFound = e ;
- }
- Assert.assertFalse("Expected to get a NullPointerExecution after init method Execution - Found [" + exceptionFound + "]", (!(exceptionFound != null && exceptionFound.getCause() instanceof NullPointerException))) ;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hdfs-agent/conf/xasecure-hdfs-security-changes.cfg
----------------------------------------------------------------------
diff --git a/hdfs-agent/conf/xasecure-hdfs-security-changes.cfg b/hdfs-agent/conf/xasecure-hdfs-security-changes.cfg
index 76f4919..97e631a5 100644
--- a/hdfs-agent/conf/xasecure-hdfs-security-changes.cfg
+++ b/hdfs-agent/conf/xasecure-hdfs-security-changes.cfg
@@ -16,7 +16,7 @@
# Change the original policy parameter to work with policy manager based.
#
#
-hdfs.authorization.verifier.classname com.xasecure.pdp.hdfs.XASecureAuthorizer mod create-if-not-exists
+hdfs.authorization.verifier.classname org.apache.ranger.pdp.hdfs.RangerAuthorizer mod create-if-not-exists
xasecure.hdfs.policymgr.url %POLICY_MGR_URL%/service/assets/policyList/%REPOSITORY_NAME% mod create-if-not-exists
xasecure.hdfs.policymgr.url.saveAsFile /tmp/hadoop_%REPOSITORY_NAME%_json mod create-if-not-exists
xasecure.hdfs.policymgr.url.laststoredfile %POLICY_CACHE_FILE_PATH%/hadoop_%REPOSITORY_NAME%_json mod create-if-not-exists
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hdfs-agent/conf/xasecure-hdfs-security.xml
----------------------------------------------------------------------
diff --git a/hdfs-agent/conf/xasecure-hdfs-security.xml b/hdfs-agent/conf/xasecure-hdfs-security.xml
index 81f8f6a..9cf5b69 100644
--- a/hdfs-agent/conf/xasecure-hdfs-security.xml
+++ b/hdfs-agent/conf/xasecure-hdfs-security.xml
@@ -21,7 +21,7 @@
<!-- The following property is used to select appropriate XASecure Authorizer Module (filebased, policymanager based) -->
<property>
<name>hdfs.authorization.verifier.classname</name>
- <value>com.xasecure.pdp.hdfs.XASecureAuthorizer</value>
+ <value>org.apache.ranger.pdp.hdfs.RangerAuthorizer</value>
<description>
Class Name of the authorization Module
</description>
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hdfs-agent/scripts/install.sh
----------------------------------------------------------------------
diff --git a/hdfs-agent/scripts/install.sh b/hdfs-agent/scripts/install.sh
index cc233da..ba72c4d 100644
--- a/hdfs-agent/scripts/install.sh
+++ b/hdfs-agent/scripts/install.sh
@@ -315,7 +315,7 @@ do
if [ $? -eq 0 ]
then
cp="${install_dir}/installer/lib/*:${hdp_dir}/*:${hdp_lib_dir}/*"
- java -cp "${cp}" com.xasecure.utils.install.XmlConfigChanger -i ${archivefn} -o ${newfn} -c ${f} ${PROP_ARGS}
+ java -cp "${cp}" org.apache.ranger.utils.install.XmlConfigChanger -i ${archivefn} -o ${newfn} -c ${f} ${PROP_ARGS}
if [ $? -eq 0 ]
then
diff -w ${newfn} ${fullpathorgfn} > /dev/null 2>&1
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hdfs-agent/src/main/java/com/xasecure/authorization/hadoop/HDFSAccessVerifier.java
----------------------------------------------------------------------
diff --git a/hdfs-agent/src/main/java/com/xasecure/authorization/hadoop/HDFSAccessVerifier.java b/hdfs-agent/src/main/java/com/xasecure/authorization/hadoop/HDFSAccessVerifier.java
deleted file mode 100644
index 358e765..0000000
--- a/hdfs-agent/src/main/java/com/xasecure/authorization/hadoop/HDFSAccessVerifier.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * 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 com.xasecure.authorization.hadoop;
-
-import java.util.Set;
-
-public interface HDFSAccessVerifier {
- public class AccessContext {
- String agentId;
- int repositoryType;
- String sessionId;
- String clientType;
- String clientIP;
- String requestData;
- }
-
- public boolean isAccessGranted(String aPathName, String aPathOwnerName, String access, String username, Set<String> groups);
- public boolean isAuditLogEnabled(String aPathName) ;
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hdfs-agent/src/main/java/com/xasecure/authorization/hadoop/HDFSAccessVerifierFactory.java
----------------------------------------------------------------------
diff --git a/hdfs-agent/src/main/java/com/xasecure/authorization/hadoop/HDFSAccessVerifierFactory.java b/hdfs-agent/src/main/java/com/xasecure/authorization/hadoop/HDFSAccessVerifierFactory.java
deleted file mode 100644
index 90dc085..0000000
--- a/hdfs-agent/src/main/java/com/xasecure/authorization/hadoop/HDFSAccessVerifierFactory.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * 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 com.xasecure.authorization.hadoop;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import com.xasecure.authorization.hadoop.config.XaSecureConfiguration;
-import com.xasecure.authorization.hadoop.constants.XaSecureHadoopConstants;
-
-public class HDFSAccessVerifierFactory {
-
- private static final Log LOG = LogFactory.getLog(HDFSAccessVerifierFactory.class) ;
-
- private static HDFSAccessVerifier hdfsAccessVerifier = null ;
-
- public static HDFSAccessVerifier getInstance() {
- if (hdfsAccessVerifier == null) {
- synchronized(HDFSAccessVerifierFactory.class) {
- HDFSAccessVerifier temp = hdfsAccessVerifier ;
- if (temp == null) {
-
- String hdfsAccessVerifierClassName = XaSecureConfiguration.getInstance().get(XaSecureHadoopConstants.HDFS_ACCESS_VERIFIER_CLASS_NAME_PROP, XaSecureHadoopConstants.HDFS_ACCESS_VERIFIER_CLASS_NAME_DEFAULT_VALUE) ;
- if (hdfsAccessVerifierClassName != null) {
- try {
- hdfsAccessVerifierClassName = hdfsAccessVerifierClassName.trim();
- hdfsAccessVerifier = (HDFSAccessVerifier) (Class.forName(hdfsAccessVerifierClassName).newInstance()) ;
- LOG.info("Created a new instance of class: [" + hdfsAccessVerifierClassName + "] for HDFS Access verification.");
- } catch (InstantiationException e) {
- LOG.error("Unable to create HdfsAccessVerifier Verifier: [" + hdfsAccessVerifierClassName + "]", e);
- } catch (IllegalAccessException e) {
- LOG.error("Unable to create HdfsAccessVerifier Verifier: [" + hdfsAccessVerifierClassName + "]", e);
- } catch (ClassNotFoundException e) {
- LOG.error("Unable to create HdfsAccessVerifier Verifier: [" + hdfsAccessVerifierClassName + "]", e);
- }
- }
- }
- }
- }
- return hdfsAccessVerifier ;
-
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hdfs-agent/src/main/java/com/xasecure/authorization/hadoop/agent/AuthCodeInjectionJavaAgent.java
----------------------------------------------------------------------
diff --git a/hdfs-agent/src/main/java/com/xasecure/authorization/hadoop/agent/AuthCodeInjectionJavaAgent.java b/hdfs-agent/src/main/java/com/xasecure/authorization/hadoop/agent/AuthCodeInjectionJavaAgent.java
deleted file mode 100644
index bdb2530..0000000
--- a/hdfs-agent/src/main/java/com/xasecure/authorization/hadoop/agent/AuthCodeInjectionJavaAgent.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * 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 com.xasecure.authorization.hadoop.agent;
-
-import java.lang.instrument.Instrumentation;
-
-public class AuthCodeInjectionJavaAgent {
- public static final String AUTHORIZATION_AGENT_PARAM = "authagent";
-
- public static void premain(String agentArgs, Instrumentation inst) {
- if (agentArgs != null && AUTHORIZATION_AGENT_PARAM.equalsIgnoreCase(agentArgs.trim())) {
- inst.addTransformer(new HadoopAuthClassTransformer());
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hdfs-agent/src/main/java/com/xasecure/authorization/hadoop/agent/HadoopAuthClassTransformer.java
----------------------------------------------------------------------
diff --git a/hdfs-agent/src/main/java/com/xasecure/authorization/hadoop/agent/HadoopAuthClassTransformer.java b/hdfs-agent/src/main/java/com/xasecure/authorization/hadoop/agent/HadoopAuthClassTransformer.java
deleted file mode 100644
index 9a8caf2..0000000
--- a/hdfs-agent/src/main/java/com/xasecure/authorization/hadoop/agent/HadoopAuthClassTransformer.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * 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 com.xasecure.authorization.hadoop.agent;
-
-import java.io.IOException;
-import java.lang.instrument.ClassFileTransformer;
-import java.lang.instrument.IllegalClassFormatException;
-import java.security.ProtectionDomain;
-
-import javassist.CannotCompileException;
-import javassist.ClassPool;
-import javassist.CtClass;
-import javassist.CtMethod;
-import javassist.NotFoundException;
-
-public class HadoopAuthClassTransformer implements ClassFileTransformer {
-
- byte[] transformedClassByteCode = null ;
-
- @Override
- public byte[] transform(ClassLoader aClassLoader, String aClassName, Class<?> aClassBeingRedefined, ProtectionDomain aProtectionDomain, byte[] aClassFileBuffer) throws IllegalClassFormatException {
-
- byte[] byteCode = aClassFileBuffer;
- if (aClassName.equals("org/apache/hadoop/hdfs/server/namenode/FSPermissionChecker")) {
- System.out.println("Injection code is Invoked in JVM [" + Runtime.getRuntime() + "] for class [" + aClassBeingRedefined + "] ....");
- try {
- if (transformedClassByteCode == null) {
- ClassPool cp = ClassPool.getDefault();
- String curClassName = aClassName.replaceAll("/", ".");
- CtClass curClass = cp.get(curClassName);
-
-
- CtClass inodeClass = null, snapShotClass = null, fsActionClass = null ;
- String paramClassName = null ;
-
- try {
- paramClassName = "org.apache.hadoop.hdfs.server.namenode.INode" ;
- inodeClass = cp.get(paramClassName) ;
- } catch (javassist.NotFoundException nfe) {
- System.err.println("Unable to find Class for [" + paramClassName + "]" + nfe) ;
- inodeClass = null ;
- }
-
-
- try {
- paramClassName = "org.apache.hadoop.fs.permission.FsAction" ;
- fsActionClass = cp.get(paramClassName) ;
- } catch (javassist.NotFoundException nfe) {
- System.err.println("Unable to find Class for [" + paramClassName + "]" + nfe) ;
- fsActionClass = null ;
- }
-
- try {
- paramClassName = "org.apache.hadoop.hdfs.server.namenode.snapshot.Snapshot" ;
- snapShotClass = cp.get(paramClassName) ;
- } catch (javassist.NotFoundException nfe) {
- System.err.println("Unable to find Class for [" + paramClassName + "]" + nfe) ;
- snapShotClass = null ;
- }
-
- boolean injected = false ;
- boolean injected_cm = false ;
- boolean withIntParamInMiddle = false ;
-
-
- try {
-
- CtClass[] paramArgs = null ;
-
- if (inodeClass != null && fsActionClass != null) {
-
- CtMethod checkMethod = null ;
-
- if (snapShotClass != null) {
- paramArgs = new CtClass[] { inodeClass, snapShotClass, fsActionClass } ;
- try {
- checkMethod = curClass.getDeclaredMethod("check", paramArgs);
- }
- catch(NotFoundException SSnfe) {
- System.out.println("Unable to find check method with snapshot class. Trying to find check method without snapshot support.") ;
- snapShotClass = null;
- paramArgs = new CtClass[] { inodeClass, CtClass.intType, fsActionClass } ;
- checkMethod = curClass.getDeclaredMethod("check", paramArgs);
- withIntParamInMiddle = true ;
- System.out.println("Found method check() - without snapshot support") ;
- }
- }
- else {
- System.out.println("Snapshot class was already null ... Trying to find check method") ;
- paramArgs = new CtClass[] { inodeClass, fsActionClass } ;
- checkMethod = curClass.getDeclaredMethod("check", paramArgs);
- System.out.println("Found method check() - without snapshot support") ;
- }
-
- if (checkMethod != null) {
- if (snapShotClass == null && (!withIntParamInMiddle)) {
- checkMethod.insertAfter("org.apache.hadoop.hdfs.server.namenode.XaSecureFSPermissionChecker.logHadoopEvent(ugi,$1,$2,true) ;");
- CtClass throwable = ClassPool.getDefault().get("java.lang.Throwable");
- checkMethod.addCatch("{ org.apache.hadoop.hdfs.server.namenode.XaSecureFSPermissionChecker.logHadoopEvent(ugi,$1,$2,false) ; throw $e; }", throwable);
- checkMethod.insertBefore("{ if ( org.apache.hadoop.hdfs.server.namenode.XaSecureFSPermissionChecker.check(ugi,$1,$2) ) { return ; } }");
- }
- else {
- checkMethod.insertAfter("org.apache.hadoop.hdfs.server.namenode.XaSecureFSPermissionChecker.logHadoopEvent(ugi,$1,$3,true) ;");
- CtClass throwable = ClassPool.getDefault().get("java.lang.Throwable");
- checkMethod.addCatch("{ org.apache.hadoop.hdfs.server.namenode.XaSecureFSPermissionChecker.logHadoopEvent(ugi,$1,$3,false) ; throw $e; }", throwable);
- checkMethod.insertBefore("{ if ( org.apache.hadoop.hdfs.server.namenode.XaSecureFSPermissionChecker.check(ugi,$1,$3) ) { return ; } }");
- }
- System.out.println("Injection of code is successfull ....");
- }
- else {
- System.out.println("Injection failed. Unable to identify check() method on class: [" + curClass.getName() + "]. Continue without Injection ...") ;
- }
-
- injected = true ;
- }
- } catch (NotFoundException nfex) {
- nfex.printStackTrace();
- System.out.println("Unable to find the check() method with expected params in [" + aClassName + "] ....");
- for (CtMethod m : curClass.getDeclaredMethods()) {
- System.err.println("Found Method: " + m);
- }
- }
-
-
- try {
-
- CtMethod checkMethod = curClass.getDeclaredMethod("checkPermission");
-
- if (checkMethod != null) {
- checkMethod.insertBefore("org.apache.hadoop.hdfs.server.namenode.XaSecureFSPermissionChecker.checkPermissionPre($1) ;");
- checkMethod.insertAfter("org.apache.hadoop.hdfs.server.namenode.XaSecureFSPermissionChecker.writeLog($1) ;");
- CtClass throwable = ClassPool.getDefault().get("org.apache.hadoop.security.AccessControlException");
- checkMethod.addCatch("{ org.apache.hadoop.hdfs.server.namenode.XaSecureFSPermissionChecker.writeLog($1); throw $e; }", throwable);
- injected_cm = true ;
- }
-
- } catch (NotFoundException nfe) {
- nfe.printStackTrace();
- System.out.println("Unable to find the checkPermission() method with expected params in [" + aClassName + "] ....");
- for (CtMethod m : curClass.getDeclaredMethods()) {
- System.err.println("Found Method: " + m);
- }
- }
-
- System.out.println("Injected: " + injected + ", Injected_CheckMethod: " + injected_cm ) ;
-
- if (injected) {
- byteCode = curClass.toBytecode();
- if (transformedClassByteCode == null) {
- synchronized(HadoopAuthClassTransformer.class) {
- byte[] temp = transformedClassByteCode ;
- if (temp == null) {
- transformedClassByteCode = byteCode;
- }
- }
- }
- }
-
- }
- else {
- byteCode = transformedClassByteCode;
- System.out.println("Injection of code (using existing bytecode) is successfull ....");
- }
- } catch (NotFoundException e) {
- System.err.println("Class Not Found Exception for class Name: " + aClassName + " Exception: " + e);
- e.printStackTrace();
- } catch (CannotCompileException e) {
- System.err.println("Can not compile Exception for class Name: " + aClassName + " Exception: " + e);
- e.printStackTrace();
- } catch (IOException e) {
- System.err.println("IO Exception for class Name: " + aClassName + " Exception: " + e);
- e.printStackTrace();
- }
-
- }
-
- return byteCode;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hdfs-agent/src/main/java/com/xasecure/authorization/hadoop/exceptions/XaSecureAccessControlException.java
----------------------------------------------------------------------
diff --git a/hdfs-agent/src/main/java/com/xasecure/authorization/hadoop/exceptions/XaSecureAccessControlException.java b/hdfs-agent/src/main/java/com/xasecure/authorization/hadoop/exceptions/XaSecureAccessControlException.java
deleted file mode 100644
index 90e4600..0000000
--- a/hdfs-agent/src/main/java/com/xasecure/authorization/hadoop/exceptions/XaSecureAccessControlException.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * 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 com.xasecure.authorization.hadoop.exceptions;
-
-import org.apache.hadoop.security.AccessControlException;
-
-
-public class XaSecureAccessControlException extends AccessControlException {
-
- private static final long serialVersionUID = -4673975720243484927L;
-
- public XaSecureAccessControlException(String aMsg) {
- super(aMsg) ;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hdfs-agent/src/main/java/org/apache/hadoop/hdfs/server/namenode/RangerFSPermissionChecker.java
----------------------------------------------------------------------
diff --git a/hdfs-agent/src/main/java/org/apache/hadoop/hdfs/server/namenode/RangerFSPermissionChecker.java b/hdfs-agent/src/main/java/org/apache/hadoop/hdfs/server/namenode/RangerFSPermissionChecker.java
new file mode 100644
index 0000000..f558013
--- /dev/null
+++ b/hdfs-agent/src/main/java/org/apache/hadoop/hdfs/server/namenode/RangerFSPermissionChecker.java
@@ -0,0 +1,317 @@
+/*
+ * 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.hadoop.hdfs.server.namenode;
+
+import static org.apache.ranger.authorization.hadoop.constants.RangerHadoopConstants.*;
+
+import java.net.InetAddress;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.TimeZone;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.fs.permission.FsAction;
+import org.apache.hadoop.ipc.Server;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.ranger.audit.model.EnumRepositoryType;
+import org.apache.ranger.audit.model.HdfsAuditEvent;
+import org.apache.ranger.audit.provider.AuditProviderFactory;
+import org.apache.ranger.authorization.hadoop.HDFSAccessVerifier;
+import org.apache.ranger.authorization.hadoop.HDFSAccessVerifierFactory;
+import org.apache.ranger.authorization.hadoop.config.RangerConfiguration;
+import org.apache.ranger.authorization.hadoop.constants.RangerHadoopConstants;
+import org.apache.ranger.authorization.hadoop.exceptions.RangerAccessControlException;
+
+
+public class RangerFSPermissionChecker {
+
+ private static Map<FsAction, String[]> access2ActionListMapper = null ;
+
+ private static HDFSAccessVerifier authorizer = null ;
+
+ private static final String RangerModuleName = RangerConfiguration.getInstance().get(RangerHadoopConstants.AUDITLOG_RANGER_MODULE_ACL_NAME_PROP , RangerHadoopConstants.DEFAULT_RANGER_MODULE_ACL_NAME) ;
+ private static final String HadoopModuleName = RangerConfiguration.getInstance().get(RangerHadoopConstants.AUDITLOG_HADOOP_MODULE_ACL_NAME_PROP , RangerHadoopConstants.DEFAULT_HADOOP_MODULE_ACL_NAME) ;
+ private static final boolean addHadoopAuth = RangerConfiguration.getInstance().getBoolean(RangerHadoopConstants.RANGER_ADD_HDFS_PERMISSION_PROP, RangerHadoopConstants.RANGER_ADD_HDFS_PERMISSION_DEFAULT) ;
+ private static final String excludeUserList = RangerConfiguration.getInstance().get(RangerHadoopConstants.AUDITLOG_HDFS_EXCLUDE_LIST_PROP, RangerHadoopConstants.AUDITLOG_EMPTY_STRING) ;
+ private static final String repositoryName = RangerConfiguration.getInstance().get(RangerHadoopConstants.AUDITLOG_REPOSITORY_NAME_PROP);
+ private static final boolean isAuditEnabled = RangerConfiguration.getInstance().getBoolean(RangerHadoopConstants.AUDITLOG_IS_ENABLED_PROP, true);
+
+ private static final Log LOG = LogFactory.getLog(RangerFSPermissionChecker.class);
+
+ private static HashSet<String> excludeUsers = null ;
+
+ private static ThreadLocal<LogEventInfo> currentValidatedLogEvent = new ThreadLocal<LogEventInfo>() ;
+
+
+ static {
+ access2ActionListMapper = new HashMap<FsAction, String[]>();
+ access2ActionListMapper.put(FsAction.NONE, new String[] {});
+ access2ActionListMapper.put(FsAction.ALL, new String[] { READ_ACCCESS_TYPE, WRITE_ACCCESS_TYPE, EXECUTE_ACCCESS_TYPE });
+ access2ActionListMapper.put(FsAction.READ, new String[] { READ_ACCCESS_TYPE });
+ access2ActionListMapper.put(FsAction.READ_WRITE, new String[] { READ_ACCCESS_TYPE, WRITE_ACCCESS_TYPE });
+ access2ActionListMapper.put(FsAction.READ_EXECUTE, new String[] { READ_ACCCESS_TYPE, EXECUTE_ACCCESS_TYPE });
+ access2ActionListMapper.put(FsAction.WRITE, new String[] { WRITE_ACCCESS_TYPE });
+ access2ActionListMapper.put(FsAction.WRITE_EXECUTE, new String[] { WRITE_ACCCESS_TYPE, EXECUTE_ACCCESS_TYPE });
+ access2ActionListMapper.put(FsAction.EXECUTE, new String[] { EXECUTE_ACCCESS_TYPE });
+
+ if (excludeUserList != null && excludeUserList.trim().length() > 0) {
+ excludeUsers = new HashSet<String>() ;
+ for(String excludeUser : excludeUserList.trim().split(",")) {
+ excludeUser = excludeUser.trim() ;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Adding exclude user [" + excludeUser + "]");
+ }
+ excludeUsers.add(excludeUser) ;
+ }
+ }
+
+ RangerConfiguration.getInstance().initAudit(AuditProviderFactory.ApplicationType.Hdfs);
+ }
+
+ public static boolean check(UserGroupInformation ugi, INode inode, FsAction access) throws RangerAccessControlException {
+
+ if (inode == null) {
+ return false;
+ }
+
+ String user = ugi.getShortUserName();
+
+ Set<String> groups = Collections.unmodifiableSet(new HashSet<String>(Arrays.asList(ugi.getGroupNames())));
+
+ String pathOwnerName = inode.getUserName() ;
+
+ boolean accessGranted = AuthorizeAccessForUser(inode.getFullPathName(), pathOwnerName, access, user, groups);
+
+ if (!accessGranted && !addHadoopAuth ) {
+ String inodeInfo = (inode.isDirectory() ? "directory" : "file") + "=" + "\"" + inode.getFullPathName() + "\"" ;
+ throw new RangerAccessControlException("Permission denied: principal{user=" + user + ",groups: " + groups + "}, access=" + access + ", " + inodeInfo ) ;
+ }
+
+ return accessGranted ;
+
+ }
+
+ public static boolean AuthorizeAccessForUser(String aPathName, String aPathOwnerName, FsAction access, String user, Set<String> groups) throws RangerAccessControlException {
+ boolean accessGranted = false;
+ try {
+ if (RangerHadoopConstants.HDFS_ROOT_FOLDER_PATH_ALT.equals(aPathName)) {
+ aPathName = RangerHadoopConstants.HDFS_ROOT_FOLDER_PATH;
+ }
+
+ String[] accessTypes = access2ActionListMapper.get(access);
+
+ if ((accessTypes == null) || (accessTypes.length == 0)) {
+ accessGranted = false;
+ } else {
+
+ if (authorizer == null) {
+ synchronized(RangerFSPermissionChecker.class) {
+ HDFSAccessVerifier temp = authorizer ;
+ if (temp == null) {
+ try {
+ authorizer = HDFSAccessVerifierFactory.getInstance();
+ }
+ catch(Throwable t) {
+ LOG.error("Unable to create Authorizer", t);
+ }
+ }
+ }
+ }
+
+ if (authorizer != null) {
+ for (String accessType : accessTypes) {
+ accessGranted = authorizer.isAccessGranted(aPathName, aPathOwnerName, accessType, user, groups);
+ if (!accessGranted) {
+ break;
+ }
+ }
+ }
+ }
+
+ } finally {
+ logEvent(RangerModuleName, user, aPathName, access, accessGranted);
+ }
+ return accessGranted;
+ }
+
+
+ public static void logHadoopEvent(UserGroupInformation ugi, INode inode, FsAction access, boolean accessGranted) {
+ String path = (inode == null) ? RangerHadoopConstants.AUDITLOG_EMPTY_STRING : inode.getFullPathName() ;
+ String username = (ugi == null) ? RangerHadoopConstants.AUDITLOG_EMPTY_STRING : ugi.getShortUserName() ;
+ logEvent(HadoopModuleName, username, path, access, accessGranted);
+ }
+
+
+
+
+
+ private static void logEvent(String moduleName, String username, String path, FsAction access, boolean accessGranted) {
+ LogEventInfo e = null;
+
+ if(isAuditEnabled) {
+ e = new LogEventInfo(moduleName, username, path, access, accessGranted) ;
+ }
+
+ currentValidatedLogEvent.set(e);
+ }
+
+
+ public static void checkPermissionPre(String pathToBeValidated) {
+ // TODO: save the path in a thread-local
+ }
+
+ public static void checkPermissionPost(String pathToBeValidated) {
+ writeLog(pathToBeValidated);
+ }
+
+ public static void writeLog(String pathValidated) {
+
+ LogEventInfo e = currentValidatedLogEvent.get();
+
+ if (e == null) {
+ return ;
+ }
+
+ String username = e.getUserName() ;
+
+ boolean skipLog = (username != null && excludeUsers != null && excludeUsers.contains(username)) ;
+
+ if (skipLog) {
+ return ;
+ }
+
+ String requestedPath = e.getPath() ;
+
+ if (requestedPath == null) {
+ requestedPath = RangerHadoopConstants.AUDITLOG_EMPTY_STRING ;
+ }
+
+ if (! authorizer.isAuditLogEnabled(requestedPath)) {
+ return ;
+ }
+
+
+ String accessType = ( (e.getAccess() == null) ? RangerHadoopConstants.AUDITLOG_EMPTY_STRING : e.getAccess().toString() ) ;
+
+ HdfsAuditEvent auditEvent = new HdfsAuditEvent();
+
+ auditEvent.setUser(username);
+ auditEvent.setResourcePath(requestedPath);
+ auditEvent.setResourceType("HDFSPath") ;
+ auditEvent.setAccessType(accessType);
+ auditEvent.setAccessResult((short)(e.isAccessGranted() ? 1 : 0));
+ auditEvent.setClientIP(getRemoteIp());
+ auditEvent.setEventTime(getUTCDate());
+ auditEvent.setAclEnforcer(e.getModuleName());
+ auditEvent.setRepositoryType(EnumRepositoryType.HDFS);
+ auditEvent.setRepositoryName(repositoryName);
+ auditEvent.setResultReason(pathValidated);
+
+ /*
+ * Review following audit fields for appropriate values
+ *
+ auditEvent.setAgentId();
+ auditEvent.setPolicyId();
+ auditEvent.setSessionId();
+ auditEvent.setClientType();
+ *
+ */
+
+ try {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Audit log of auditEvent: [" + auditEvent.toString() + "] - START.");
+ }
+ AuditProviderFactory.getAuditProvider().log(auditEvent);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Audit log of auditEvent: [" + auditEvent.toString() + "] - END.");
+ }
+ }
+ catch(Throwable t) {
+ LOG.error("ERROR during audit log of auditEvent: [" + auditEvent.toString() + "]", t);
+ }
+ }
+
+
+ private static String getRemoteIp() {
+ String ret = null ;
+ InetAddress ip = Server.getRemoteIp() ;
+ if (ip != null) {
+ ret = ip.getHostAddress();
+ }
+ return ret ;
+ }
+
+
+ public static Date getUTCDate() {
+ Calendar local=Calendar.getInstance();
+ int offset = local.getTimeZone().getOffset(local.getTimeInMillis());
+ GregorianCalendar utc = new GregorianCalendar(TimeZone.getTimeZone("GMT+0"));
+ utc.setTimeInMillis(local.getTimeInMillis());
+ utc.add(Calendar.MILLISECOND, -offset);
+ return utc.getTime();
+ }
+
+}
+
+class LogEventInfo {
+ String moduleName ;
+ String userName ;
+ String path ;
+ FsAction access ;
+ boolean accessGranted ;
+
+ LogEventInfo(String moduleName, String username, String path, FsAction access, boolean accessGranted) {
+ this.moduleName = moduleName ;
+ this.userName = username ;
+ this.path = path ;
+ this.access = access ;
+ this.accessGranted = accessGranted;
+ }
+
+ public String getModuleName() {
+ return moduleName;
+ }
+
+ public String getUserName() {
+ return userName;
+ }
+
+ public String getPath() {
+ return path;
+ }
+
+ public FsAction getAccess() {
+ return access;
+ }
+
+ public boolean isAccessGranted() {
+ return accessGranted;
+ }
+
+
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hdfs-agent/src/main/java/org/apache/hadoop/hdfs/server/namenode/XaSecureFSPermissionChecker.java
----------------------------------------------------------------------
diff --git a/hdfs-agent/src/main/java/org/apache/hadoop/hdfs/server/namenode/XaSecureFSPermissionChecker.java b/hdfs-agent/src/main/java/org/apache/hadoop/hdfs/server/namenode/XaSecureFSPermissionChecker.java
deleted file mode 100644
index ba61d1d..0000000
--- a/hdfs-agent/src/main/java/org/apache/hadoop/hdfs/server/namenode/XaSecureFSPermissionChecker.java
+++ /dev/null
@@ -1,318 +0,0 @@
-/*
- * 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.hadoop.hdfs.server.namenode;
-
-import static com.xasecure.authorization.hadoop.constants.XaSecureHadoopConstants.*;
-
-import java.net.InetAddress;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.Collections;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.TimeZone;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.fs.permission.FsAction;
-import org.apache.hadoop.ipc.Server;
-import org.apache.hadoop.security.UserGroupInformation;
-
-import com.xasecure.audit.model.EnumRepositoryType;
-import com.xasecure.audit.model.HdfsAuditEvent;
-import com.xasecure.audit.provider.AuditProviderFactory;
-import com.xasecure.authorization.hadoop.HDFSAccessVerifier;
-import com.xasecure.authorization.hadoop.HDFSAccessVerifierFactory;
-import com.xasecure.authorization.hadoop.config.XaSecureConfiguration;
-import com.xasecure.authorization.hadoop.constants.XaSecureHadoopConstants;
-import com.xasecure.authorization.hadoop.exceptions.XaSecureAccessControlException;
-
-
-public class XaSecureFSPermissionChecker {
-
- private static Map<FsAction, String[]> access2ActionListMapper = null ;
-
- private static HDFSAccessVerifier authorizer = null ;
-
- private static final String XaSecureModuleName = XaSecureConfiguration.getInstance().get(XaSecureHadoopConstants.AUDITLOG_XASECURE_MODULE_ACL_NAME_PROP , XaSecureHadoopConstants.DEFAULT_XASECURE_MODULE_ACL_NAME) ;
- private static final String HadoopModuleName = XaSecureConfiguration.getInstance().get(XaSecureHadoopConstants.AUDITLOG_HADOOP_MODULE_ACL_NAME_PROP , XaSecureHadoopConstants.DEFAULT_HADOOP_MODULE_ACL_NAME) ;
- private static final boolean addHadoopAuth = XaSecureConfiguration.getInstance().getBoolean(XaSecureHadoopConstants.XASECURE_ADD_HDFS_PERMISSION_PROP, XaSecureHadoopConstants.XASECURE_ADD_HDFS_PERMISSION_DEFAULT) ;
- private static final String excludeUserList = XaSecureConfiguration.getInstance().get(XaSecureHadoopConstants.AUDITLOG_HDFS_EXCLUDE_LIST_PROP, XaSecureHadoopConstants.AUDITLOG_EMPTY_STRING) ;
- private static final String repositoryName = XaSecureConfiguration.getInstance().get(XaSecureHadoopConstants.AUDITLOG_REPOSITORY_NAME_PROP);
- private static final boolean isAuditEnabled = XaSecureConfiguration.getInstance().getBoolean(XaSecureHadoopConstants.AUDITLOG_IS_ENABLED_PROP, true);
-
- private static final Log LOG = LogFactory.getLog(XaSecureFSPermissionChecker.class);
-
- private static HashSet<String> excludeUsers = null ;
-
- private static ThreadLocal<LogEventInfo> currentValidatedLogEvent = new ThreadLocal<LogEventInfo>() ;
-
-
- static {
- access2ActionListMapper = new HashMap<FsAction, String[]>();
- access2ActionListMapper.put(FsAction.NONE, new String[] {});
- access2ActionListMapper.put(FsAction.ALL, new String[] { READ_ACCCESS_TYPE, WRITE_ACCCESS_TYPE, EXECUTE_ACCCESS_TYPE });
- access2ActionListMapper.put(FsAction.READ, new String[] { READ_ACCCESS_TYPE });
- access2ActionListMapper.put(FsAction.READ_WRITE, new String[] { READ_ACCCESS_TYPE, WRITE_ACCCESS_TYPE });
- access2ActionListMapper.put(FsAction.READ_EXECUTE, new String[] { READ_ACCCESS_TYPE, EXECUTE_ACCCESS_TYPE });
- access2ActionListMapper.put(FsAction.WRITE, new String[] { WRITE_ACCCESS_TYPE });
- access2ActionListMapper.put(FsAction.WRITE_EXECUTE, new String[] { WRITE_ACCCESS_TYPE, EXECUTE_ACCCESS_TYPE });
- access2ActionListMapper.put(FsAction.EXECUTE, new String[] { EXECUTE_ACCCESS_TYPE });
-
- if (excludeUserList != null && excludeUserList.trim().length() > 0) {
- excludeUsers = new HashSet<String>() ;
- for(String excludeUser : excludeUserList.trim().split(",")) {
- excludeUser = excludeUser.trim() ;
- if (LOG.isDebugEnabled()) {
- LOG.debug("Adding exclude user [" + excludeUser + "]");
- }
- excludeUsers.add(excludeUser) ;
- }
- }
-
- XaSecureConfiguration.getInstance().initAudit(AuditProviderFactory.ApplicationType.Hdfs);
- }
-
- public static boolean check(UserGroupInformation ugi, INode inode, FsAction access) throws XaSecureAccessControlException {
-
- if (inode == null) {
- return false;
- }
-
- String user = ugi.getShortUserName();
-
- Set<String> groups = Collections.unmodifiableSet(new HashSet<String>(Arrays.asList(ugi.getGroupNames())));
-
- String pathOwnerName = inode.getUserName() ;
-
- boolean accessGranted = AuthorizeAccessForUser(inode.getFullPathName(), pathOwnerName, access, user, groups);
-
- if (!accessGranted && !addHadoopAuth ) {
- String inodeInfo = (inode.isDirectory() ? "directory" : "file") + "=" + "\"" + inode.getFullPathName() + "\"" ;
- throw new XaSecureAccessControlException("Permission denied: principal{user=" + user + ",groups: " + groups + "}, access=" + access + ", " + inodeInfo ) ;
- }
-
- return accessGranted ;
-
- }
-
- public static boolean AuthorizeAccessForUser(String aPathName, String aPathOwnerName, FsAction access, String user, Set<String> groups) throws XaSecureAccessControlException {
- boolean accessGranted = false;
- try {
- if (XaSecureHadoopConstants.HDFS_ROOT_FOLDER_PATH_ALT.equals(aPathName)) {
- aPathName = XaSecureHadoopConstants.HDFS_ROOT_FOLDER_PATH;
- }
-
- String[] accessTypes = access2ActionListMapper.get(access);
-
- if ((accessTypes == null) || (accessTypes.length == 0)) {
- accessGranted = false;
- } else {
-
- if (authorizer == null) {
- synchronized(XaSecureFSPermissionChecker.class) {
- HDFSAccessVerifier temp = authorizer ;
- if (temp == null) {
- try {
- authorizer = HDFSAccessVerifierFactory.getInstance();
- }
- catch(Throwable t) {
- LOG.error("Unable to create Authorizer", t);
- }
- }
- }
- }
-
- if (authorizer != null) {
- for (String accessType : accessTypes) {
- accessGranted = authorizer.isAccessGranted(aPathName, aPathOwnerName, accessType, user, groups);
- if (!accessGranted) {
- break;
- }
- }
- }
- }
-
- } finally {
- logEvent(XaSecureModuleName, user, aPathName, access, accessGranted);
- }
- return accessGranted;
- }
-
-
- public static void logHadoopEvent(UserGroupInformation ugi, INode inode, FsAction access, boolean accessGranted) {
- String path = (inode == null) ? XaSecureHadoopConstants.AUDITLOG_EMPTY_STRING : inode.getFullPathName() ;
- String username = (ugi == null) ? XaSecureHadoopConstants.AUDITLOG_EMPTY_STRING : ugi.getShortUserName() ;
- logEvent(HadoopModuleName, username, path, access, accessGranted);
- }
-
-
-
-
-
- private static void logEvent(String moduleName, String username, String path, FsAction access, boolean accessGranted) {
- LogEventInfo e = null;
-
- if(isAuditEnabled) {
- e = new LogEventInfo(moduleName, username, path, access, accessGranted) ;
- }
-
- currentValidatedLogEvent.set(e);
- }
-
-
- public static void checkPermissionPre(String pathToBeValidated) {
- // TODO: save the path in a thread-local
- }
-
- public static void checkPermissionPost(String pathToBeValidated) {
- writeLog(pathToBeValidated);
- }
-
- public static void writeLog(String pathValidated) {
-
- LogEventInfo e = currentValidatedLogEvent.get();
-
- if (e == null) {
- return ;
- }
-
- String username = e.getUserName() ;
-
- boolean skipLog = (username != null && excludeUsers != null && excludeUsers.contains(username)) ;
-
- if (skipLog) {
- return ;
- }
-
- String requestedPath = e.getPath() ;
-
- if (requestedPath == null) {
- requestedPath = XaSecureHadoopConstants.AUDITLOG_EMPTY_STRING ;
- }
-
- if (! authorizer.isAuditLogEnabled(requestedPath)) {
- return ;
- }
-
-
- String accessType = ( (e.getAccess() == null) ? XaSecureHadoopConstants.AUDITLOG_EMPTY_STRING : e.getAccess().toString() ) ;
-
- HdfsAuditEvent auditEvent = new HdfsAuditEvent();
-
- auditEvent.setUser(username);
- auditEvent.setResourcePath(requestedPath);
- auditEvent.setResourceType("HDFSPath") ;
- auditEvent.setAccessType(accessType);
- auditEvent.setAccessResult((short)(e.isAccessGranted() ? 1 : 0));
- auditEvent.setClientIP(getRemoteIp());
- auditEvent.setEventTime(getUTCDate());
- auditEvent.setAclEnforcer(e.getModuleName());
- auditEvent.setRepositoryType(EnumRepositoryType.HDFS);
- auditEvent.setRepositoryName(repositoryName);
- auditEvent.setResultReason(pathValidated);
-
- /*
- * Review following audit fields for appropriate values
- *
- auditEvent.setAgentId();
- auditEvent.setPolicyId();
- auditEvent.setSessionId();
- auditEvent.setClientType();
- *
- */
-
- try {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Audit log of auditEvent: [" + auditEvent.toString() + "] - START.");
- }
- AuditProviderFactory.getAuditProvider().log(auditEvent);
- if (LOG.isDebugEnabled()) {
- LOG.debug("Audit log of auditEvent: [" + auditEvent.toString() + "] - END.");
- }
- }
- catch(Throwable t) {
- LOG.error("ERROR during audit log of auditEvent: [" + auditEvent.toString() + "]", t);
- }
- }
-
-
- private static String getRemoteIp() {
- String ret = null ;
- InetAddress ip = Server.getRemoteIp() ;
- if (ip != null) {
- ret = ip.getHostAddress();
- }
- return ret ;
- }
-
-
- public static Date getUTCDate() {
- Calendar local=Calendar.getInstance();
- int offset = local.getTimeZone().getOffset(local.getTimeInMillis());
- GregorianCalendar utc = new GregorianCalendar(TimeZone.getTimeZone("GMT+0"));
- utc.setTimeInMillis(local.getTimeInMillis());
- utc.add(Calendar.MILLISECOND, -offset);
- return utc.getTime();
- }
-
-}
-
-class LogEventInfo {
- String moduleName ;
- String userName ;
- String path ;
- FsAction access ;
- boolean accessGranted ;
-
- LogEventInfo(String moduleName, String username, String path, FsAction access, boolean accessGranted) {
- this.moduleName = moduleName ;
- this.userName = username ;
- this.path = path ;
- this.access = access ;
- this.accessGranted = accessGranted;
- }
-
- public String getModuleName() {
- return moduleName;
- }
-
- public String getUserName() {
- return userName;
- }
-
- public String getPath() {
- return path;
- }
-
- public FsAction getAccess() {
- return access;
- }
-
- public boolean isAccessGranted() {
- return accessGranted;
- }
-
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hdfs-agent/src/main/java/org/apache/ranger/authorization/hadoop/HDFSAccessVerifier.java
----------------------------------------------------------------------
diff --git a/hdfs-agent/src/main/java/org/apache/ranger/authorization/hadoop/HDFSAccessVerifier.java b/hdfs-agent/src/main/java/org/apache/ranger/authorization/hadoop/HDFSAccessVerifier.java
new file mode 100644
index 0000000..1a0cb0b
--- /dev/null
+++ b/hdfs-agent/src/main/java/org/apache/ranger/authorization/hadoop/HDFSAccessVerifier.java
@@ -0,0 +1,35 @@
+/*
+ * 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.authorization.hadoop;
+
+import java.util.Set;
+
+public interface HDFSAccessVerifier {
+ public class AccessContext {
+ String agentId;
+ int repositoryType;
+ String sessionId;
+ String clientType;
+ String clientIP;
+ String requestData;
+ }
+
+ public boolean isAccessGranted(String aPathName, String aPathOwnerName, String access, String username, Set<String> groups);
+ public boolean isAuditLogEnabled(String aPathName) ;
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hdfs-agent/src/main/java/org/apache/ranger/authorization/hadoop/HDFSAccessVerifierFactory.java
----------------------------------------------------------------------
diff --git a/hdfs-agent/src/main/java/org/apache/ranger/authorization/hadoop/HDFSAccessVerifierFactory.java b/hdfs-agent/src/main/java/org/apache/ranger/authorization/hadoop/HDFSAccessVerifierFactory.java
new file mode 100644
index 0000000..c4d262a
--- /dev/null
+++ b/hdfs-agent/src/main/java/org/apache/ranger/authorization/hadoop/HDFSAccessVerifierFactory.java
@@ -0,0 +1,58 @@
+/*
+ * 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.authorization.hadoop;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.authorization.hadoop.config.RangerConfiguration;
+import org.apache.ranger.authorization.hadoop.constants.RangerHadoopConstants;
+
+public class HDFSAccessVerifierFactory {
+
+ private static final Log LOG = LogFactory.getLog(HDFSAccessVerifierFactory.class) ;
+
+ private static HDFSAccessVerifier hdfsAccessVerifier = null ;
+
+ public static HDFSAccessVerifier getInstance() {
+ if (hdfsAccessVerifier == null) {
+ synchronized(HDFSAccessVerifierFactory.class) {
+ HDFSAccessVerifier temp = hdfsAccessVerifier ;
+ if (temp == null) {
+
+ String hdfsAccessVerifierClassName = RangerConfiguration.getInstance().get(RangerHadoopConstants.HDFS_ACCESS_VERIFIER_CLASS_NAME_PROP, RangerHadoopConstants.HDFS_ACCESS_VERIFIER_CLASS_NAME_DEFAULT_VALUE) ;
+ if (hdfsAccessVerifierClassName != null) {
+ try {
+ hdfsAccessVerifierClassName = hdfsAccessVerifierClassName.trim();
+ hdfsAccessVerifier = (HDFSAccessVerifier) (Class.forName(hdfsAccessVerifierClassName).newInstance()) ;
+ LOG.info("Created a new instance of class: [" + hdfsAccessVerifierClassName + "] for HDFS Access verification.");
+ } catch (InstantiationException e) {
+ LOG.error("Unable to create HdfsAccessVerifier Verifier: [" + hdfsAccessVerifierClassName + "]", e);
+ } catch (IllegalAccessException e) {
+ LOG.error("Unable to create HdfsAccessVerifier Verifier: [" + hdfsAccessVerifierClassName + "]", e);
+ } catch (ClassNotFoundException e) {
+ LOG.error("Unable to create HdfsAccessVerifier Verifier: [" + hdfsAccessVerifierClassName + "]", e);
+ }
+ }
+ }
+ }
+ }
+ return hdfsAccessVerifier ;
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hdfs-agent/src/main/java/org/apache/ranger/authorization/hadoop/agent/AuthCodeInjectionJavaAgent.java
----------------------------------------------------------------------
diff --git a/hdfs-agent/src/main/java/org/apache/ranger/authorization/hadoop/agent/AuthCodeInjectionJavaAgent.java b/hdfs-agent/src/main/java/org/apache/ranger/authorization/hadoop/agent/AuthCodeInjectionJavaAgent.java
new file mode 100644
index 0000000..b7fd50a
--- /dev/null
+++ b/hdfs-agent/src/main/java/org/apache/ranger/authorization/hadoop/agent/AuthCodeInjectionJavaAgent.java
@@ -0,0 +1,32 @@
+/*
+ * 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.authorization.hadoop.agent;
+
+import java.lang.instrument.Instrumentation;
+
+public class AuthCodeInjectionJavaAgent {
+ public static final String AUTHORIZATION_AGENT_PARAM = "authagent";
+
+ public static void premain(String agentArgs, Instrumentation inst) {
+ if (agentArgs != null && AUTHORIZATION_AGENT_PARAM.equalsIgnoreCase(agentArgs.trim())) {
+ inst.addTransformer(new HadoopAuthClassTransformer());
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hdfs-agent/src/main/java/org/apache/ranger/authorization/hadoop/agent/HadoopAuthClassTransformer.java
----------------------------------------------------------------------
diff --git a/hdfs-agent/src/main/java/org/apache/ranger/authorization/hadoop/agent/HadoopAuthClassTransformer.java b/hdfs-agent/src/main/java/org/apache/ranger/authorization/hadoop/agent/HadoopAuthClassTransformer.java
new file mode 100644
index 0000000..a4c1d45
--- /dev/null
+++ b/hdfs-agent/src/main/java/org/apache/ranger/authorization/hadoop/agent/HadoopAuthClassTransformer.java
@@ -0,0 +1,196 @@
+/*
+ * 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.authorization.hadoop.agent;
+
+import java.io.IOException;
+import java.lang.instrument.ClassFileTransformer;
+import java.lang.instrument.IllegalClassFormatException;
+import java.security.ProtectionDomain;
+
+import javassist.CannotCompileException;
+import javassist.ClassPool;
+import javassist.CtClass;
+import javassist.CtMethod;
+import javassist.NotFoundException;
+
+public class HadoopAuthClassTransformer implements ClassFileTransformer {
+
+ byte[] transformedClassByteCode = null ;
+
+ @Override
+ public byte[] transform(ClassLoader aClassLoader, String aClassName, Class<?> aClassBeingRedefined, ProtectionDomain aProtectionDomain, byte[] aClassFileBuffer) throws IllegalClassFormatException {
+
+ byte[] byteCode = aClassFileBuffer;
+ if (aClassName.equals("org/apache/hadoop/hdfs/server/namenode/FSPermissionChecker")) {
+ System.out.println("Injection code is Invoked in JVM [" + Runtime.getRuntime() + "] for class [" + aClassBeingRedefined + "] ....");
+ try {
+ if (transformedClassByteCode == null) {
+ ClassPool cp = ClassPool.getDefault();
+ String curClassName = aClassName.replaceAll("/", ".");
+ CtClass curClass = cp.get(curClassName);
+
+
+ CtClass inodeClass = null, snapShotClass = null, fsActionClass = null ;
+ String paramClassName = null ;
+
+ try {
+ paramClassName = "org.apache.hadoop.hdfs.server.namenode.INode" ;
+ inodeClass = cp.get(paramClassName) ;
+ } catch (javassist.NotFoundException nfe) {
+ System.err.println("Unable to find Class for [" + paramClassName + "]" + nfe) ;
+ inodeClass = null ;
+ }
+
+
+ try {
+ paramClassName = "org.apache.hadoop.fs.permission.FsAction" ;
+ fsActionClass = cp.get(paramClassName) ;
+ } catch (javassist.NotFoundException nfe) {
+ System.err.println("Unable to find Class for [" + paramClassName + "]" + nfe) ;
+ fsActionClass = null ;
+ }
+
+ try {
+ paramClassName = "org.apache.hadoop.hdfs.server.namenode.snapshot.Snapshot" ;
+ snapShotClass = cp.get(paramClassName) ;
+ } catch (javassist.NotFoundException nfe) {
+ System.err.println("Unable to find Class for [" + paramClassName + "]" + nfe) ;
+ snapShotClass = null ;
+ }
+
+ boolean injected = false ;
+ boolean injected_cm = false ;
+ boolean withIntParamInMiddle = false ;
+
+
+ try {
+
+ CtClass[] paramArgs = null ;
+
+ if (inodeClass != null && fsActionClass != null) {
+
+ CtMethod checkMethod = null ;
+
+ if (snapShotClass != null) {
+ paramArgs = new CtClass[] { inodeClass, snapShotClass, fsActionClass } ;
+ try {
+ checkMethod = curClass.getDeclaredMethod("check", paramArgs);
+ }
+ catch(NotFoundException SSnfe) {
+ System.out.println("Unable to find check method with snapshot class. Trying to find check method without snapshot support.") ;
+ snapShotClass = null;
+ paramArgs = new CtClass[] { inodeClass, CtClass.intType, fsActionClass } ;
+ checkMethod = curClass.getDeclaredMethod("check", paramArgs);
+ withIntParamInMiddle = true ;
+ System.out.println("Found method check() - without snapshot support") ;
+ }
+ }
+ else {
+ System.out.println("Snapshot class was already null ... Trying to find check method") ;
+ paramArgs = new CtClass[] { inodeClass, fsActionClass } ;
+ checkMethod = curClass.getDeclaredMethod("check", paramArgs);
+ System.out.println("Found method check() - without snapshot support") ;
+ }
+
+ if (checkMethod != null) {
+ if (snapShotClass == null && (!withIntParamInMiddle)) {
+ checkMethod.insertAfter("org.apache.hadoop.hdfs.server.namenode.RangerFSPermissionChecker.logHadoopEvent(ugi,$1,$2,true) ;");
+ CtClass throwable = ClassPool.getDefault().get("java.lang.Throwable");
+ checkMethod.addCatch("{ org.apache.hadoop.hdfs.server.namenode.RangerFSPermissionChecker.logHadoopEvent(ugi,$1,$2,false) ; throw $e; }", throwable);
+ checkMethod.insertBefore("{ if ( org.apache.hadoop.hdfs.server.namenode.RangerFSPermissionChecker.check(ugi,$1,$2) ) { return ; } }");
+ }
+ else {
+ checkMethod.insertAfter("org.apache.hadoop.hdfs.server.namenode.RangerFSPermissionChecker.logHadoopEvent(ugi,$1,$3,true) ;");
+ CtClass throwable = ClassPool.getDefault().get("java.lang.Throwable");
+ checkMethod.addCatch("{ org.apache.hadoop.hdfs.server.namenode.RangerFSPermissionChecker.logHadoopEvent(ugi,$1,$3,false) ; throw $e; }", throwable);
+ checkMethod.insertBefore("{ if ( org.apache.hadoop.hdfs.server.namenode.RangerFSPermissionChecker.check(ugi,$1,$3) ) { return ; } }");
+ }
+ System.out.println("Injection of code is successfull ....");
+ }
+ else {
+ System.out.println("Injection failed. Unable to identify check() method on class: [" + curClass.getName() + "]. Continue without Injection ...") ;
+ }
+
+ injected = true ;
+ }
+ } catch (NotFoundException nfex) {
+ nfex.printStackTrace();
+ System.out.println("Unable to find the check() method with expected params in [" + aClassName + "] ....");
+ for (CtMethod m : curClass.getDeclaredMethods()) {
+ System.err.println("Found Method: " + m);
+ }
+ }
+
+
+ try {
+
+ CtMethod checkMethod = curClass.getDeclaredMethod("checkPermission");
+
+ if (checkMethod != null) {
+ checkMethod.insertBefore("org.apache.hadoop.hdfs.server.namenode.RangerFSPermissionChecker.checkPermissionPre($1) ;");
+ checkMethod.insertAfter("org.apache.hadoop.hdfs.server.namenode.RangerFSPermissionChecker.writeLog($1) ;");
+ CtClass throwable = ClassPool.getDefault().get("org.apache.hadoop.security.AccessControlException");
+ checkMethod.addCatch("{ org.apache.hadoop.hdfs.server.namenode.RangerFSPermissionChecker.writeLog($1); throw $e; }", throwable);
+ injected_cm = true ;
+ }
+
+ } catch (NotFoundException nfe) {
+ nfe.printStackTrace();
+ System.out.println("Unable to find the checkPermission() method with expected params in [" + aClassName + "] ....");
+ for (CtMethod m : curClass.getDeclaredMethods()) {
+ System.err.println("Found Method: " + m);
+ }
+ }
+
+ System.out.println("Injected: " + injected + ", Injected_CheckMethod: " + injected_cm ) ;
+
+ if (injected) {
+ byteCode = curClass.toBytecode();
+ if (transformedClassByteCode == null) {
+ synchronized(HadoopAuthClassTransformer.class) {
+ byte[] temp = transformedClassByteCode ;
+ if (temp == null) {
+ transformedClassByteCode = byteCode;
+ }
+ }
+ }
+ }
+
+ }
+ else {
+ byteCode = transformedClassByteCode;
+ System.out.println("Injection of code (using existing bytecode) is successfull ....");
+ }
+ } catch (NotFoundException e) {
+ System.err.println("Class Not Found Exception for class Name: " + aClassName + " Exception: " + e);
+ e.printStackTrace();
+ } catch (CannotCompileException e) {
+ System.err.println("Can not compile Exception for class Name: " + aClassName + " Exception: " + e);
+ e.printStackTrace();
+ } catch (IOException e) {
+ System.err.println("IO Exception for class Name: " + aClassName + " Exception: " + e);
+ e.printStackTrace();
+ }
+
+ }
+
+ return byteCode;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hdfs-agent/src/main/java/org/apache/ranger/authorization/hadoop/exceptions/RangerAccessControlException.java
----------------------------------------------------------------------
diff --git a/hdfs-agent/src/main/java/org/apache/ranger/authorization/hadoop/exceptions/RangerAccessControlException.java b/hdfs-agent/src/main/java/org/apache/ranger/authorization/hadoop/exceptions/RangerAccessControlException.java
new file mode 100644
index 0000000..68ca895
--- /dev/null
+++ b/hdfs-agent/src/main/java/org/apache/ranger/authorization/hadoop/exceptions/RangerAccessControlException.java
@@ -0,0 +1,32 @@
+/*
+ * 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.authorization.hadoop.exceptions;
+
+import org.apache.hadoop.security.AccessControlException;
+
+
+public class RangerAccessControlException extends AccessControlException {
+
+ private static final long serialVersionUID = -4673975720243484927L;
+
+ public RangerAccessControlException(String aMsg) {
+ super(aMsg) ;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hdfs-agent/src/main/resources/META-INF/MANIFEST.MF
----------------------------------------------------------------------
diff --git a/hdfs-agent/src/main/resources/META-INF/MANIFEST.MF b/hdfs-agent/src/main/resources/META-INF/MANIFEST.MF
index 0d9d2b4..a8ea649 100644
--- a/hdfs-agent/src/main/resources/META-INF/MANIFEST.MF
+++ b/hdfs-agent/src/main/resources/META-INF/MANIFEST.MF
@@ -1 +1 @@
-premain-class: com.xasecure.authorization.hadoop.agent.AuthCodeInjectionJavaAgent
+premain-class: org.apache.ranger.authorization.hadoop.agent.AuthCodeInjectionJavaAgent
[10/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXRepositoryList.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXRepositoryList.java b/security-admin/src/main/java/com/xasecure/view/VXRepositoryList.java
deleted file mode 100644
index 298fab3..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXRepositoryList.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-
-/**
- * List wrapper class for VXRepository
- */
-
-import java.util.*;
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-import com.xasecure.common.view.*;
-
-@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY)
-@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.FIELD)
-public class VXRepositoryList extends VList {
- private static final long serialVersionUID = 1L;
- List<VXRepository> vXRepositories = new ArrayList<VXRepository>();
-
- public VXRepositoryList() {
- super();
- }
-
- public VXRepositoryList(List<VXRepository> objList) {
- super(objList);
- this.vXRepositories = objList;
- }
-
- /**
- * @return the vXRepositories
- */
- public List<VXRepository> getVXRepositories() {
- return vXRepositories;
- }
-
- /**
- * @param vXRepositories
- * the vXRepositories to set
- */
- public void setVXRepositories(List<VXRepository> vXRepositories) {
- this.vXRepositories = vXRepositories;
- }
-
- @Override
- public int getListSize() {
- if (vXRepositories != null) {
- return vXRepositories.size();
- }
- return 0;
- }
-
- @Override
- public List<VXRepository> getList() {
- return vXRepositories;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXResource.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXResource.java b/security-admin/src/main/java/com/xasecure/view/VXResource.java
deleted file mode 100644
index 3619ef7..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXResource.java
+++ /dev/null
@@ -1,624 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * Resource
- *
- */
-
-import java.util.*;
-
-import com.xasecure.common.*;
-import com.xasecure.common.view.*;
-import com.xasecure.common.*;
-import com.xasecure.json.JsonDateSerializer;
-import com.xasecure.view.*;
-
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@JsonIgnoreProperties(ignoreUnknown=true)
-@XmlRootElement
-public class VXResource extends VXDataObject implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- /**
- * Name
- */
- protected String name;
- protected String policyName;
- /**
- * Description
- */
- protected String description;
- /**
- * Status
- * This attribute is of type enum CommonEnums::ResourceType
- */
- protected int resourceType;
- /**
- * Id of the asset
- */
- protected Long assetId;
- /**
- * Id of the parent
- */
- protected Long parentId;
- /**
- * Path for the parent
- */
- protected String parentPath;
- /**
- * Whether to encrypt this resource
- * This attribute is of type enum CommonEnums::BooleanValue
- */
- protected int isEncrypt = XAConstants.BOOL_FALSE;
- /**
- * List of permissions maps
- */
- protected List<VXPermMap> permMapList;
- /**
- * List of audits
- */
- protected List<VXAuditMap> auditList;
- /**
- * Is recursive
- * This attribute is of type enum CommonEnums::BooleanValue
- */
- protected int isRecursive = XAConstants.BOOL_NONE;
- /**
- * Group to which this resource belongs to
- */
- protected String resourceGroup;
- /**
- * Databases
- */
- protected String databases;
- /**
- * Tables
- */
- protected String tables;
- /**
- * Column families
- */
- protected String columnFamilies;
- /**
- * Columns
- */
- protected String columns;
- /**
- * UDFs
- */
- protected String udfs;
- /**
- * Asset Name
- */
- protected String assetName;
- /**
- * Asset Type
- */
- protected int assetType;
- /**
- * Resource Status
- */
- protected int resourceStatus;
- /**
- * Table Type
- */
- protected int tableType;
- /**
- * Resource Status
- */
- protected int columnType;
- /**
- * Check parent permission
- * This attribute is of type enum CommonEnums::BooleanValue
- */
- protected int checkParentPermission = XAConstants.BOOL_NONE;
- /**
- * Topologoies
- */
- protected String topologies;
- /**
- * Services
- */
- protected String services;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VXResource ( ) {
- resourceType = AppConstants.RESOURCE_PATH;
- isEncrypt = XAConstants.BOOL_FALSE;
- isRecursive = XAConstants.BOOL_NONE;
- checkParentPermission = XAConstants.BOOL_NONE;
- }
-
- /**
- * This method sets the value to the member attribute <b>name</b>.
- * You cannot set null to the attribute.
- * @param name Value to set member attribute <b>name</b>
- */
- public void setName( String name ) {
- this.name = name;
- }
-
- /**
- * Returns the value for the member attribute <b>name</b>
- * @return String - value of member attribute <b>name</b>.
- */
- public String getName( ) {
- return this.name;
- }
-
- public String getPolicyName() {
- return policyName;
- }
-
- public void setPolicyName(String policyName) {
- this.policyName = policyName;
- }
-
- /**
- * This method sets the value to the member attribute <b>description</b>.
- * You cannot set null to the attribute.
- * @param description Value to set member attribute <b>description</b>
- */
- public void setDescription( String description ) {
- this.description = description;
- }
-
- /**
- * Returns the value for the member attribute <b>description</b>
- * @return String - value of member attribute <b>description</b>.
- */
- public String getDescription( ) {
- return this.description;
- }
-
- /**
- * This method sets the value to the member attribute <b>resourceType</b>.
- * You cannot set null to the attribute.
- * @param resourceType Value to set member attribute <b>resourceType</b>
- */
- public void setResourceType( int resourceType ) {
- this.resourceType = resourceType;
- }
-
- /**
- * Returns the value for the member attribute <b>resourceType</b>
- * @return int - value of member attribute <b>resourceType</b>.
- */
- public int getResourceType( ) {
- return this.resourceType;
- }
-
- /**
- * This method sets the value to the member attribute <b>assetId</b>.
- * You cannot set null to the attribute.
- * @param assetId Value to set member attribute <b>assetId</b>
- */
- public void setAssetId( Long assetId ) {
- this.assetId = assetId;
- }
-
- /**
- * Returns the value for the member attribute <b>assetId</b>
- * @return Long - value of member attribute <b>assetId</b>.
- */
- public Long getAssetId( ) {
- return this.assetId;
- }
-
- /**
- * This method sets the value to the member attribute <b>parentId</b>.
- * You cannot set null to the attribute.
- * @param parentId Value to set member attribute <b>parentId</b>
- */
- public void setParentId( Long parentId ) {
- this.parentId = parentId;
- }
-
- /**
- * Returns the value for the member attribute <b>parentId</b>
- * @return Long - value of member attribute <b>parentId</b>.
- */
- public Long getParentId( ) {
- return this.parentId;
- }
-
- /**
- * This method sets the value to the member attribute <b>parentPath</b>.
- * You cannot set null to the attribute.
- * @param parentPath Value to set member attribute <b>parentPath</b>
- */
- public void setParentPath( String parentPath ) {
- this.parentPath = parentPath;
- }
-
- /**
- * Returns the value for the member attribute <b>parentPath</b>
- * @return String - value of member attribute <b>parentPath</b>.
- */
- public String getParentPath( ) {
- return this.parentPath;
- }
-
- /**
- * This method sets the value to the member attribute <b>isEncrypt</b>.
- * You cannot set null to the attribute.
- * @param isEncrypt Value to set member attribute <b>isEncrypt</b>
- */
- public void setIsEncrypt( int isEncrypt ) {
- this.isEncrypt = isEncrypt;
- }
-
- /**
- * Returns the value for the member attribute <b>isEncrypt</b>
- * @return int - value of member attribute <b>isEncrypt</b>.
- */
- public int getIsEncrypt( ) {
- return this.isEncrypt;
- }
-
- /**
- * This method sets the value to the member attribute <b>permMapList</b>.
- * You cannot set null to the attribute.
- * @param permMapList Value to set member attribute <b>permMapList</b>
- */
- public void setPermMapList( List<VXPermMap> permMapList ) {
- this.permMapList = permMapList;
- }
-
- /**
- * Returns the value for the member attribute <b>permMapList</b>
- * @return List<VXPermMap> - value of member attribute <b>permMapList</b>.
- */
- public List<VXPermMap> getPermMapList( ) {
- return this.permMapList;
- }
-
- /**
- * This method sets the value to the member attribute <b>auditList</b>.
- * You cannot set null to the attribute.
- * @param auditList Value to set member attribute <b>auditList</b>
- */
- public void setAuditList( List<VXAuditMap> auditList ) {
- this.auditList = auditList;
- }
-
- /**
- * Returns the value for the member attribute <b>auditList</b>
- * @return List<VXAuditMap> - value of member attribute <b>auditList</b>.
- */
- public List<VXAuditMap> getAuditList( ) {
- return this.auditList;
- }
-
- /**
- * This method sets the value to the member attribute <b>isRecursive</b>.
- * You cannot set null to the attribute.
- * @param isRecursive Value to set member attribute <b>isRecursive</b>
- */
- public void setIsRecursive( int isRecursive ) {
- this.isRecursive = isRecursive;
- }
-
- /**
- * Returns the value for the member attribute <b>isRecursive</b>
- * @return int - value of member attribute <b>isRecursive</b>.
- */
- public int getIsRecursive( ) {
- return this.isRecursive;
- }
-
- /**
- * This method sets the value to the member attribute <b>resourceGroup</b>.
- * You cannot set null to the attribute.
- * @param resourceGroup Value to set member attribute <b>resourceGroup</b>
- */
- public void setResourceGroup( String resourceGroup ) {
- this.resourceGroup = resourceGroup;
- }
-
- /**
- * Returns the value for the member attribute <b>resourceGroup</b>
- * @return String - value of member attribute <b>resourceGroup</b>.
- */
- public String getResourceGroup( ) {
- return this.resourceGroup;
- }
-
- /**
- * This method sets the value to the member attribute <b>databases</b>.
- * You cannot set null to the attribute.
- * @param databases Value to set member attribute <b>databases</b>
- */
- public void setDatabases( String databases ) {
- this.databases = databases;
- }
-
- /**
- * Returns the value for the member attribute <b>databases</b>
- * @return String - value of member attribute <b>databases</b>.
- */
- public String getDatabases( ) {
- return this.databases;
- }
-
- /**
- * This method sets the value to the member attribute <b>tables</b>.
- * You cannot set null to the attribute.
- * @param tables Value to set member attribute <b>tables</b>
- */
- public void setTables( String tables ) {
- this.tables = tables;
- }
-
- /**
- * Returns the value for the member attribute <b>tables</b>
- * @return String - value of member attribute <b>tables</b>.
- */
- public String getTables( ) {
- return this.tables;
- }
-
- /**
- * This method sets the value to the member attribute <b>columnFamilies</b>.
- * You cannot set null to the attribute.
- * @param columnFamilies Value to set member attribute <b>columnFamilies</b>
- */
- public void setColumnFamilies( String columnFamilies ) {
- this.columnFamilies = columnFamilies;
- }
-
- /**
- * Returns the value for the member attribute <b>columnFamilies</b>
- * @return String - value of member attribute <b>columnFamilies</b>.
- */
- public String getColumnFamilies( ) {
- return this.columnFamilies;
- }
-
- /**
- * This method sets the value to the member attribute <b>columns</b>.
- * You cannot set null to the attribute.
- * @param columns Value to set member attribute <b>columns</b>
- */
- public void setColumns( String columns ) {
- this.columns = columns;
- }
-
- /**
- * Returns the value for the member attribute <b>columns</b>
- * @return String - value of member attribute <b>columns</b>.
- */
- public String getColumns( ) {
- return this.columns;
- }
-
- /**
- * This method sets the value to the member attribute <b>udfs</b>.
- * You cannot set null to the attribute.
- * @param udfs Value to set member attribute <b>udfs</b>
- */
- public void setUdfs( String udfs ) {
- this.udfs = udfs;
- }
-
- /**
- * Returns the value for the member attribute <b>udfs</b>
- * @return String - value of member attribute <b>udfs</b>.
- */
- public String getUdfs( ) {
- return this.udfs;
- }
-
- /**
- * This method sets the value to the member attribute <b>assetName</b>.
- * You cannot set null to the attribute.
- * @param assetName Value to set member attribute <b>assetName</b>
- */
- public void setAssetName( String assetName ) {
- this.assetName = assetName;
- }
-
- /**
- * Returns the value for the member attribute <b>assetName</b>
- * @return String - value of member attribute <b>assetName</b>.
- */
- public String getAssetName( ) {
- return this.assetName;
- }
-
- /**
- * This method sets the value to the member attribute <b>assetType</b>.
- * You cannot set null to the attribute.
- * @param assetType Value to set member attribute <b>assetType</b>
- */
- public void setAssetType( int assetType ) {
- this.assetType = assetType;
- }
-
- /**
- * Returns the value for the member attribute <b>assetType</b>
- * @return int - value of member attribute <b>assetType</b>.
- */
- public int getAssetType( ) {
- return this.assetType;
- }
-
- /**
- * This method sets the value to the member attribute <b>resourceStatus</b>.
- * You cannot set null to the attribute.
- * @param resourceStatus Value to set member attribute <b>resourceStatus</b>
- */
- public void setResourceStatus( int resourceStatus ) {
- this.resourceStatus = resourceStatus;
- }
-
- /**
- * Returns the value for the member attribute <b>resourceStatus</b>
- * @return int - value of member attribute <b>resourceStatus</b>.
- */
- public int getResourceStatus( ) {
- return this.resourceStatus;
- }
-
- /**
- * This method sets the value to the member attribute <b>tableType</b>.
- * You cannot set null to the attribute.
- * @param tableType Value to set member attribute <b>tableType</b>
- */
- public void setTableType( int tableType ) {
- this.tableType = tableType;
- }
-
- /**
- * Returns the value for the member attribute <b>tableType</b>
- * @return int - value of member attribute <b>tableType</b>.
- */
- public int getTableType( ) {
- return this.tableType;
- }
-
- /**
- * This method sets the value to the member attribute <b>columnType</b>.
- * You cannot set null to the attribute.
- * @param columnType Value to set member attribute <b>columnType</b>
- */
- public void setColumnType( int columnType ) {
- this.columnType = columnType;
- }
-
- /**
- * Returns the value for the member attribute <b>columnType</b>
- * @return int - value of member attribute <b>columnType</b>.
- */
- public int getColumnType( ) {
- return this.columnType;
- }
-
- /**
- * Returns the value for the member attribute <b>topologies</b>
- *
- * @return String - value of member attribute <b>topologies</b>.
- */
- public String getTopologies() {
- return topologies;
- }
-
- /**
- * This method sets the value to the member attribute <b>topologies</b>. You
- * cannot set null to the attribute.
- *
- * @param topologies
- * Value to set member attribute <b>topologies</b>
- */
- public void setTopologies(String topologies) {
- this.topologies = topologies;
- }
-
- /**
- * Returns the value for the member attribute <b>services</b>
- *
- * @return String - value of member attribute <b>services</b>.
- */
- public String getServices() {
- return services;
- }
-
- /**
- * This method sets the value to the member attribute <b>services</b>. You
- * cannot set null to the attribute.
- *
- * @param services
- * Value to set member attribute <b>services</b>
- */
- public void setServices(String services) {
- this.services = services;
- }
-
- /**
- * This method sets the value to the member attribute <b>checkParentPermission</b>.
- * You cannot set null to the attribute.
- * @param checkParentPermission Value to set member attribute <b>checkParentPermission</b>
- */
- public void setCheckParentPermission( int checkParentPermission ) {
- this.checkParentPermission = checkParentPermission;
- }
-
- /**
- * Returns the value for the member attribute <b>checkParentPermission</b>
- * @return int - value of member attribute <b>checkParentPermission</b>.
- */
- public int getCheckParentPermission( ) {
- return this.checkParentPermission;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_XA_RESOURCE;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- public String toString( ) {
- String str = "VXResource={";
- str += super.toString();
- str += "name={" + name + "} ";
- str += "policyName={" + policyName + "} ";
- str += "description={" + description + "} ";
- str += "resourceType={" + resourceType + "} ";
- str += "assetId={" + assetId + "} ";
- str += "parentId={" + parentId + "} ";
- str += "parentPath={" + parentPath + "} ";
- str += "isEncrypt={" + isEncrypt + "} ";
- str += "permMapList={" + permMapList + "} ";
- str += "auditList={" + auditList + "} ";
- str += "isRecursive={" + isRecursive + "} ";
- str += "resourceGroup={" + resourceGroup + "} ";
- str += "databases={" + databases + "} ";
- str += "tables={" + tables + "} ";
- str += "columnFamilies={" + columnFamilies + "} ";
- str += "columns={" + columns + "} ";
- str += "udfs={" + udfs + "} ";
- str += "assetName={" + assetName + "} ";
- str += "assetType={" + assetType + "} ";
- str += "resourceStatus={" + resourceStatus + "} ";
- str += "tableType={" + tableType + "} ";
- str += "columnType={" + columnType + "} ";
- str += "checkParentPermission={" + checkParentPermission + "} ";
- str += "topologies={" + topologies + "} ";
- str += "services={" + services + "} ";
- str += "}";
- return str;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXResourceList.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXResourceList.java b/security-admin/src/main/java/com/xasecure/view/VXResourceList.java
deleted file mode 100644
index d261477..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXResourceList.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * List wrapper class for VXResource
- *
- */
-
-import java.util.*;
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-import com.xasecure.common.view.*;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.FIELD)
-public class VXResourceList extends VList {
- private static final long serialVersionUID = 1L;
- List<VXResource> vXResources = new ArrayList<VXResource>();
-
- public VXResourceList() {
- super();
- }
-
- public VXResourceList(List<VXResource> objList) {
- super(objList);
- this.vXResources = objList;
- }
-
- /**
- * @return the vXResources
- */
- public List<VXResource> getVXResources() {
- return vXResources;
- }
-
- /**
- * @param vXResources
- * the vXResources to set
- */
- public void setVXResources(List<VXResource> vXResources) {
- this.vXResources = vXResources;
- }
-
- @Override
- public int getListSize() {
- if (vXResources != null) {
- return vXResources.size();
- }
- return 0;
- }
-
- @Override
- public List<VXResource> getList() {
- return vXResources;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXResponse.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXResponse.java b/security-admin/src/main/java/com/xasecure/view/VXResponse.java
deleted file mode 100644
index 2650fb3..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXResponse.java
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * Response
- *
- */
-
-import java.util.*;
-
-import com.xasecure.common.*;
-import com.xasecure.common.view.*;
-
-import com.xasecure.common.*;
-import com.xasecure.json.JsonDateSerializer;
-
-import com.xasecure.view.*;
-
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@JsonIgnoreProperties(ignoreUnknown=true)
-@XmlRootElement
-public class VXResponse extends ViewBaseBean implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
- /**
- * Enum values for ResponseStatus
- */
- /**
- * STATUS_SUCCESS is an element of enum ResponseStatus. Its value is "STATUS_SUCCESS".
- */
- public static final int STATUS_SUCCESS = 0;
- /**
- * STATUS_ERROR is an element of enum ResponseStatus. Its value is "STATUS_ERROR".
- */
- public static final int STATUS_ERROR = 1;
- /**
- * STATUS_VALIDATION is an element of enum ResponseStatus. Its value is "STATUS_VALIDATION".
- */
- public static final int STATUS_VALIDATION = 2;
- /**
- * STATUS_WARN is an element of enum ResponseStatus. Its value is "STATUS_WARN".
- */
- public static final int STATUS_WARN = 3;
- /**
- * STATUS_INFO is an element of enum ResponseStatus. Its value is "STATUS_INFO".
- */
- public static final int STATUS_INFO = 4;
- /**
- * STATUS_PARTIAL_SUCCESS is an element of enum ResponseStatus. Its value is "STATUS_PARTIAL_SUCCESS".
- */
- public static final int STATUS_PARTIAL_SUCCESS = 5;
-
- /**
- * Max value for enum ResponseStatus_MAX
- */
- public static final int ResponseStatus_MAX = 5;
-
-
- /**
- * Status code
- * This attribute is of type enum XResponse::ResponseStatus
- */
- protected int statusCode;
- /**
- * Message description
- */
- protected String msgDesc;
- /**
- * List of messages
- */
- protected List<VXMessage> messageList;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VXResponse ( ) {
- statusCode = 0;
- }
-
- /**
- * This method sets the value to the member attribute <b>statusCode</b>.
- * You cannot set null to the attribute.
- * @param statusCode Value to set member attribute <b>statusCode</b>
- */
- public void setStatusCode( int statusCode ) {
- this.statusCode = statusCode;
- }
-
- /**
- * Returns the value for the member attribute <b>statusCode</b>
- * @return int - value of member attribute <b>statusCode</b>.
- */
- public int getStatusCode( ) {
- return this.statusCode;
- }
-
- /**
- * This method sets the value to the member attribute <b>msgDesc</b>.
- * You cannot set null to the attribute.
- * @param msgDesc Value to set member attribute <b>msgDesc</b>
- */
- public void setMsgDesc( String msgDesc ) {
- this.msgDesc = msgDesc;
- }
-
- /**
- * Returns the value for the member attribute <b>msgDesc</b>
- * @return String - value of member attribute <b>msgDesc</b>.
- */
- public String getMsgDesc( ) {
- return this.msgDesc;
- }
-
- /**
- * This method sets the value to the member attribute <b>messageList</b>.
- * You cannot set null to the attribute.
- * @param messageList Value to set member attribute <b>messageList</b>
- */
- public void setMessageList( List<VXMessage> messageList ) {
- this.messageList = messageList;
- }
-
- /**
- * Returns the value for the member attribute <b>messageList</b>
- * @return List<VXMessage> - value of member attribute <b>messageList</b>.
- */
- public List<VXMessage> getMessageList( ) {
- return this.messageList;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_RESPONSE;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- public String toString( ) {
- String str = "VXResponse={";
- str += super.toString();
- str += "statusCode={" + statusCode + "} ";
- str += "msgDesc={" + msgDesc + "} ";
- str += "messageList={" + messageList + "} ";
- str += "}";
- return str;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXString.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXString.java b/security-admin/src/main/java/com/xasecure/view/VXString.java
deleted file mode 100644
index 002b338..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXString.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * String
- *
- */
-
-import java.util.*;
-
-import com.xasecure.common.*;
-import com.xasecure.common.view.*;
-
-import com.xasecure.common.*;
-import com.xasecure.json.JsonDateSerializer;
-
-import com.xasecure.view.*;
-
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@JsonIgnoreProperties(ignoreUnknown=true)
-@XmlRootElement
-public class VXString extends ViewBaseBean implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- /**
- * Value
- */
- protected String value;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VXString ( ) {
- }
-
- /**
- * This method sets the value to the member attribute <b>value</b>.
- * You cannot set null to the attribute.
- * @param value Value to set member attribute <b>value</b>
- */
- public void setValue( String value ) {
- this.value = value;
- }
-
- /**
- * Returns the value for the member attribute <b>value</b>
- * @return String - value of member attribute <b>value</b>.
- */
- public String getValue( ) {
- return this.value;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_STRING;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- public String toString( ) {
- String str = "VXString={";
- str += super.toString();
- str += "value={" + value + "} ";
- str += "}";
- return str;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXStringList.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXStringList.java b/security-admin/src/main/java/com/xasecure/view/VXStringList.java
deleted file mode 100644
index b2cc0af..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXStringList.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * List wrapper class for VXString
- *
- */
-
-import java.util.*;
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-import com.xasecure.common.view.*;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.FIELD)
-public class VXStringList extends VList {
- private static final long serialVersionUID = 1L;
- List<VXString> vXStrings = new ArrayList<VXString>();
-
- public VXStringList() {
- super();
- }
-
- public VXStringList(List<VXString> objList) {
- super(objList);
- this.vXStrings = objList;
- }
-
- /**
- * @return the vXStrings
- */
- public List<VXString> getVXStrings() {
- return vXStrings;
- }
-
- /**
- * @param vXStrings
- * the vXStrings to set
- */
- public void setVXStrings(List<VXString> vXStrings) {
- this.vXStrings = vXStrings;
- }
-
- @Override
- public int getListSize() {
- if (vXStrings != null) {
- return vXStrings.size();
- }
- return 0;
- }
-
- @Override
- public List<VXString> getList() {
- return vXStrings;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXTrxLog.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXTrxLog.java b/security-admin/src/main/java/com/xasecure/view/VXTrxLog.java
deleted file mode 100644
index f2c635c..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXTrxLog.java
+++ /dev/null
@@ -1,379 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * Logging table for all DB create and update queries
- *
- */
-
-import java.util.*;
-
-import com.xasecure.common.*;
-import com.xasecure.common.view.*;
-
-import com.xasecure.common.*;
-import com.xasecure.json.JsonDateSerializer;
-
-import com.xasecure.view.*;
-
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@JsonIgnoreProperties(ignoreUnknown=true)
-@XmlRootElement
-public class VXTrxLog extends VXDataObject implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- /**
- * Name of the class to which the object id belongs to
- * This attribute is of type enum CommonEnums::ClassTypes
- */
- protected int objectClassType = XAConstants.CLASS_TYPE_NONE;
- /**
- * Id of the object to which this notes refers to
- */
- protected Long objectId;
- /**
- * Object Id of the parent object
- */
- protected Long parentObjectId;
- /**
- * Object Class Type of the parent object
- */
- protected int parentObjectClassType;
- /**
- * Name of the parent object name that was changed
- */
- protected String parentObjectName;
- /**
- * Name of the object name that was changed
- */
- protected String objectName;
- /**
- * Name of the attribute that was changed
- */
- protected String attributeName;
- /**
- * Previous value
- */
- protected String previousValue;
- /**
- * New value
- */
- protected String newValue;
- /**
- * Transaction id
- */
- protected String transactionId;
- /**
- * Action of the transaction
- */
- protected String action;
- /**
- * Session Id
- */
- protected String sessionId;
- /**
- * Request Id
- */
- protected String requestId;
- /**
- * Session Type
- */
- protected String sessionType;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VXTrxLog ( ) {
- objectClassType = XAConstants.CLASS_TYPE_NONE;
- }
-
- /**
- * This method sets the value to the member attribute <b>objectClassType</b>.
- * You cannot set null to the attribute.
- * @param objectClassType Value to set member attribute <b>objectClassType</b>
- */
- public void setObjectClassType( int objectClassType ) {
- this.objectClassType = objectClassType;
- }
-
- /**
- * Returns the value for the member attribute <b>objectClassType</b>
- * @return int - value of member attribute <b>objectClassType</b>.
- */
- public int getObjectClassType( ) {
- return this.objectClassType;
- }
-
- /**
- * This method sets the value to the member attribute <b>objectId</b>.
- * You cannot set null to the attribute.
- * @param objectId Value to set member attribute <b>objectId</b>
- */
- public void setObjectId( Long objectId ) {
- this.objectId = objectId;
- }
-
- /**
- * Returns the value for the member attribute <b>objectId</b>
- * @return Long - value of member attribute <b>objectId</b>.
- */
- public Long getObjectId( ) {
- return this.objectId;
- }
-
- /**
- * This method sets the value to the member attribute <b>parentObjectId</b>.
- * You cannot set null to the attribute.
- * @param parentObjectId Value to set member attribute <b>parentObjectId</b>
- */
- public void setParentObjectId( Long parentObjectId ) {
- this.parentObjectId = parentObjectId;
- }
-
- /**
- * Returns the value for the member attribute <b>parentObjectId</b>
- * @return Long - value of member attribute <b>parentObjectId</b>.
- */
- public Long getParentObjectId( ) {
- return this.parentObjectId;
- }
-
- /**
- * This method sets the value to the member attribute <b>parentObjectClassType</b>.
- * You cannot set null to the attribute.
- * @param parentObjectClassType Value to set member attribute <b>parentObjectClassType</b>
- */
- public void setParentObjectClassType( int parentObjectClassType ) {
- this.parentObjectClassType = parentObjectClassType;
- }
-
- /**
- * Returns the value for the member attribute <b>parentObjectClassType</b>
- * @return int - value of member attribute <b>parentObjectClassType</b>.
- */
- public int getParentObjectClassType( ) {
- return this.parentObjectClassType;
- }
-
- /**
- * This method sets the value to the member attribute <b>parentObjectName</b>.
- * You cannot set null to the attribute.
- * @param parentObjectName Value to set member attribute <b>parentObjectName</b>
- */
- public void setParentObjectName( String parentObjectName ) {
- this.parentObjectName = parentObjectName;
- }
-
- /**
- * Returns the value for the member attribute <b>parentObjectName</b>
- * @return String - value of member attribute <b>parentObjectName</b>.
- */
- public String getParentObjectName( ) {
- return this.parentObjectName;
- }
-
- /**
- * This method sets the value to the member attribute <b>objectName</b>.
- * You cannot set null to the attribute.
- * @param objectName Value to set member attribute <b>objectName</b>
- */
- public void setObjectName( String objectName ) {
- this.objectName = objectName;
- }
-
- /**
- * Returns the value for the member attribute <b>objectName</b>
- * @return String - value of member attribute <b>objectName</b>.
- */
- public String getObjectName( ) {
- return this.objectName;
- }
-
- /**
- * This method sets the value to the member attribute <b>attributeName</b>.
- * You cannot set null to the attribute.
- * @param attributeName Value to set member attribute <b>attributeName</b>
- */
- public void setAttributeName( String attributeName ) {
- this.attributeName = attributeName;
- }
-
- /**
- * Returns the value for the member attribute <b>attributeName</b>
- * @return String - value of member attribute <b>attributeName</b>.
- */
- public String getAttributeName( ) {
- return this.attributeName;
- }
-
- /**
- * This method sets the value to the member attribute <b>previousValue</b>.
- * You cannot set null to the attribute.
- * @param previousValue Value to set member attribute <b>previousValue</b>
- */
- public void setPreviousValue( String previousValue ) {
- this.previousValue = previousValue;
- }
-
- /**
- * Returns the value for the member attribute <b>previousValue</b>
- * @return String - value of member attribute <b>previousValue</b>.
- */
- public String getPreviousValue( ) {
- return this.previousValue;
- }
-
- /**
- * This method sets the value to the member attribute <b>newValue</b>.
- * You cannot set null to the attribute.
- * @param newValue Value to set member attribute <b>newValue</b>
- */
- public void setNewValue( String newValue ) {
- this.newValue = newValue;
- }
-
- /**
- * Returns the value for the member attribute <b>newValue</b>
- * @return String - value of member attribute <b>newValue</b>.
- */
- public String getNewValue( ) {
- return this.newValue;
- }
-
- /**
- * This method sets the value to the member attribute <b>transactionId</b>.
- * You cannot set null to the attribute.
- * @param transactionId Value to set member attribute <b>transactionId</b>
- */
- public void setTransactionId( String transactionId ) {
- this.transactionId = transactionId;
- }
-
- /**
- * Returns the value for the member attribute <b>transactionId</b>
- * @return String - value of member attribute <b>transactionId</b>.
- */
- public String getTransactionId( ) {
- return this.transactionId;
- }
-
- /**
- * This method sets the value to the member attribute <b>action</b>.
- * You cannot set null to the attribute.
- * @param action Value to set member attribute <b>action</b>
- */
- public void setAction( String action ) {
- this.action = action;
- }
-
- /**
- * Returns the value for the member attribute <b>action</b>
- * @return String - value of member attribute <b>action</b>.
- */
- public String getAction( ) {
- return this.action;
- }
-
- /**
- * This method sets the value to the member attribute <b>sessionId</b>.
- * You cannot set null to the attribute.
- * @param sessionId Value to set member attribute <b>sessionId</b>
- */
- public void setSessionId( String sessionId ) {
- this.sessionId = sessionId;
- }
-
- /**
- * Returns the value for the member attribute <b>sessionId</b>
- * @return String - value of member attribute <b>sessionId</b>.
- */
- public String getSessionId( ) {
- return this.sessionId;
- }
-
- /**
- * This method sets the value to the member attribute <b>requestId</b>.
- * You cannot set null to the attribute.
- * @param requestId Value to set member attribute <b>requestId</b>
- */
- public void setRequestId( String requestId ) {
- this.requestId = requestId;
- }
-
- /**
- * Returns the value for the member attribute <b>requestId</b>
- * @return String - value of member attribute <b>requestId</b>.
- */
- public String getRequestId( ) {
- return this.requestId;
- }
-
- /**
- * This method sets the value to the member attribute <b>sessionType</b>.
- * You cannot set null to the attribute.
- * @param sessionType Value to set member attribute <b>sessionType</b>
- */
- public void setSessionType( String sessionType ) {
- this.sessionType = sessionType;
- }
-
- /**
- * Returns the value for the member attribute <b>sessionType</b>
- * @return String - value of member attribute <b>sessionType</b>.
- */
- public String getSessionType( ) {
- return this.sessionType;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- public String toString( ) {
- String str = "VXTrxLog={";
- str += super.toString();
- str += "objectClassType={" + objectClassType + "} ";
- str += "objectId={" + objectId + "} ";
- str += "parentObjectId={" + parentObjectId + "} ";
- str += "parentObjectClassType={" + parentObjectClassType + "} ";
- str += "parentObjectName={" + parentObjectName + "} ";
- str += "objectName={" + objectName + "} ";
- str += "attributeName={" + attributeName + "} ";
- str += "previousValue={" + previousValue + "} ";
- str += "newValue={" + newValue + "} ";
- str += "transactionId={" + transactionId + "} ";
- str += "action={" + action + "} ";
- str += "sessionId={" + sessionId + "} ";
- str += "requestId={" + requestId + "} ";
- str += "sessionType={" + sessionType + "} ";
- str += "}";
- return str;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXTrxLogList.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXTrxLogList.java b/security-admin/src/main/java/com/xasecure/view/VXTrxLogList.java
deleted file mode 100644
index 84be7a9..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXTrxLogList.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-import java.util.*;
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-import com.xasecure.common.view.*;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.FIELD)
-public class VXTrxLogList extends VList {
- private static final long serialVersionUID = 1L;
- List<VXTrxLog> vXTrxLogs = new ArrayList<VXTrxLog>();
-
- public VXTrxLogList() {
- super();
- }
-
- public VXTrxLogList(List<VXTrxLog> objList) {
- super(objList);
- this.vXTrxLogs = objList;
- }
-
- /**
- * @return the vXTrxLogs
- */
- public List<VXTrxLog> getVXTrxLogs() {
- return vXTrxLogs;
- }
-
- /**
- * @param vXTrxLogs
- * the vXTrxLogs to set
- */
- public void setVXTrxLogs(List<VXTrxLog> vXTrxLogs) {
- this.vXTrxLogs = vXTrxLogs;
- }
-
- @Override
- public int getListSize() {
- if (vXTrxLogs != null) {
- return vXTrxLogs.size();
- }
- return 0;
- }
-
- @Override
- public List<VXTrxLog> getList() {
- return vXTrxLogs;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXUser.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXUser.java b/security-admin/src/main/java/com/xasecure/view/VXUser.java
deleted file mode 100644
index 3606bc4..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXUser.java
+++ /dev/null
@@ -1,302 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * User
- *
- */
-
-import java.util.*;
-
-import com.xasecure.common.*;
-import com.xasecure.common.view.*;
-import com.xasecure.common.*;
-import com.xasecure.json.JsonDateSerializer;
-import com.xasecure.view.*;
-
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@JsonIgnoreProperties(ignoreUnknown=true)
-@XmlRootElement
-public class VXUser extends VXDataObject implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- /**
- * Name
- */
- protected String name;
- /**
- * First Name
- */
- protected String firstName;
- /**
- * Last Name
- */
- protected String lastName;
- /**
- * Email address
- */
- protected String emailAddress;
- /**
- * Password
- */
- protected String password;
- /**
- * Description
- */
- protected String description;
- /**
- * Id of the credential store
- */
- protected Long credStoreId;
- /**
- * List of group ids
- */
- protected Collection<Long> groupIdList;
- protected Collection<String> groupNameList;
-
- protected int status;
- protected int userSource;
- /**
- * List of roles for this user
- */
- protected Collection<String> userRoleList;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VXUser ( ) {
- }
-
- /**
- * This method sets the value to the member attribute <b>name</b>.
- * You cannot set null to the attribute.
- * @param name Value to set member attribute <b>name</b>
- */
- public void setName( String name ) {
- this.name = name;
- }
-
- /**
- * Returns the value for the member attribute <b>name</b>
- * @return String - value of member attribute <b>name</b>.
- */
- public String getName( ) {
- return this.name;
- }
-
- /**
- * This method sets the value to the member attribute <b>firstName</b>.
- * You cannot set null to the attribute.
- * @param firstName Value to set member attribute <b>firstName</b>
- */
- public void setFirstName( String firstName ) {
- this.firstName = firstName;
- }
-
- /**
- * Returns the value for the member attribute <b>firstName</b>
- * @return String - value of member attribute <b>firstName</b>.
- */
- public String getFirstName( ) {
- return this.firstName;
- }
-
- /**
- * This method sets the value to the member attribute <b>lastName</b>.
- * You cannot set null to the attribute.
- * @param lastName Value to set member attribute <b>lastName</b>
- */
- public void setLastName( String lastName ) {
- this.lastName = lastName;
- }
-
- /**
- * Returns the value for the member attribute <b>lastName</b>
- * @return String - value of member attribute <b>lastName</b>.
- */
- public String getLastName( ) {
- return this.lastName;
- }
-
- /**
- * This method sets the value to the member attribute <b>emailAddress</b>.
- * You cannot set null to the attribute.
- * @param emailAddress Value to set member attribute <b>emailAddress</b>
- */
- public void setEmailAddress( String emailAddress ) {
- this.emailAddress = emailAddress;
- }
-
- /**
- * Returns the value for the member attribute <b>emailAddress</b>
- * @return String - value of member attribute <b>emailAddress</b>.
- */
- public String getEmailAddress( ) {
- return this.emailAddress;
- }
-
- /**
- * This method sets the value to the member attribute <b>password</b>.
- * You cannot set null to the attribute.
- * @param password Value to set member attribute <b>password</b>
- */
- public void setPassword( String password ) {
- this.password = password;
- }
-
- /**
- * Returns the value for the member attribute <b>password</b>
- * @return String - value of member attribute <b>password</b>.
- */
- public String getPassword( ) {
- return this.password;
- }
-
- /**
- * This method sets the value to the member attribute <b>description</b>.
- * You cannot set null to the attribute.
- * @param description Value to set member attribute <b>description</b>
- */
- public void setDescription( String description ) {
- this.description = description;
- }
-
- /**
- * Returns the value for the member attribute <b>description</b>
- * @return String - value of member attribute <b>description</b>.
- */
- public String getDescription( ) {
- return this.description;
- }
-
- /**
- * This method sets the value to the member attribute <b>credStoreId</b>.
- * You cannot set null to the attribute.
- * @param credStoreId Value to set member attribute <b>credStoreId</b>
- */
- public void setCredStoreId( Long credStoreId ) {
- this.credStoreId = credStoreId;
- }
-
- /**
- * Returns the value for the member attribute <b>credStoreId</b>
- * @return Long - value of member attribute <b>credStoreId</b>.
- */
- public Long getCredStoreId( ) {
- return this.credStoreId;
- }
-
- /**
- * This method sets the value to the member attribute <b>groupIdList</b>.
- * You cannot set null to the attribute.
- * @param groupIdList Value to set member attribute <b>groupIdList</b>
- */
- public void setGroupIdList( Collection<Long> groupIdList ) {
- this.groupIdList = groupIdList;
- }
-
- /**
- * Returns the value for the member attribute <b>groupIdList</b>
- * @return Collection<Long> - value of member attribute <b>groupIdList</b>.
- */
- public Collection<Long> getGroupIdList( ) {
- return this.groupIdList;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_XA_USER;
- }
-
-
- public int getStatus() {
- return status;
- }
-
- public void setStatus(int status) {
- this.status = status;
- }
-
-
-
- public int getUserSource() {
- return userSource;
- }
-
- public void setUserSource(int userSource) {
- this.userSource = userSource;
- }
-
- /**
- * This method sets the value to the member attribute <b>userRoleList</b>.
- * You cannot set null to the attribute.
- * @param userRoleList Value to set member attribute <b>userRoleList</b>
- */
- public void setUserRoleList( Collection<String> userRoleList ) {
- this.userRoleList = userRoleList;
- }
-
- /**
- * Returns the value for the member attribute <b>userRoleList</b>
- * @return Collection<String> - value of member attribute <b>userRoleList</b>.
- */
- public Collection<String> getUserRoleList( ) {
- return this.userRoleList;
- }
-
-
- public Collection<String> getGroupNameList() {
- return groupNameList;
- }
-
- public void setGroupNameList(Collection<String> groupNameList) {
- this.groupNameList = groupNameList;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- public String toString( ) {
- String str = "VXUser={";
- str += super.toString();
- str += "name={" + name + "} ";
- str += "firstName={" + firstName + "} ";
- str += "lastName={" + lastName + "} ";
- str += "emailAddress={" + emailAddress + "} ";
- str += "password={" + password + "} ";
- str += "description={" + description + "} ";
- str += "credStoreId={" + credStoreId + "} ";
- str += "groupIdList={" + groupIdList + "} ";
- str += "groupNameList={" + groupNameList + "} ";
- str += "}";
- return str;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXUserList.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXUserList.java b/security-admin/src/main/java/com/xasecure/view/VXUserList.java
deleted file mode 100644
index 0c429c8..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXUserList.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * List wrapper class for VXUser
- *
- */
-
-import java.util.*;
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-import com.xasecure.common.view.*;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.FIELD)
-public class VXUserList extends VList {
- private static final long serialVersionUID = 1L;
- List<VXUser> vXUsers = new ArrayList<VXUser>();
-
- public VXUserList() {
- super();
- }
-
- public VXUserList(List<VXUser> objList) {
- super(objList);
- this.vXUsers = objList;
- }
-
- /**
- * @return the vXUsers
- */
- public List<VXUser> getVXUsers() {
- return vXUsers;
- }
-
- /**
- * @param vXUsers
- * the vXUsers to set
- */
- public void setVXUsers(List<VXUser> vXUsers) {
- this.vXUsers = vXUsers;
- }
-
- @Override
- public int getListSize() {
- if (vXUsers != null) {
- return vXUsers.size();
- }
- return 0;
- }
-
- @Override
- public List<VXUser> getList() {
- return vXUsers;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/authentication/unix/jaas/RoleUserAuthorityGranter.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/authentication/unix/jaas/RoleUserAuthorityGranter.java b/security-admin/src/main/java/org/apache/ranger/authentication/unix/jaas/RoleUserAuthorityGranter.java
new file mode 100644
index 0000000..19d08f4
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/authentication/unix/jaas/RoleUserAuthorityGranter.java
@@ -0,0 +1,41 @@
+/*
+ * 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.authentication.unix.jaas;
+
+import java.security.Principal;
+import java.util.Collections;
+import java.util.Set;
+
+import org.apache.ranger.authentication.unix.jaas.UnixGroupPrincipal;
+import org.springframework.security.authentication.jaas.AuthorityGranter;
+
+public class RoleUserAuthorityGranter implements AuthorityGranter {
+
+ @Override
+ public Set<String> grant(Principal principal) {
+ if (principal instanceof UnixGroupPrincipal) {
+ Collections.singleton(principal.getName());
+ }
+ else {
+ Collections.singleton("ROLE_USER");
+ }
+ return null;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/biz/AssetConnectionMgr.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/AssetConnectionMgr.java b/security-admin/src/main/java/org/apache/ranger/biz/AssetConnectionMgr.java
new file mode 100644
index 0000000..c481e65
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/biz/AssetConnectionMgr.java
@@ -0,0 +1,424 @@
+/*
+ * 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.biz;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.common.AppConstants;
+import org.apache.ranger.common.JSONUtil;
+import org.apache.ranger.common.StringUtil;
+import org.apache.ranger.common.TimedEventUtil;
+import org.apache.ranger.db.XADaoManager;
+import org.apache.ranger.entity.XXAsset;
+import org.apache.ranger.hadoop.client.HadoopFS;
+import org.apache.ranger.hbase.client.HBaseClient;
+import org.apache.ranger.hive.client.HiveClient;
+import org.apache.ranger.knox.client.KnoxClient;
+import org.apache.ranger.service.XAssetService;
+import org.apache.ranger.storm.client.StormClient;
+import org.apache.ranger.view.VXAsset;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Component;
+
+@Component
+@Scope("singleton")
+public class AssetConnectionMgr {
+
+ private static Logger logger = Logger.getLogger(AssetConnectionMgr.class);
+
+ protected HashMap<String, HadoopFS> hadoopConnectionCache;
+ protected HashMap<String, HiveClient> hiveConnectionCache;
+ protected HashMap<String, HBaseClient> hbaseConnectionCache;
+
+ protected HashMap<String, Boolean> repoConnectStatusMap;
+
+ @Autowired
+ protected JSONUtil jsonUtil;
+
+ @Autowired
+ protected StringUtil stringUtil;
+
+ @Autowired
+ protected XADaoManager xADaoManager;
+
+ @Autowired
+ XAssetService xAssetService;
+
+ public AssetConnectionMgr(){
+ hadoopConnectionCache = new HashMap<String, HadoopFS>();
+ hiveConnectionCache = new HashMap<String, HiveClient>();
+ hbaseConnectionCache = new HashMap<String, HBaseClient>();
+ repoConnectStatusMap = new HashMap<String, Boolean>();
+ }
+
+ public HadoopFS getHadoopConnection(final String dataSourceName) {
+ HadoopFS hadoopFS = null;
+ XXAsset asset = xADaoManager.getXXAsset().findByAssetName(dataSourceName);
+ if (asset != null) {
+ // get it from the cache
+ synchronized (hadoopConnectionCache) {
+ hadoopFS = hadoopConnectionCache.get(asset.getName());
+ if (hadoopFS == null) {
+ // if it doesn't exist in cache then create the connection
+ String config = asset.getConfig();
+ if(!stringUtil.isEmpty(config)){
+ config=xAssetService.getConfigWithDecryptedPassword(config);
+ }
+ // FIXME remove this once we start using putting config for
+ // default asset "hadoopdev" (should come from properties)
+ if (stringUtil.isEmpty(config)
+ && asset.getName().equals("hadoopdev")) {
+
+ final Callable<HadoopFS> connectHDFS = new Callable<HadoopFS>() {
+ @Override
+ public HadoopFS call() throws Exception {
+ return new HadoopFS(dataSourceName);
+ }
+ };
+
+ try {
+ hadoopFS = TimedEventUtil.timedTask(connectHDFS, 10, TimeUnit.SECONDS);
+ } catch(Exception e){
+ logger.error("Error establishing connection for HDFS repository : "
+ + dataSourceName, e);
+ }
+
+ } else if (!stringUtil.isEmpty(config)) {
+ final HashMap<String, String> configMap = (HashMap<String, String>) jsonUtil
+ .jsonToMap(config);
+ final String assetName = asset.getName();
+
+ final Callable<HadoopFS> connectHDFS = new Callable<HadoopFS>() {
+ @Override
+ public HadoopFS call() throws Exception {
+ return new HadoopFS(assetName, configMap);
+ }
+ };
+
+ try {
+ hadoopFS = TimedEventUtil.timedTask(connectHDFS, 5, TimeUnit.SECONDS);
+ } catch(Exception e){
+ logger.error("Error establishing connection for HDFS repository : "
+ + dataSourceName + " using configuration : " +config, e);
+ }
+ // put it into the cache
+ } else {
+ logger.error("Connection Config not defined for asset :"
+ + asset.getName(), new Throwable());
+ }
+ hadoopConnectionCache.put(asset.getName(), hadoopFS);
+ repoConnectStatusMap.put(asset.getName(), true);
+ } else {
+ List<String> testConnect = hadoopFS.listFiles("/", "*");
+ if(testConnect == null){
+ hadoopConnectionCache.remove(dataSourceName);
+ hadoopFS = getHadoopConnection(dataSourceName);
+ }
+ }
+ }
+ } else {
+ logger.error("Asset not found with name "+dataSourceName, new Throwable());
+ }
+
+ return hadoopFS;
+ }
+
+ public HiveClient getHiveConnection(final String dataSourceName) {
+ HiveClient hiveClient = null;
+ XXAsset asset = xADaoManager.getXXAsset().findByAssetName(dataSourceName);
+ if (asset != null) {
+ // get it from the cache
+ synchronized (hiveConnectionCache) {
+ hiveClient = hiveConnectionCache.get(asset.getName());
+ if (hiveClient == null) {
+ String config = asset.getConfig();
+ if (!stringUtil.isEmpty(config)) {
+ config=xAssetService.getConfigWithDecryptedPassword(config);
+ final HashMap<String, String> configMap = (HashMap<String, String>) jsonUtil
+ .jsonToMap(config);
+
+ final Callable<HiveClient> connectHive = new Callable<HiveClient>() {
+ @Override
+ public HiveClient call() throws Exception {
+ return new HiveClient(dataSourceName, configMap);
+ }
+ };
+ try {
+ hiveClient = TimedEventUtil.timedTask(connectHive, 5, TimeUnit.SECONDS);
+ } catch(Exception e){
+ logger.error("Error connecting hive repository : "+
+ dataSourceName +" using config : "+ config, e);
+ }
+ hiveConnectionCache.put(asset.getName(), hiveClient);
+ repoConnectStatusMap.put(asset.getName(), true);
+ } else {
+ logger.error("Connection Config not defined for asset :"
+ + asset.getName(), new Throwable());
+ }
+ } else {
+ try {
+ List<String> testConnect = hiveClient.getDatabaseList("*");
+ } catch(Exception e) {
+ hiveConnectionCache.remove(dataSourceName);
+ hiveClient = getHiveConnection(dataSourceName);
+ }
+ }
+ }
+ } else {
+ logger.error("Asset not found with name "+dataSourceName, new Throwable());
+ }
+ return hiveClient;
+ }
+
+ public KnoxClient getKnoxClient(String dataSourceName) {
+ KnoxClient knoxClient = null;
+ logger.debug("Getting knoxClient for datasource: " + dataSourceName);
+ XXAsset asset = xADaoManager.getXXAsset().findByAssetName(dataSourceName);
+ if (asset == null) {
+ logger.error("Asset not found with name " + dataSourceName, new Throwable());
+ } else {
+ knoxClient = getKnoxClient(asset);
+ }
+ return knoxClient;
+ }
+
+ public KnoxClient getKnoxClient(XXAsset asset) {
+ KnoxClient knoxClient = null;
+ if (asset == null) {
+ logger.error("Asset is null", new Throwable());
+ } else {
+ String config = asset.getConfig();
+ if(!stringUtil.isEmpty(config)){
+ config=xAssetService.getConfigWithDecryptedPassword(config);
+ }
+ knoxClient = getKnoxClientByConfig(config);
+ }
+ return knoxClient;
+ }
+
+ public KnoxClient getKnoxClientByConfig(String config) {
+ KnoxClient knoxClient = null;
+ if (config == null || config.trim().isEmpty()) {
+ logger.error("Connection Config is empty");
+
+ } else {
+ final HashMap<String, String> configMap = (HashMap<String, String>) jsonUtil
+ .jsonToMap(config);
+ String knoxUrl = configMap.get("knox.url");
+ String knoxAdminUser = configMap.get("username");
+ String knoxAdminPassword = configMap.get("password");
+ knoxClient = new KnoxClient(knoxUrl, knoxAdminUser, knoxAdminPassword);
+ }
+ return knoxClient;
+ }
+
+ public KnoxClient getKnoxClient(String dataSourceName,
+ Map<String, String> configMap) {
+ KnoxClient knoxClient = null;
+ logger.debug("Getting knoxClient for datasource: " + dataSourceName +
+ "configMap: " + configMap);
+ if (configMap == null || configMap.isEmpty()) {
+ logger.error("Connection ConfigMap is empty");
+ } else {
+ String knoxUrl = configMap.get("knox.url");
+ String knoxAdminUser = configMap.get("username");
+ String knoxAdminPassword = configMap.get("password");
+ knoxClient = new KnoxClient(knoxUrl, knoxAdminUser, knoxAdminPassword);
+ }
+ return knoxClient;
+ }
+
+
+ public static KnoxClient getKnoxClient(final String knoxUrl, String knoxAdminUser, String knoxAdminPassword) {
+ KnoxClient knoxClient = null;
+ if (knoxUrl == null || knoxUrl.isEmpty()) {
+ logger.error("Can not create KnoxClient: knoxUrl is empty");
+ } else if (knoxAdminUser == null || knoxAdminUser.isEmpty()) {
+ logger.error("Can not create KnoxClient: knoxAdminUser is empty");
+ } else if (knoxAdminPassword == null || knoxAdminPassword.isEmpty()) {
+ logger.error("Can not create KnoxClient: knoxAdminPassword is empty");
+ } else {
+ knoxClient = new KnoxClient(knoxUrl, knoxAdminUser, knoxAdminPassword);
+ }
+ return knoxClient;
+ }
+
+ public HBaseClient getHBaseConnection(final String dataSourceName) {
+ HBaseClient client = null;
+ XXAsset asset = xADaoManager.getXXAsset().findByAssetName(
+ dataSourceName);
+ if (asset != null) {
+ // get it from the cache
+ synchronized (hbaseConnectionCache) {
+ client = hbaseConnectionCache.get(asset.getName());
+ if (client == null) {
+ // if it doesn't exist in cache then create the connection
+ String config = asset.getConfig();
+ if(!stringUtil.isEmpty(config)){
+ config=xAssetService.getConfigWithDecryptedPassword(config);
+ }
+ // FIXME remove this once we start using putting config for
+ // default asset "dev-hive" (should come from properties)
+ if (stringUtil.isEmpty(config)
+ && asset.getName().equals("hbase")) {
+
+ final Callable<HBaseClient> connectHBase = new Callable<HBaseClient>() {
+ @Override
+
+ public HBaseClient call() throws Exception {
+ HBaseClient hBaseClient=null;
+ if(dataSourceName!=null){
+ try{
+ hBaseClient=new HBaseClient(dataSourceName);
+ }catch(Exception ex){
+ logger.error("Error connecting HBase repository : ", ex);
+ }
+ }
+ return hBaseClient;
+ }
+
+ };
+
+ try {
+ if(connectHBase!=null){
+ client = TimedEventUtil.timedTask(connectHBase, 5, TimeUnit.SECONDS);
+ }
+ } catch(Exception e){
+ logger.error("Error connecting HBase repository : " + dataSourceName);
+ }
+ } else if (!stringUtil.isEmpty(config)) {
+ final HashMap<String, String> configMap = (HashMap<String, String>) jsonUtil
+ .jsonToMap(config);
+
+ final Callable<HBaseClient> connectHBase = new Callable<HBaseClient>() {
+ @Override
+ public HBaseClient call() throws Exception {
+ HBaseClient hBaseClient=null;
+ if(dataSourceName!=null && configMap!=null){
+ try{
+ hBaseClient=new HBaseClient(dataSourceName,configMap);
+ }catch(Exception ex){
+ logger.error("Error connecting HBase repository : ", ex);
+ }
+ }
+ return hBaseClient;
+ }
+ };
+
+ try {
+ if(connectHBase!=null){
+ client = TimedEventUtil.timedTask(connectHBase, 5, TimeUnit.SECONDS);
+ }
+ } catch(Exception e){
+ logger.error("Error connecting HBase repository : "+
+ dataSourceName +" using config : "+ config);
+ }
+
+ } else {
+ logger.error(
+ "Connection Config not defined for asset :"
+ + asset.getName(), new Throwable());
+ }
+ if(client!=null){
+ hbaseConnectionCache.put(asset.getName(), client);
+ }
+ } else {
+ List<String> testConnect = client.getTableList(".\\*");
+ if(testConnect == null){
+ hbaseConnectionCache.remove(dataSourceName);
+ client = getHBaseConnection(dataSourceName);
+ }
+ }
+ repoConnectStatusMap.put(asset.getName(), true);
+ }
+ } else {
+ logger.error("Asset not found with name " + dataSourceName,
+ new Throwable());
+ }
+
+ return client;
+ }
+
+ public boolean destroyConnection(VXAsset asset) {
+ boolean result = false;
+ if (asset != null) {
+ if(asset.getAssetType() == AppConstants.ASSET_HDFS) {
+ synchronized (hadoopConnectionCache) {
+
+ @SuppressWarnings("unused")
+ HadoopFS hadoopFS = hadoopConnectionCache.get(asset.getName());
+ // TODO need a way to close the connection
+ hadoopConnectionCache.remove(asset.getName());
+ repoConnectStatusMap.remove(asset.getName());
+
+ }
+ } else if(asset.getAssetType() == AppConstants.ASSET_HIVE) {
+ synchronized (hadoopConnectionCache) {
+
+ HiveClient hiveClient = hiveConnectionCache.get(asset.getName());
+ if(hiveClient != null) {
+ hiveClient.close();
+ }
+ hadoopConnectionCache.remove(asset.getName());
+ repoConnectStatusMap.remove(asset.getName());
+
+ }
+ } else if (asset.getAssetType() == AppConstants.ASSET_HBASE) {
+ synchronized (hbaseConnectionCache) {
+ @SuppressWarnings("unused")
+ HBaseClient hBaseClient = hbaseConnectionCache.get(asset
+ .getName());
+ // TODO need a way to close the connection
+ hbaseConnectionCache.remove(asset.getName());
+ repoConnectStatusMap.remove(asset.getName());
+
+ }
+ }
+ result = true;
+ }
+ return result;
+ }
+
+ public HadoopFS resetHadoopConnection(final String dataSourceName){
+ hadoopConnectionCache.remove(dataSourceName);
+ return getHadoopConnection(dataSourceName);
+ }
+
+ public static StormClient getStormClient(final String stormUIURL, String userName, String password) {
+ StormClient stormClient = null;
+ if (stormUIURL == null || stormUIURL.isEmpty()) {
+ logger.error("Can not create KnoxClient: stormUIURL is empty");
+ } else if (userName == null || userName.isEmpty()) {
+ logger.error("Can not create KnoxClient: knoxAdminUser is empty");
+ } else if (password == null || password.isEmpty()) {
+ logger.error("Can not create KnoxClient: knoxAdminPassword is empty");
+ } else {
+ stormClient = new StormClient(stormUIURL, userName, password);
+ }
+ return stormClient;
+ }
+
+}
[51/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
RANGER-194: Rename packages from xasecure to apache ranger
Project: http://git-wip-us.apache.org/repos/asf/incubator-ranger/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-ranger/commit/413fcb68
Tree: http://git-wip-us.apache.org/repos/asf/incubator-ranger/tree/413fcb68
Diff: http://git-wip-us.apache.org/repos/asf/incubator-ranger/diff/413fcb68
Branch: refs/heads/master
Commit: 413fcb68f0368b35b2b0bc3c71bb8e71af6704ed
Parents: 830fe61
Author: Alok Lal <al...@hortonworks.com>
Authored: Thu Dec 11 17:22:43 2014 -0800
Committer: Madhan Neethiraj <ma...@apache.org>
Committed: Thu Dec 11 17:22:43 2014 -0800
----------------------------------------------------------------------
.../java/com/xasecure/audit/dao/BaseDao.java | 234 --
.../java/com/xasecure/audit/dao/DaoManager.java | 56 -
.../com/xasecure/audit/dao/DaoManagerBase.java | 80 -
.../audit/dao/XAHBaseAuditEventDao.java | 29 -
.../xasecure/audit/dao/XAHdfsAuditEventDao.java | 29 -
.../xasecure/audit/dao/XAHiveAuditEventDao.java | 29 -
.../xasecure/audit/dao/XAKnoxAuditEventDao.java | 29 -
.../audit/dao/XAStormAuditEventDao.java | 29 -
.../xasecure/audit/entity/XXBaseAuditEvent.java | 228 --
.../audit/entity/XXBaseAuditEvent_.java | 46 -
.../audit/entity/XXHBaseAuditEvent.java | 84 -
.../audit/entity/XXHBaseAuditEvent_.java | 32 -
.../xasecure/audit/entity/XXHdfsAuditEvent.java | 75 -
.../audit/entity/XXHdfsAuditEvent_.java | 31 -
.../xasecure/audit/entity/XXHiveAuditEvent.java | 86 -
.../audit/entity/XXHiveAuditEvent_.java | 32 -
.../xasecure/audit/entity/XXKnoxAuditEvent.java | 82 -
.../audit/entity/XXStormAuditEvent.java | 82 -
.../xasecure/audit/model/AuditEventBase.java | 378 --
.../audit/model/EnumRepositoryType.java | 37 -
.../xasecure/audit/model/HBaseAuditEvent.java | 128 -
.../xasecure/audit/model/HdfsAuditEvent.java | 107 -
.../xasecure/audit/model/HiveAuditEvent.java | 126 -
.../xasecure/audit/model/KnoxAuditEvent.java | 97 -
.../xasecure/audit/model/StormAuditEvent.java | 97 -
.../audit/provider/AsyncAuditProvider.java | 272 --
.../xasecure/audit/provider/AuditProvider.java | 36 -
.../audit/provider/AuditProviderFactory.java | 243 --
.../audit/provider/BaseAuditProvider.java | 173 -
.../audit/provider/BufferedAuditProvider.java | 93 -
.../audit/provider/DbAuditProvider.java | 356 --
.../xasecure/audit/provider/DebugTracer.java | 28 -
.../audit/provider/DummyAuditProvider.java | 65 -
.../audit/provider/LocalFileLogBuffer.java | 687 ----
.../audit/provider/Log4jAuditProvider.java | 100 -
.../xasecure/audit/provider/Log4jTracer.java | 59 -
.../com/xasecure/audit/provider/LogBuffer.java | 32 -
.../xasecure/audit/provider/LogDestination.java | 34 -
.../com/xasecure/audit/provider/MiscUtil.java | 250 --
.../audit/provider/MultiDestAuditProvider.java | 162 -
.../audit/provider/hdfs/HdfsAuditProvider.java | 93 -
.../audit/provider/hdfs/HdfsLogDestination.java | 452 ---
.../com/xasecure/audit/test/TestEvents.java | 153 -
.../org/apache/ranger/audit/dao/BaseDao.java | 234 ++
.../org/apache/ranger/audit/dao/DaoManager.java | 56 +
.../apache/ranger/audit/dao/DaoManagerBase.java | 80 +
.../audit/dao/RangerHBaseAuditEventDao.java | 29 +
.../audit/dao/RangerHdfsAuditEventDao.java | 29 +
.../audit/dao/RangerHiveAuditEventDao.java | 29 +
.../audit/dao/RangerKnoxAuditEventDao.java | 29 +
.../audit/dao/RangerStormAuditEventDao.java | 29 +
.../ranger/audit/entity/XXBaseAuditEvent.java | 228 ++
.../ranger/audit/entity/XXBaseAuditEvent_.java | 48 +
.../ranger/audit/entity/XXHBaseAuditEvent.java | 84 +
.../ranger/audit/entity/XXHBaseAuditEvent_.java | 32 +
.../ranger/audit/entity/XXHdfsAuditEvent.java | 75 +
.../ranger/audit/entity/XXHdfsAuditEvent_.java | 31 +
.../ranger/audit/entity/XXHiveAuditEvent.java | 86 +
.../ranger/audit/entity/XXHiveAuditEvent_.java | 32 +
.../ranger/audit/entity/XXKnoxAuditEvent.java | 82 +
.../ranger/audit/entity/XXStormAuditEvent.java | 82 +
.../ranger/audit/model/AuditEventBase.java | 378 ++
.../ranger/audit/model/EnumRepositoryType.java | 37 +
.../ranger/audit/model/HBaseAuditEvent.java | 128 +
.../ranger/audit/model/HdfsAuditEvent.java | 107 +
.../ranger/audit/model/HiveAuditEvent.java | 127 +
.../ranger/audit/model/KnoxAuditEvent.java | 98 +
.../ranger/audit/model/StormAuditEvent.java | 98 +
.../audit/provider/AsyncAuditProvider.java | 271 ++
.../ranger/audit/provider/AuditProvider.java | 36 +
.../audit/provider/AuditProviderFactory.java | 242 ++
.../audit/provider/BaseAuditProvider.java | 172 +
.../audit/provider/BufferedAuditProvider.java | 93 +
.../ranger/audit/provider/DbAuditProvider.java | 355 ++
.../ranger/audit/provider/DebugTracer.java | 28 +
.../audit/provider/DummyAuditProvider.java | 65 +
.../audit/provider/LocalFileLogBuffer.java | 687 ++++
.../audit/provider/Log4jAuditProvider.java | 100 +
.../ranger/audit/provider/Log4jTracer.java | 59 +
.../apache/ranger/audit/provider/LogBuffer.java | 32 +
.../ranger/audit/provider/LogDestination.java | 34 +
.../apache/ranger/audit/provider/MiscUtil.java | 250 ++
.../audit/provider/MultiDestAuditProvider.java | 161 +
.../audit/provider/hdfs/HdfsAuditProvider.java | 92 +
.../audit/provider/hdfs/HdfsLogDestination.java | 451 +++
.../apache/ranger/audit/test/TestEvents.java | 152 +
.../src/main/resources/META-INF/persistence.xml | 12 +-
agents-common/conf/log4j.properties | 2 +-
agents-common/scripts/enable-agent.sh | 10 +-
.../xasecure/admin/client/XaAdminClient.java | 32 -
.../admin/client/XaAdminRESTClient.java | 390 ---
.../admin/client/datatype/GrantRevokeData.java | 273 --
.../admin/client/datatype/RESTResponse.java | 208 --
.../hadoop/config/XaSecureConfiguration.java | 165 -
.../constants/XaSecureHadoopConstants.java | 89 -
.../hadoop/log/HdfsFileAppender.java | 1376 --------
.../authorization/utils/StringUtil.java | 276 --
.../ranger/admin/client/RangerAdminClient.java | 32 +
.../admin/client/RangerAdminRESTClient.java | 389 +++
.../admin/client/datatype/GrantRevokeData.java | 272 ++
.../admin/client/datatype/RESTResponse.java | 208 ++
.../hadoop/config/RangerConfiguration.java | 164 +
.../hadoop/constants/RangerHadoopConstants.java | 89 +
.../hadoop/log/HdfsFileAppender.java | 1376 ++++++++
.../ranger/authorization/utils/StringUtil.java | 276 ++
.../.settings/org.eclipse.core.resources.prefs | 1 +
.../utils/XaSecureCredentialProvider.java | 84 -
.../hadoop/utils/RangerCredentialProvider.java | 84 +
.../utils/XaSecureCredentialProviderTest.java | 91 -
.../utils/RangerCredentialProviderTest.java | 92 +
.../com/xasecure/pdp/config/ConfigWatcher.java | 543 ---
.../pdp/config/Jersey2ConfigWatcher.java | 565 ---
.../pdp/config/Jersey2PolicyRefresher.java | 207 --
.../pdp/config/PolicyChangeListener.java | 26 -
.../xasecure/pdp/config/PolicyRefresher.java | 229 --
.../pdp/config/gson/ExcludeSerialization.java | 32 -
.../config/gson/PolicyExclusionStrategy.java | 37 -
.../pdp/constants/XaSecureConstants.java | 89 -
.../com/xasecure/pdp/hbase/HBaseAuthDB.java | 489 ---
.../com/xasecure/pdp/hbase/HBaseAuthRules.java | 135 -
.../com/xasecure/pdp/hbase/URLBasedAuthDB.java | 234 --
.../xasecure/pdp/hbase/XASecureAuthorizer.java | 108 -
.../xasecure/pdp/hdfs/AdminPolicyChecker.java | 183 -
.../com/xasecure/pdp/hdfs/URLBasedAuthDB.java | 480 ---
.../xasecure/pdp/hdfs/XASecureAuthorizer.java | 40 -
.../java/com/xasecure/pdp/hive/HiveAuthDB.java | 307 --
.../com/xasecure/pdp/hive/HiveAuthRule.java | 223 --
.../pdp/hive/HiveAuthorizationProviderBase.java | 65 -
.../com/xasecure/pdp/hive/URLBasedAuthDB.java | 222 --
.../xasecure/pdp/hive/XASecureAuthorizer.java | 48 -
.../com/xasecure/pdp/knox/URLBasedAuthDB.java | 453 ---
.../xasecure/pdp/knox/XASecureAuthorizer.java | 65 -
.../XASecurePDPKnoxDeploymentContributor.java | 73 -
.../pdp/knox/filter/XASecurePDPKnoxFilter.java | 215 --
.../java/com/xasecure/pdp/model/Policy.java | 325 --
.../com/xasecure/pdp/model/PolicyContainer.java | 55 -
.../com/xasecure/pdp/model/ResourcePath.java | 43 -
.../com/xasecure/pdp/model/RolePermission.java | 71 -
.../com/xasecure/pdp/storm/StormAuthRule.java | 137 -
.../com/xasecure/pdp/storm/URLBasedAuthDB.java | 177 -
.../xasecure/pdp/storm/XASecureAuthorizer.java | 62 -
.../com/xasecure/pdp/utils/XaSecureUtils.java | 49 -
.../apache/ranger/pdp/config/ConfigWatcher.java | 543 +++
.../ranger/pdp/config/Jersey2ConfigWatcher.java | 565 +++
.../pdp/config/Jersey2PolicyRefresher.java | 207 ++
.../ranger/pdp/config/PolicyChangeListener.java | 26 +
.../ranger/pdp/config/PolicyRefresher.java | 229 ++
.../pdp/config/gson/ExcludeSerialization.java | 32 +
.../config/gson/PolicyExclusionStrategy.java | 37 +
.../ranger/pdp/constants/RangerConstants.java | 89 +
.../apache/ranger/pdp/hbase/HBaseAuthDB.java | 488 +++
.../apache/ranger/pdp/hbase/HBaseAuthRules.java | 134 +
.../ranger/pdp/hbase/RangerAuthorizer.java | 107 +
.../apache/ranger/pdp/hbase/URLBasedAuthDB.java | 233 ++
.../ranger/pdp/hdfs/AdminPolicyChecker.java | 183 +
.../ranger/pdp/hdfs/RangerAuthorizer.java | 40 +
.../apache/ranger/pdp/hdfs/URLBasedAuthDB.java | 479 +++
.../org/apache/ranger/pdp/hive/HiveAuthDB.java | 306 ++
.../apache/ranger/pdp/hive/HiveAuthRule.java | 222 ++
.../pdp/hive/HiveAuthorizationProviderBase.java | 64 +
.../ranger/pdp/hive/RangerAuthorizer.java | 47 +
.../apache/ranger/pdp/hive/URLBasedAuthDB.java | 221 ++
.../ranger/pdp/knox/RangerAuthorizer.java | 64 +
.../apache/ranger/pdp/knox/URLBasedAuthDB.java | 452 +++
.../RangerPDPKnoxDeploymentContributor.java | 73 +
.../pdp/knox/filter/RangerPDPKnoxFilter.java | 214 ++
.../org/apache/ranger/pdp/model/Policy.java | 326 ++
.../ranger/pdp/model/PolicyContainer.java | 55 +
.../apache/ranger/pdp/model/ResourcePath.java | 43 +
.../apache/ranger/pdp/model/RolePermission.java | 71 +
.../ranger/pdp/storm/RangerAuthorizer.java | 61 +
.../apache/ranger/pdp/storm/StormAuthRule.java | 136 +
.../apache/ranger/pdp/storm/URLBasedAuthDB.java | 176 +
.../apache/ranger/pdp/utils/RangerUtils.java | 49 +
...gateway.deploy.ProviderDeploymentContributor | 2 +-
.../xasecure/pdp/hdfs/PolicyCacheStoreTest.java | 169 -
.../xasecure/pdp/hdfs/URLBasedAuthDBTest.java | 66 -
...asedAuthDB_IsAuditLogEnabledByACL_PTest.java | 340 --
.../xasecure/pdp/knox/URLBasedAuthDBTest.java | 956 ------
.../ranger/pdp/hdfs/PolicyCacheStoreTest.java | 170 +
.../ranger/pdp/hdfs/URLBasedAuthDBTest.java | 66 +
...asedAuthDB_IsAuditLogEnabledByACL_PTest.java | 340 ++
.../ranger/pdp/knox/URLBasedAuthDBTest.java | 956 ++++++
.../utils/install/PasswordGenerator.java | 141 -
.../utils/install/XmlConfigChanger.java | 494 ---
.../ranger/utils/install/PasswordGenerator.java | 141 +
.../ranger/utils/install/XmlConfigChanger.java | 494 +++
credentialbuilder/.gitignore | 1 +
.../credentialapi/CredentialReader.java | 87 -
.../com/hortonworks/credentialapi/buildks.java | 433 ---
.../ranger/credentialapi/CredentialReader.java | 87 +
.../apache/ranger/credentialapi/buildks.java | 433 +++
.../credentialapi/TestCredentialReader.java | 52 -
.../hortonworks/credentialapi/Testbuildks.java | 78 -
.../credentialapi/TestCredentialReader.java | 54 +
.../ranger/credentialapi/Testbuildks.java | 79 +
embededwebserver/scripts/start-ranger-admin.sh | 2 +-
embededwebserver/scripts/stop-ranger-admin.sh | 2 +-
.../xasecure/server/tomcat/EmbededServer.java | 240 --
.../server/tomcat/StopEmbededServer.java | 62 -
.../ranger/server/tomcat/EmbededServer.java | 240 ++
.../ranger/server/tomcat/StopEmbededServer.java | 62 +
.../.settings/org.eclipse.core.resources.prefs | 1 +
hbase-agent/conf/hbase-site-changes.cfg | 4 +-
.../conf/xasecure-hbase-security-changes.cfg | 2 +-
hbase-agent/conf/xasecure-hbase-security.xml | 2 +-
hbase-agent/disable-conf/hbase-site-changes.cfg | 4 +-
hbase-agent/scripts/install.sh | 2 +-
.../com/xasecure/authorization/hbase/Crypt.java | 85 -
.../hbase/HBaseAccessController.java | 40 -
.../hbase/HBaseAccessControllerFactory.java | 62 -
.../hbase/XaSecureAccessControlFilter.java | 51 -
.../hbase/XaSecureAuthorizationCoprocessor.java | 1259 -------
.../XaSecureAuthorizationCoprocessorBase.java | 671 ----
.../access/RangerAccessControlLists.java | 104 +
.../security/access/XaAccessControlLists.java | 104 -
.../ranger/authorization/hbase/Crypt.java | 85 +
.../hbase/HBaseAccessController.java | 40 +
.../hbase/HBaseAccessControllerFactory.java | 61 +
.../hbase/RangerAccessControlFilter.java | 51 +
.../hbase/RangerAuthorizationCoprocessor.java | 1259 +++++++
.../RangerAuthorizationCoprocessorBase.java | 671 ++++
.../access/RangerAccessControlListsTest.java | 61 +
.../access/XaAccessControlListsTest.java | 61 -
.../conf/xasecure-hdfs-security-changes.cfg | 2 +-
hdfs-agent/conf/xasecure-hdfs-security.xml | 2 +-
hdfs-agent/scripts/install.sh | 2 +-
.../hadoop/HDFSAccessVerifier.java | 35 -
.../hadoop/HDFSAccessVerifierFactory.java | 59 -
.../agent/AuthCodeInjectionJavaAgent.java | 32 -
.../agent/HadoopAuthClassTransformer.java | 196 --
.../XaSecureAccessControlException.java | 32 -
.../namenode/RangerFSPermissionChecker.java | 317 ++
.../namenode/XaSecureFSPermissionChecker.java | 318 --
.../hadoop/HDFSAccessVerifier.java | 35 +
.../hadoop/HDFSAccessVerifierFactory.java | 58 +
.../agent/AuthCodeInjectionJavaAgent.java | 32 +
.../agent/HadoopAuthClassTransformer.java | 196 ++
.../RangerAccessControlException.java | 32 +
.../src/main/resources/META-INF/MANIFEST.MF | 2 +-
.../agent/TestXaSecureFSPermissionChecker.java | 68 -
.../agent/TestRangerFSPermissionChecker.java | 67 +
hive-agent/conf/hiveserver2-site-changes.cfg | 2 +-
.../conf/xasecure-hive-security-changes.cfg | 2 +-
hive-agent/conf/xasecure-hive-security.xml | 2 +-
hive-agent/scripts/install.sh | 2 +-
.../authorization/hive/XaHiveAccessContext.java | 75 -
.../hive/XaHiveAccessVerifier.java | 29 -
.../hive/XaHiveAccessVerifierFactory.java | 67 -
.../hive/XaHiveObjectAccessInfo.java | 240 --
.../hive/authorizer/XaSecureHiveAuthorizer.java | 850 -----
.../authorizer/XaSecureHiveAuthorizerBase.java | 231 --
.../XaSecureHiveAuthorizerFactory.java | 39 -
.../hive/constants/XaSecureHiveConstants.java | 28 -
.../hive/RangerHiveAccessContext.java | 75 +
.../hive/RangerHiveAccessVerifier.java | 29 +
.../hive/RangerHiveAccessVerifierFactory.java | 66 +
.../hive/RangerHiveObjectAccessInfo.java | 240 ++
.../hive/authorizer/RangerHiveAuthorizer.java | 849 +++++
.../authorizer/RangerHiveAuthorizerBase.java | 230 ++
.../authorizer/RangerHiveAuthorizerFactory.java | 39 +
.../hive/constants/RangerHiveConstants.java | 28 +
knox-agent/.gitignore | 1 +
.../conf/xasecure-knox-security-changes.cfg | 2 +-
knox-agent/conf/xasecure-knox-security.xml | 2 +-
knox-agent/scripts/install.sh | 4 +-
.../authorization/knox/KnoxAccessVerifier.java | 30 -
.../knox/KnoxAccessVerifierFactory.java | 66 -
.../authorization/knox/KnoxAccessVerifier.java | 30 +
.../knox/KnoxAccessVerifierFactory.java | 65 +
.../com/xasecure/hadoop/client/HadoopFS.java | 196 --
.../xasecure/hadoop/client/HadoopFSTester.java | 61 -
.../hadoop/client/config/BaseClient.java | 164 -
.../hadoop/client/config/HadoopClassLoader.java | 106 -
.../client/config/HadoopConfigHolder.java | 361 --
.../client/exceptions/HadoopException.java | 60 -
.../com/xasecure/hbase/client/HBaseClient.java | 403 ---
.../hbase/client/HBaseClientTester.java | 78 -
.../com/xasecure/hive/client/HiveClient.java | 511 ---
.../xasecure/hive/client/HiveClientTester.java | 97 -
.../com/xasecure/knox/client/KnoxClient.java | 387 ---
.../xasecure/knox/client/KnoxClientTest.java | 42 -
.../xasecure/knox/client/XaSecureConstants.java | 42 -
.../com/xasecure/storm/client/StormClient.java | 395 ---
.../storm/client/json/model/Topology.java | 47 -
.../client/json/model/TopologyListResponse.java | 38 -
.../apache/ranger/hadoop/client/HadoopFS.java | 195 ++
.../ranger/hadoop/client/HadoopFSTester.java | 61 +
.../ranger/hadoop/client/config/BaseClient.java | 163 +
.../hadoop/client/config/HadoopClassLoader.java | 105 +
.../client/config/HadoopConfigHolder.java | 360 ++
.../client/exceptions/HadoopException.java | 60 +
.../apache/ranger/hbase/client/HBaseClient.java | 403 +++
.../ranger/hbase/client/HBaseClientTester.java | 78 +
.../apache/ranger/hive/client/HiveClient.java | 510 +++
.../ranger/hive/client/HiveClientTester.java | 97 +
.../apache/ranger/knox/client/KnoxClient.java | 387 +++
.../ranger/knox/client/KnoxClientTest.java | 42 +
.../ranger/knox/client/RangerConstants.java | 42 +
.../apache/ranger/storm/client/StormClient.java | 395 +++
.../storm/client/json/model/Topology.java | 47 +
.../client/json/model/TopologyListResponse.java | 38 +
lookup-client/src/scripts/run-audit-test.sh | 2 +-
lookup-client/src/scripts/run-hadoop-client.sh | 4 +-
lookup-client/src/scripts/run-hbase-client.sh | 8 +-
lookup-client/src/scripts/run-hive-client.sh | 10 +-
security-admin/.gitignore | 1 +
.../.settings/org.eclipse.wst.common.component | 1 -
security-admin/scripts/setup.sh | 16 +-
security-admin/src/bin/ranger_install.py | 4 +-
security-admin/src/bin/ranger_usersync.py | 2 +-
security-admin/src/bin/service_start.py | 2 +-
.../unix/jaas/RoleUserAuthorityGranter.java | 40 -
.../com/xasecure/biz/AssetConnectionMgr.java | 425 ---
.../main/java/com/xasecure/biz/AssetMgr.java | 3219 ------------------
.../java/com/xasecure/biz/AssetMgrBase.java | 174 -
.../src/main/java/com/xasecure/biz/BaseMgr.java | 80 -
.../main/java/com/xasecure/biz/HadoopFSMgr.java | 84 -
.../main/java/com/xasecure/biz/HiveFSMgr.java | 83 -
.../main/java/com/xasecure/biz/SessionMgr.java | 342 --
.../src/main/java/com/xasecure/biz/UserMgr.java | 1150 -------
.../main/java/com/xasecure/biz/UserMgrBase.java | 66 -
.../main/java/com/xasecure/biz/XABizUtil.java | 1316 -------
.../main/java/com/xasecure/biz/XAuditMgr.java | 25 -
.../java/com/xasecure/biz/XAuditMgrBase.java | 102 -
.../main/java/com/xasecure/biz/XUserMgr.java | 452 ---
.../java/com/xasecure/biz/XUserMgrBase.java | 246 --
.../java/com/xasecure/common/AppConstants.java | 954 ------
.../java/com/xasecure/common/ContextUtil.java | 84 -
.../main/java/com/xasecure/common/DateUtil.java | 108 -
.../com/xasecure/common/ErrorMessageUtil.java | 61 -
.../main/java/com/xasecure/common/GUIDUtil.java | 41 -
.../main/java/com/xasecure/common/HTTPUtil.java | 65 -
.../main/java/com/xasecure/common/JSONUtil.java | 134 -
.../java/com/xasecure/common/MessageEnums.java | 71 -
.../java/com/xasecure/common/MyCallBack.java | 34 -
.../java/com/xasecure/common/PasswordUtils.java | 159 -
.../com/xasecure/common/PropertiesUtil.java | 164 -
.../java/com/xasecure/common/RESTErrorUtil.java | 349 --
.../com/xasecure/common/RequestContext.java | 161 -
.../com/xasecure/common/SearchCriteria.java | 200 --
.../java/com/xasecure/common/SearchField.java | 218 --
.../java/com/xasecure/common/SearchGroup.java | 140 -
.../java/com/xasecure/common/SearchUtil.java | 819 -----
.../java/com/xasecure/common/SearchValue.java | 78 -
.../java/com/xasecure/common/SortField.java | 99 -
.../java/com/xasecure/common/StringUtil.java | 262 --
.../com/xasecure/common/TimedEventUtil.java | 78 -
.../com/xasecure/common/UserSessionBase.java | 115 -
.../java/com/xasecure/common/XACommonEnums.java | 1443 --------
.../java/com/xasecure/common/XAConfigUtil.java | 92 -
.../java/com/xasecure/common/XAConstants.java | 169 -
.../xasecure/common/XAJAXBContextResolver.java | 72 -
.../java/com/xasecure/common/XASearchUtil.java | 79 -
.../annotation/XAAnnotationClassName.java | 32 -
.../annotation/XAAnnotationJSMgrName.java | 35 -
.../common/annotation/XAAnnotationRestAPI.java | 36 -
.../java/com/xasecure/common/db/BaseDao.java | 216 --
.../xasecure/common/db/JPABeanCallbacks.java | 105 -
.../java/com/xasecure/common/view/VEnum.java | 107 -
.../com/xasecure/common/view/VEnumElement.java | 166 -
.../java/com/xasecure/common/view/VList.java | 189 -
.../com/xasecure/common/view/VTrxLogAttr.java | 84 -
.../com/xasecure/common/view/ViewBaseBean.java | 57 -
.../credentialapi/CredentialReader.java | 87 -
.../main/java/com/xasecure/db/XADaoManager.java | 79 -
.../java/com/xasecure/db/XADaoManagerBase.java | 214 --
.../java/com/xasecure/db/XXAccessAuditDao.java | 33 -
.../main/java/com/xasecure/db/XXAssetDao.java | 56 -
.../java/com/xasecure/db/XXAuditMapDao.java | 61 -
.../java/com/xasecure/db/XXAuthSessionDao.java | 53 -
.../com/xasecure/db/XXCredentialStoreDao.java | 34 -
.../main/java/com/xasecure/db/XXDBBaseDao.java | 31 -
.../main/java/com/xasecure/db/XXGroupDao.java | 74 -
.../java/com/xasecure/db/XXGroupGroupDao.java | 34 -
.../java/com/xasecure/db/XXGroupUserDao.java | 68 -
.../main/java/com/xasecure/db/XXPermMapDao.java | 60 -
.../com/xasecure/db/XXPolicyExportAuditDao.java | 33 -
.../java/com/xasecure/db/XXPortalUserDao.java | 79 -
.../com/xasecure/db/XXPortalUserRoleDao.java | 59 -
.../java/com/xasecure/db/XXResourceDao.java | 276 --
.../main/java/com/xasecure/db/XXTrxLogDao.java | 58 -
.../main/java/com/xasecure/db/XXUserDao.java | 53 -
.../java/com/xasecure/entity/XXAccessAudit.java | 651 ----
.../main/java/com/xasecure/entity/XXAsset.java | 287 --
.../java/com/xasecure/entity/XXAuditMap.java | 226 --
.../java/com/xasecure/entity/XXAuthSession.java | 470 ---
.../com/xasecure/entity/XXCredentialStore.java | 162 -
.../main/java/com/xasecure/entity/XXDBBase.java | 232 --
.../main/java/com/xasecure/entity/XXGroup.java | 273 --
.../java/com/xasecure/entity/XXGroupGroup.java | 194 --
.../java/com/xasecure/entity/XXGroupUser.java | 197 --
.../java/com/xasecure/entity/XXPermMap.java | 396 ---
.../xasecure/entity/XXPolicyExportAudit.java | 310 --
.../java/com/xasecure/entity/XXPortalUser.java | 378 --
.../com/xasecure/entity/XXPortalUserRole.java | 186 -
.../java/com/xasecure/entity/XXResource.java | 717 ----
.../main/java/com/xasecure/entity/XXTrxLog.java | 523 ---
.../main/java/com/xasecure/entity/XXUser.java | 227 --
.../com/xasecure/entity/view/VXXTrxLog.java | 399 ---
.../src/main/java/com/xasecure/json/Folder.java | 43 -
.../com/xasecure/json/JsonDateSerializer.java | 51 -
.../java/com/xasecure/patch/BaseLoader.java | 206 --
.../patch/PatchPasswordEncryption_J10001.java | 100 -
.../main/java/com/xasecure/rest/AssetREST.java | 655 ----
.../main/java/com/xasecure/rest/PublicAPIs.java | 319 --
.../main/java/com/xasecure/rest/UserREST.java | 332 --
.../main/java/com/xasecure/rest/XAuditREST.java | 150 -
.../main/java/com/xasecure/rest/XUserREST.java | 594 ----
.../security/context/XAContextHolder.java | 45 -
.../security/context/XASecurityContext.java | 58 -
.../xasecure/security/handler/Permission.java | 53 -
.../handler/XADomainObjectSecurityHandler.java | 112 -
.../security/listener/SpringEventListener.java | 113 -
.../standalone/StandaloneSecurityHandler.java | 79 -
.../CustomLogoutSuccessHandler.java | 68 -
.../authentication/XAAuthFailureHandler.java | 109 -
.../authentication/XAAuthSuccessHandler.java | 162 -
.../XAAuthenticationEntryPoint.java | 107 -
.../security/web/filter/MyRememberMeFilter.java | 184 -
.../XASecurityContextFormationFilter.java | 141 -
.../XAUsernamePasswordAuthenticationFilter.java | 52 -
.../service/AbstractBaseResourceService.java | 872 -----
.../xasecure/service/AuthSessionService.java | 207 --
.../xasecure/service/PublicAPIServiceBase.java | 45 -
.../java/com/xasecure/service/UserService.java | 329 --
.../com/xasecure/service/UserServiceBase.java | 73 -
.../xasecure/service/XAccessAuditService.java | 265 --
.../service/XAccessAuditServiceBase.java | 113 -
.../com/xasecure/service/XAgentService.java | 144 -
.../com/xasecure/service/XAssetService.java | 400 ---
.../com/xasecure/service/XAssetServiceBase.java | 89 -
.../com/xasecure/service/XAuditMapService.java | 188 -
.../xasecure/service/XAuditMapServiceBase.java | 85 -
.../service/XCredentialStoreService.java | 49 -
.../service/XCredentialStoreServiceBase.java | 81 -
.../xasecure/service/XGroupGroupService.java | 49 -
.../service/XGroupGroupServiceBase.java | 83 -
.../com/xasecure/service/XGroupService.java | 252 --
.../com/xasecure/service/XGroupServiceBase.java | 85 -
.../com/xasecure/service/XGroupUserService.java | 194 --
.../xasecure/service/XGroupUserServiceBase.java | 83 -
.../com/xasecure/service/XPermMapService.java | 316 --
.../xasecure/service/XPermMapServiceBase.java | 97 -
.../service/XPolicyExportAuditService.java | 67 -
.../service/XPolicyExportAuditServiceBase.java | 91 -
.../com/xasecure/service/XPolicyService.java | 754 ----
.../xasecure/service/XPortalUserService.java | 195 --
.../service/XPortalUserServiceBase.java | 95 -
.../xasecure/service/XRepositoryService.java | 133 -
.../com/xasecure/service/XResourceService.java | 1115 ------
.../xasecure/service/XResourceServiceBase.java | 117 -
.../com/xasecure/service/XTrxLogService.java | 461 ---
.../xasecure/service/XTrxLogServiceBase.java | 105 -
.../java/com/xasecure/service/XUserService.java | 380 ---
.../com/xasecure/service/XUserServiceBase.java | 83 -
.../service/filter/XARESTAPIFilter.java | 281 --
.../main/java/com/xasecure/util/CLIUtil.java | 68 -
.../main/java/com/xasecure/util/RestUtil.java | 78 -
.../main/java/com/xasecure/util/XAEnumUtil.java | 2023 -----------
.../main/java/com/xasecure/util/XARestUtil.java | 157 -
.../java/com/xasecure/view/VXAccessAudit.java | 473 ---
.../com/xasecure/view/VXAccessAuditList.java | 81 -
.../main/java/com/xasecure/view/VXAsset.java | 210 --
.../java/com/xasecure/view/VXAssetList.java | 81 -
.../main/java/com/xasecure/view/VXAuditMap.java | 164 -
.../java/com/xasecure/view/VXAuditMapList.java | 81 -
.../java/com/xasecure/view/VXAuditRecord.java | 239 --
.../com/xasecure/view/VXAuditRecordList.java | 69 -
.../java/com/xasecure/view/VXAuthSession.java | 501 ---
.../com/xasecure/view/VXAuthSessionList.java | 81 -
.../com/xasecure/view/VXCredentialStore.java | 118 -
.../xasecure/view/VXCredentialStoreList.java | 81 -
.../java/com/xasecure/view/VXDataObject.java | 186 -
.../main/java/com/xasecure/view/VXGroup.java | 179 -
.../java/com/xasecure/view/VXGroupGroup.java | 140 -
.../com/xasecure/view/VXGroupGroupList.java | 81 -
.../java/com/xasecure/view/VXGroupList.java | 81 -
.../java/com/xasecure/view/VXGroupUser.java | 140 -
.../java/com/xasecure/view/VXGroupUserList.java | 81 -
.../src/main/java/com/xasecure/view/VXLong.java | 96 -
.../main/java/com/xasecure/view/VXMessage.java | 184 -
.../com/xasecure/view/VXPasswordChange.java | 206 --
.../main/java/com/xasecure/view/VXPermMap.java | 334 --
.../java/com/xasecure/view/VXPermMapList.java | 81 -
.../main/java/com/xasecure/view/VXPermObj.java | 142 -
.../java/com/xasecure/view/VXPermObjList.java | 81 -
.../main/java/com/xasecure/view/VXPolicy.java | 577 ----
.../com/xasecure/view/VXPolicyExportAudit.java | 229 --
.../xasecure/view/VXPolicyExportAuditList.java | 81 -
.../java/com/xasecure/view/VXPolicyList.java | 81 -
.../java/com/xasecure/view/VXPortalUser.java | 293 --
.../com/xasecure/view/VXPortalUserList.java | 81 -
.../java/com/xasecure/view/VXRepository.java | 219 --
.../com/xasecure/view/VXRepositoryList.java | 81 -
.../main/java/com/xasecure/view/VXResource.java | 624 ----
.../java/com/xasecure/view/VXResourceList.java | 81 -
.../main/java/com/xasecure/view/VXResponse.java | 175 -
.../main/java/com/xasecure/view/VXString.java | 96 -
.../java/com/xasecure/view/VXStringList.java | 81 -
.../main/java/com/xasecure/view/VXTrxLog.java | 379 ---
.../java/com/xasecure/view/VXTrxLogList.java | 76 -
.../src/main/java/com/xasecure/view/VXUser.java | 302 --
.../main/java/com/xasecure/view/VXUserList.java | 81 -
.../unix/jaas/RoleUserAuthorityGranter.java | 41 +
.../apache/ranger/biz/AssetConnectionMgr.java | 424 +++
.../java/org/apache/ranger/biz/AssetMgr.java | 3218 +++++++++++++++++
.../org/apache/ranger/biz/AssetMgrBase.java | 174 +
.../java/org/apache/ranger/biz/BaseMgr.java | 79 +
.../java/org/apache/ranger/biz/HadoopFSMgr.java | 83 +
.../java/org/apache/ranger/biz/HiveFSMgr.java | 83 +
.../java/org/apache/ranger/biz/SessionMgr.java | 340 ++
.../java/org/apache/ranger/biz/UserMgr.java | 1149 +++++++
.../java/org/apache/ranger/biz/UserMgrBase.java | 66 +
.../java/org/apache/ranger/biz/XABizUtil.java | 1313 +++++++
.../java/org/apache/ranger/biz/XAuditMgr.java | 25 +
.../org/apache/ranger/biz/XAuditMgrBase.java | 102 +
.../java/org/apache/ranger/biz/XUserMgr.java | 450 +++
.../org/apache/ranger/biz/XUserMgrBase.java | 246 ++
.../org/apache/ranger/common/AppConstants.java | 955 ++++++
.../org/apache/ranger/common/ContextUtil.java | 84 +
.../java/org/apache/ranger/common/DateUtil.java | 108 +
.../apache/ranger/common/ErrorMessageUtil.java | 61 +
.../java/org/apache/ranger/common/GUIDUtil.java | 41 +
.../java/org/apache/ranger/common/HTTPUtil.java | 65 +
.../java/org/apache/ranger/common/JSONUtil.java | 133 +
.../org/apache/ranger/common/MessageEnums.java | 71 +
.../org/apache/ranger/common/MyCallBack.java | 34 +
.../org/apache/ranger/common/PasswordUtils.java | 159 +
.../apache/ranger/common/PropertiesUtil.java | 164 +
.../org/apache/ranger/common/RESTErrorUtil.java | 348 ++
.../apache/ranger/common/RequestContext.java | 161 +
.../apache/ranger/common/SearchCriteria.java | 199 ++
.../org/apache/ranger/common/SearchField.java | 218 ++
.../org/apache/ranger/common/SearchGroup.java | 140 +
.../org/apache/ranger/common/SearchUtil.java | 819 +++++
.../org/apache/ranger/common/SearchValue.java | 78 +
.../org/apache/ranger/common/SortField.java | 99 +
.../org/apache/ranger/common/StringUtil.java | 262 ++
.../apache/ranger/common/TimedEventUtil.java | 78 +
.../apache/ranger/common/UserSessionBase.java | 115 +
.../org/apache/ranger/common/XACommonEnums.java | 1444 ++++++++
.../org/apache/ranger/common/XAConfigUtil.java | 91 +
.../org/apache/ranger/common/XAConstants.java | 169 +
.../ranger/common/XAJAXBContextResolver.java | 73 +
.../org/apache/ranger/common/XASearchUtil.java | 78 +
.../annotation/XAAnnotationClassName.java | 32 +
.../annotation/XAAnnotationJSMgrName.java | 35 +
.../common/annotation/XAAnnotationRestAPI.java | 36 +
.../org/apache/ranger/common/db/BaseDao.java | 215 ++
.../ranger/common/db/JPABeanCallbacks.java | 103 +
.../org/apache/ranger/common/view/VEnum.java | 107 +
.../apache/ranger/common/view/VEnumElement.java | 166 +
.../org/apache/ranger/common/view/VList.java | 189 +
.../apache/ranger/common/view/VTrxLogAttr.java | 83 +
.../apache/ranger/common/view/ViewBaseBean.java | 56 +
.../ranger/credentialapi/CredentialReader.java | 87 +
.../java/org/apache/ranger/db/XADaoManager.java | 77 +
.../org/apache/ranger/db/XADaoManagerBase.java | 216 ++
.../org/apache/ranger/db/XXAccessAuditDao.java | 32 +
.../java/org/apache/ranger/db/XXAssetDao.java | 54 +
.../org/apache/ranger/db/XXAuditMapDao.java | 57 +
.../org/apache/ranger/db/XXAuthSessionDao.java | 53 +
.../apache/ranger/db/XXCredentialStoreDao.java | 32 +
.../java/org/apache/ranger/db/XXDBBaseDao.java | 31 +
.../java/org/apache/ranger/db/XXGroupDao.java | 73 +
.../org/apache/ranger/db/XXGroupGroupDao.java | 32 +
.../org/apache/ranger/db/XXGroupUserDao.java | 64 +
.../java/org/apache/ranger/db/XXPermMapDao.java | 56 +
.../ranger/db/XXPolicyExportAuditDao.java | 32 +
.../org/apache/ranger/db/XXPortalUserDao.java | 79 +
.../apache/ranger/db/XXPortalUserRoleDao.java | 59 +
.../org/apache/ranger/db/XXResourceDao.java | 273 ++
.../java/org/apache/ranger/db/XXTrxLogDao.java | 56 +
.../java/org/apache/ranger/db/XXUserDao.java | 51 +
.../org/apache/ranger/entity/XXAccessAudit.java | 653 ++++
.../java/org/apache/ranger/entity/XXAsset.java | 289 ++
.../org/apache/ranger/entity/XXAuditMap.java | 228 ++
.../org/apache/ranger/entity/XXAuthSession.java | 472 +++
.../apache/ranger/entity/XXCredentialStore.java | 164 +
.../java/org/apache/ranger/entity/XXDBBase.java | 234 ++
.../java/org/apache/ranger/entity/XXGroup.java | 275 ++
.../org/apache/ranger/entity/XXGroupGroup.java | 196 ++
.../org/apache/ranger/entity/XXGroupUser.java | 199 ++
.../org/apache/ranger/entity/XXPermMap.java | 398 +++
.../ranger/entity/XXPolicyExportAudit.java | 312 ++
.../org/apache/ranger/entity/XXPortalUser.java | 380 +++
.../apache/ranger/entity/XXPortalUserRole.java | 188 +
.../org/apache/ranger/entity/XXResource.java | 719 ++++
.../java/org/apache/ranger/entity/XXTrxLog.java | 525 +++
.../java/org/apache/ranger/entity/XXUser.java | 229 ++
.../apache/ranger/entity/view/VXXTrxLog.java | 399 +++
.../java/org/apache/ranger/json/Folder.java | 43 +
.../apache/ranger/json/JsonDateSerializer.java | 51 +
.../org/apache/ranger/patch/BaseLoader.java | 204 ++
.../patch/PatchPasswordEncryption_J10001.java | 99 +
.../java/org/apache/ranger/rest/AssetREST.java | 654 ++++
.../java/org/apache/ranger/rest/PublicAPIs.java | 318 ++
.../java/org/apache/ranger/rest/UserREST.java | 330 ++
.../java/org/apache/ranger/rest/XAuditREST.java | 145 +
.../java/org/apache/ranger/rest/XUserREST.java | 589 ++++
.../security/context/XAContextHolder.java | 45 +
.../security/context/XASecurityContext.java | 58 +
.../ranger/security/handler/Permission.java | 53 +
.../handler/XADomainObjectSecurityHandler.java | 112 +
.../security/listener/SpringEventListener.java | 111 +
.../standalone/StandaloneSecurityHandler.java | 78 +
.../CustomLogoutSuccessHandler.java | 67 +
.../authentication/XAAuthFailureHandler.java | 108 +
.../authentication/XAAuthSuccessHandler.java | 161 +
.../XAAuthenticationEntryPoint.java | 106 +
.../security/web/filter/MyRememberMeFilter.java | 184 +
.../XASecurityContextFormationFilter.java | 139 +
.../XAUsernamePasswordAuthenticationFilter.java | 52 +
.../service/AbstractBaseResourceService.java | 870 +++++
.../ranger/service/AuthSessionService.java | 206 ++
.../ranger/service/PublicAPIServiceBase.java | 45 +
.../org/apache/ranger/service/UserService.java | 328 ++
.../apache/ranger/service/UserServiceBase.java | 73 +
.../ranger/service/XAccessAuditService.java | 264 ++
.../ranger/service/XAccessAuditServiceBase.java | 113 +
.../apache/ranger/service/XAgentService.java | 142 +
.../apache/ranger/service/XAssetService.java | 398 +++
.../ranger/service/XAssetServiceBase.java | 89 +
.../apache/ranger/service/XAuditMapService.java | 186 +
.../ranger/service/XAuditMapServiceBase.java | 85 +
.../ranger/service/XCredentialStoreService.java | 45 +
.../service/XCredentialStoreServiceBase.java | 81 +
.../ranger/service/XGroupGroupService.java | 45 +
.../ranger/service/XGroupGroupServiceBase.java | 83 +
.../apache/ranger/service/XGroupService.java | 248 ++
.../ranger/service/XGroupServiceBase.java | 85 +
.../ranger/service/XGroupUserService.java | 190 ++
.../ranger/service/XGroupUserServiceBase.java | 83 +
.../apache/ranger/service/XPermMapService.java | 314 ++
.../ranger/service/XPermMapServiceBase.java | 97 +
.../service/XPolicyExportAuditService.java | 65 +
.../service/XPolicyExportAuditServiceBase.java | 91 +
.../apache/ranger/service/XPolicyService.java | 753 ++++
.../ranger/service/XPortalUserService.java | 194 ++
.../ranger/service/XPortalUserServiceBase.java | 95 +
.../ranger/service/XRepositoryService.java | 132 +
.../apache/ranger/service/XResourceService.java | 1112 ++++++
.../ranger/service/XResourceServiceBase.java | 117 +
.../apache/ranger/service/XTrxLogService.java | 460 +++
.../ranger/service/XTrxLogServiceBase.java | 105 +
.../org/apache/ranger/service/XUserService.java | 375 ++
.../apache/ranger/service/XUserServiceBase.java | 83 +
.../ranger/service/filter/XARESTAPIFilter.java | 280 ++
.../java/org/apache/ranger/util/CLIUtil.java | 67 +
.../java/org/apache/ranger/util/RestUtil.java | 77 +
.../java/org/apache/ranger/util/XAEnumUtil.java | 2024 +++++++++++
.../java/org/apache/ranger/util/XARestUtil.java | 156 +
.../org/apache/ranger/view/VXAccessAudit.java | 469 +++
.../apache/ranger/view/VXAccessAuditList.java | 81 +
.../java/org/apache/ranger/view/VXAsset.java | 206 ++
.../org/apache/ranger/view/VXAssetList.java | 81 +
.../java/org/apache/ranger/view/VXAuditMap.java | 160 +
.../org/apache/ranger/view/VXAuditMapList.java | 81 +
.../org/apache/ranger/view/VXAuditRecord.java | 238 ++
.../apache/ranger/view/VXAuditRecordList.java | 68 +
.../org/apache/ranger/view/VXAuthSession.java | 497 +++
.../apache/ranger/view/VXAuthSessionList.java | 81 +
.../apache/ranger/view/VXCredentialStore.java | 114 +
.../ranger/view/VXCredentialStoreList.java | 81 +
.../org/apache/ranger/view/VXDataObject.java | 182 +
.../java/org/apache/ranger/view/VXGroup.java | 175 +
.../org/apache/ranger/view/VXGroupGroup.java | 136 +
.../apache/ranger/view/VXGroupGroupList.java | 81 +
.../org/apache/ranger/view/VXGroupList.java | 81 +
.../org/apache/ranger/view/VXGroupUser.java | 136 +
.../org/apache/ranger/view/VXGroupUserList.java | 81 +
.../java/org/apache/ranger/view/VXLong.java | 92 +
.../java/org/apache/ranger/view/VXMessage.java | 180 +
.../apache/ranger/view/VXPasswordChange.java | 202 ++
.../java/org/apache/ranger/view/VXPermMap.java | 330 ++
.../org/apache/ranger/view/VXPermMapList.java | 81 +
.../java/org/apache/ranger/view/VXPermObj.java | 142 +
.../org/apache/ranger/view/VXPermObjList.java | 81 +
.../java/org/apache/ranger/view/VXPolicy.java | 576 ++++
.../apache/ranger/view/VXPolicyExportAudit.java | 225 ++
.../ranger/view/VXPolicyExportAuditList.java | 81 +
.../org/apache/ranger/view/VXPolicyList.java | 81 +
.../org/apache/ranger/view/VXPortalUser.java | 289 ++
.../apache/ranger/view/VXPortalUserList.java | 81 +
.../org/apache/ranger/view/VXRepository.java | 218 ++
.../apache/ranger/view/VXRepositoryList.java | 81 +
.../java/org/apache/ranger/view/VXResource.java | 622 ++++
.../org/apache/ranger/view/VXResourceList.java | 81 +
.../java/org/apache/ranger/view/VXResponse.java | 171 +
.../java/org/apache/ranger/view/VXString.java | 92 +
.../org/apache/ranger/view/VXStringList.java | 81 +
.../java/org/apache/ranger/view/VXTrxLog.java | 375 ++
.../org/apache/ranger/view/VXTrxLogList.java | 76 +
.../java/org/apache/ranger/view/VXUser.java | 300 ++
.../java/org/apache/ranger/view/VXUserList.java | 81 +
.../src/main/resources/META-INF/persistence.xml | 32 +-
.../conf.dist/security-applicationContext.xml | 16 +-
.../src/main/resources/xa_default.properties | 2 +-
.../main/webapp/META-INF/applicationContext.xml | 10 +-
.../META-INF/contextXML/unix_bean_settings.xml | 4 +-
.../src/main/webapp/WEB-INF/log4j.dev.xml | 2 +-
.../src/main/webapp/WEB-INF/log4j.xml | 2 +-
security-admin/src/main/webapp/WEB-INF/web.xml | 8 +-
.../java/com/xasecure/biz/TestAssetMgr.java | 739 ----
.../test/java/com/xasecure/biz/TestUserMgr.java | 573 ----
.../java/com/xasecure/biz/TestXABizUtil.java | 546 ---
.../java/com/xasecure/biz/TestXUserMgr.java | 398 ---
.../java/com/xasecure/common/TestDateUtil.java | 80 -
.../java/com/xasecure/common/TestJSONUtil.java | 71 -
.../com/xasecure/common/TestPropertiesUtil.java | 112 -
.../com/xasecure/common/TestStringUtil.java | 193 --
.../com/xasecure/common/TestXAConfigUtil.java | 54 -
.../java/com/xasecure/rest/TestPublicAPIs.java | 245 --
.../test/java/com/xasecure/util/BaseTest.java | 111 -
.../java/com/xasecure/util/TestXAEnumUtil.java | 124 -
.../org/apache/ranger/biz/TestAssetMgr.java | 741 ++++
.../java/org/apache/ranger/biz/TestUserMgr.java | 574 ++++
.../org/apache/ranger/biz/TestXABizUtil.java | 548 +++
.../org/apache/ranger/biz/TestXUserMgr.java | 399 +++
.../org/apache/ranger/common/TestDateUtil.java | 81 +
.../org/apache/ranger/common/TestJSONUtil.java | 73 +
.../ranger/common/TestPropertiesUtil.java | 113 +
.../apache/ranger/common/TestStringUtil.java | 193 ++
.../apache/ranger/common/TestXAConfigUtil.java | 55 +
.../org/apache/ranger/rest/TestPublicAPIs.java | 245 ++
.../java/org/apache/ranger/util/BaseTest.java | 110 +
.../org/apache/ranger/util/TestXAEnumUtil.java | 126 +
storm-agent/.gitignore | 1 +
.../conf/xasecure-storm-security-changes.cfg | 2 +-
storm-agent/conf/xasecure-storm-security.xml | 2 +-
storm-agent/scripts/install.sh | 10 +-
.../storm/XaStormAccessVerifier.java | 26 -
.../storm/XaStormAccessVerifierFactory.java | 69 -
.../authorizer/XaSecureStormAuthorizer.java | 198 --
.../storm/RangerStormAccessVerifier.java | 26 +
.../storm/RangerStormAccessVerifierFactory.java | 68 +
.../storm/authorizer/RangerStormAuthorizer.java | 197 ++
.../process/LdapUserGroupBuilder.java | 308 --
.../process/PolicyMgrUserGroupBuilder.java | 703 ----
.../config/UserGroupSyncConfig.java | 399 ---
.../model/GetXGroupListResponse.java | 50 -
.../model/GetXUserGroupListResponse.java | 50 -
.../model/GetXUserListResponse.java | 51 -
.../xasecure/unixusersync/model/MUserInfo.java | 62 -
.../xasecure/unixusersync/model/XGroupInfo.java | 56 -
.../unixusersync/model/XUserGroupInfo.java | 59 -
.../xasecure/unixusersync/model/XUserInfo.java | 55 -
.../unixusersync/poc/InvalidGroupException.java | 39 -
.../unixusersync/poc/InvalidUserException.java | 39 -
.../unixusersync/poc/ListUserGroupTest.java | 39 -
.../xasecure/unixusersync/poc/ListUserTest.java | 49 -
.../unixusersync/poc/ListXaSecureUser.java | 116 -
.../unixusersync/poc/ListXaSecureUserGroup.java | 142 -
.../unixusersync/poc/RestClientPost.java | 55 -
.../poc/XaSecureClientUserGroupMapping.java | 67 -
.../unixusersync/poc/XaSecureJSONParser.java | 63 -
.../poc/XaSecureUpdateUserGroupMapping.java | 77 -
.../poc/XaSecureUserGroupMapping.java | 85 -
.../process/PolicyMgrUserGroupBuilder.java | 703 ----
.../process/UnixUserGroupBuilder.java | 256 --
.../xasecure/usergroupsync/UserGroupSink.java | 28 -
.../xasecure/usergroupsync/UserGroupSource.java | 29 -
.../xasecure/usergroupsync/UserGroupSync.java | 123 -
.../process/LdapUserGroupBuilder.java | 307 ++
.../process/PolicyMgrUserGroupBuilder.java | 703 ++++
.../config/UserGroupSyncConfig.java | 399 +++
.../model/GetXGroupListResponse.java | 50 +
.../model/GetXUserGroupListResponse.java | 50 +
.../model/GetXUserListResponse.java | 51 +
.../ranger/unixusersync/model/MUserInfo.java | 62 +
.../ranger/unixusersync/model/XGroupInfo.java | 56 +
.../unixusersync/model/XUserGroupInfo.java | 59 +
.../ranger/unixusersync/model/XUserInfo.java | 55 +
.../unixusersync/poc/InvalidGroupException.java | 39 +
.../unixusersync/poc/InvalidUserException.java | 39 +
.../ranger/unixusersync/poc/ListRangerUser.java | 116 +
.../unixusersync/poc/ListRangerUserGroup.java | 142 +
.../unixusersync/poc/ListUserGroupTest.java | 39 +
.../ranger/unixusersync/poc/ListUserTest.java | 49 +
.../poc/RangerClientUserGroupMapping.java | 67 +
.../unixusersync/poc/RangerJSONParser.java | 63 +
.../poc/RangerUpdateUserGroupMapping.java | 77 +
.../poc/RangerUserGroupMapping.java | 85 +
.../ranger/unixusersync/poc/RestClientPost.java | 55 +
.../process/PolicyMgrUserGroupBuilder.java | 703 ++++
.../process/UnixUserGroupBuilder.java | 255 ++
.../ranger/usergroupsync/UserGroupSink.java | 28 +
.../ranger/usergroupsync/UserGroupSource.java | 29 +
.../ranger/usergroupsync/UserGroupSync.java | 122 +
.../unix/jaas/ConsolePromptCallbackHandler.java | 59 -
.../unix/jaas/RemoteUnixLoginModule.java | 471 ---
.../unix/jaas/UnixGroupPrincipal.java | 40 -
.../unix/jaas/UnixUserPrincipal.java | 40 -
.../unix/jaas/ConsolePromptCallbackHandler.java | 59 +
.../unix/jaas/RemoteUnixLoginModule.java | 471 +++
.../unix/jaas/UnixGroupPrincipal.java | 40 +
.../unix/jaas/UnixUserPrincipal.java | 40 +
unixauthservice/conf.dist/jaas.conf | 2 +-
.../conf.dist/unixauthservice.properties | 26 +-
unixauthservice/scripts/setup.sh | 10 +-
unixauthservice/scripts/start.sh | 2 +-
.../authentication/PasswordValidator.java | 161 -
.../UnixAuthenticationService.java | 284 --
.../authentication/PasswordValidator.java | 161 +
.../UnixAuthenticationService.java | 283 ++
winpkg/pom.xml | 2 +-
winpkg/src/scripts/InstallApi.psm1 | 8 +-
winpkg/src/scripts/install.ps1 | 18 +-
809 files changed, 77720 insertions(+), 77904 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/dao/BaseDao.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/dao/BaseDao.java b/agents-audit/src/main/java/com/xasecure/audit/dao/BaseDao.java
deleted file mode 100644
index 2a5a91d..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/dao/BaseDao.java
+++ /dev/null
@@ -1,234 +0,0 @@
-/*
- * 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 com.xasecure.audit.dao;
-
-
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.EntityTransaction;
-import javax.persistence.NoResultException;
-import javax.persistence.TypedQuery;
-
-import org.apache.log4j.Logger;
-
-public abstract class BaseDao<T> {
- static final Logger logger = Logger.getLogger(BaseDao.class);
-
- protected DaoManager daoManager;
-
- protected Class<T> tClass;
-
- public BaseDao(DaoManagerBase daoManager) {
- this.init(daoManager);
- }
-
- @SuppressWarnings("unchecked")
- private void init(DaoManagerBase daoManager) {
- this.daoManager = (DaoManager) daoManager;
-
- ParameterizedType genericSuperclass = (ParameterizedType) getClass()
- .getGenericSuperclass();
-
- Type type = genericSuperclass.getActualTypeArguments()[0];
-
- if (type instanceof ParameterizedType) {
- this.tClass = (Class<T>) ((ParameterizedType) type).getRawType();
- } else {
- this.tClass = (Class<T>) type;
- }
- }
-
- public EntityManager getEntityManager() {
- return daoManager.getEntityManager();
- }
-
- public boolean beginTransaction() {
- boolean ret = false;
-
- EntityManager em = getEntityManager();
-
- if(em != null) {
- EntityTransaction et = em.getTransaction();
-
- // check the transaction is not already active
- if(et != null && !et.isActive()) {
- et.begin();
- ret = true;
- }
- }
-
- return ret;
- }
-
- public void commitTransaction() {
- EntityManager em = getEntityManager();
-
- if(em != null) {
- em.flush();
-
- EntityTransaction et = em.getTransaction();
-
- if(et != null) {
- et.commit();
- }
- }
- }
-
- public void rollbackTransaction() {
- EntityManager em = getEntityManager();
-
- if(em != null) {
- EntityTransaction et = em.getTransaction();
-
- if(et != null) {
- et.rollback();
- }
- }
- }
-
- public T create(T obj) {
- T ret = null;
-
- boolean trxBegan = beginTransaction();
-
- getEntityManager().persist(obj);
-
- if(trxBegan) {
- commitTransaction();
- }
-
- ret = obj;
-
- return ret;
- }
-
- public T update(T obj) {
- boolean trxBegan = beginTransaction();
-
- getEntityManager().merge(obj);
-
- if(trxBegan) {
- commitTransaction();
- }
-
- return obj;
- }
-
- public boolean remove(Long id) {
- return remove(getById(id));
- }
-
- public boolean remove(T obj) {
- if (obj == null) {
- return true;
- }
-
- boolean ret = false;
-
- boolean trxBegan = beginTransaction();
-
- getEntityManager().remove(obj);
-
- if(trxBegan) {
- commitTransaction();
- }
-
- ret = true;
-
- return ret;
- }
-
- public T getById(Long id) {
- if (id == null) {
- return null;
- }
- T ret = null;
- try {
- ret = getEntityManager().find(tClass, id);
- } catch (NoResultException e) {
- return null;
- }
- return ret;
- }
-
- public List<T> getAll() {
- List<T> ret = null;
-
- TypedQuery<T> qry = getEntityManager().createQuery(
- "SELECT t FROM " + tClass.getSimpleName() + " t", tClass);
-
- ret = qry.getResultList();
-
- return ret;
- }
-
- public Long getAllCount() {
- Long ret = null;
-
- TypedQuery<Long> qry = getEntityManager().createQuery(
- "SELECT count(t) FROM " + tClass.getSimpleName() + " t",
- Long.class);
-
- ret = qry.getSingleResult();
-
- return ret;
- }
-
- public T getUniqueResult(TypedQuery<T> qry) {
- T ret = null;
-
- try {
- ret = qry.getSingleResult();
- } catch (NoResultException e) {
- // ignore
- }
- return ret;
- }
-
- public List<T> executeQuery(TypedQuery<T> qry) {
- List<T> ret = null;
-
- ret = qry.getResultList();
-
- return ret;
- }
-
- public List<T> findByNamedQuery(String namedQuery, String paramName,
- Object refId) {
- List<T> ret = new ArrayList<T>();
-
- if (namedQuery == null) {
- return ret;
- }
- try {
- TypedQuery<T> qry = getEntityManager().createNamedQuery(namedQuery, tClass);
- qry.setParameter(paramName, refId);
- ret = qry.getResultList();
- } catch (NoResultException e) {
- // ignore
- }
- return ret;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/dao/DaoManager.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/dao/DaoManager.java b/agents-audit/src/main/java/com/xasecure/audit/dao/DaoManager.java
deleted file mode 100644
index 05dfb89..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/dao/DaoManager.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * 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 com.xasecure.audit.dao;
-
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.PersistenceContext;
-
-
-//@Component
-public class DaoManager extends DaoManagerBase {
-
- @PersistenceContext
- private EntityManagerFactory emf;
-
- static ThreadLocal<EntityManager> sEntityManager;
-
- public void setEntityManagerFactory(EntityManagerFactory emf) {
- this.emf = emf;
- sEntityManager = new ThreadLocal<EntityManager>();
- }
-
- @Override
- public EntityManager getEntityManager() {
- EntityManager em = null;
-
- if(sEntityManager != null) {
- em = sEntityManager.get();
-
- if(em == null && this.emf != null) {
- em = this.emf.createEntityManager();
-
- sEntityManager.set(em);
- }
- }
-
- return em;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/dao/DaoManagerBase.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/dao/DaoManagerBase.java b/agents-audit/src/main/java/com/xasecure/audit/dao/DaoManagerBase.java
deleted file mode 100644
index 0718bec..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/dao/DaoManagerBase.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/**
- * 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 com.xasecure.audit.dao;
-
-import javax.persistence.EntityManager;
-
-import org.apache.log4j.Logger;
-
-
-public abstract class DaoManagerBase {
- final static Logger logger = Logger.getLogger(DaoManagerBase.class);
-
- abstract public EntityManager getEntityManager();
-
- private XAHBaseAuditEventDao mHBaseDao = null;
- private XAHdfsAuditEventDao mHdfsDao = null;
- private XAHiveAuditEventDao mHiveDao = null;
- private XAKnoxAuditEventDao mKnoxDao = null;
- private XAStormAuditEventDao mStormDao = null;
-
- public DaoManagerBase() {
- }
-
- public XAHBaseAuditEventDao getXAHBaseAuditEventDao() {
- if(mHBaseDao == null) {
- mHBaseDao = new XAHBaseAuditEventDao(this);
- }
-
- return mHBaseDao;
- }
-
- public XAHdfsAuditEventDao getXAHdfsAuditEventDao() {
- if(mHdfsDao == null) {
- mHdfsDao = new XAHdfsAuditEventDao(this);
- }
-
- return mHdfsDao;
- }
-
- public XAHiveAuditEventDao getXAHiveAuditEventDao() {
- if(mHiveDao == null) {
- mHiveDao = new XAHiveAuditEventDao(this);
- }
-
- return mHiveDao;
- }
-
- public XAKnoxAuditEventDao getXAKnoxAuditEventDao() {
- if(mKnoxDao == null) {
- mKnoxDao = new XAKnoxAuditEventDao(this);
- }
-
- return mKnoxDao;
- }
-
- public XAStormAuditEventDao getXAStormAuditEventDao() {
- if(mStormDao == null) {
- mStormDao = new XAStormAuditEventDao(this);
- }
-
- return mStormDao;
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/dao/XAHBaseAuditEventDao.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/dao/XAHBaseAuditEventDao.java b/agents-audit/src/main/java/com/xasecure/audit/dao/XAHBaseAuditEventDao.java
deleted file mode 100644
index 610a5d8..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/dao/XAHBaseAuditEventDao.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * 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 com.xasecure.audit.dao;
-
-import com.xasecure.audit.entity.XXHBaseAuditEvent;
-
-public class XAHBaseAuditEventDao extends BaseDao<XXHBaseAuditEvent> {
-
- public XAHBaseAuditEventDao(DaoManagerBase daoManager) {
- super(daoManager);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/dao/XAHdfsAuditEventDao.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/dao/XAHdfsAuditEventDao.java b/agents-audit/src/main/java/com/xasecure/audit/dao/XAHdfsAuditEventDao.java
deleted file mode 100644
index 450b483..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/dao/XAHdfsAuditEventDao.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * 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 com.xasecure.audit.dao;
-
-import com.xasecure.audit.entity.XXHdfsAuditEvent;
-
-public class XAHdfsAuditEventDao extends BaseDao<XXHdfsAuditEvent> {
-
- public XAHdfsAuditEventDao(DaoManagerBase daoManager) {
- super(daoManager);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/dao/XAHiveAuditEventDao.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/dao/XAHiveAuditEventDao.java b/agents-audit/src/main/java/com/xasecure/audit/dao/XAHiveAuditEventDao.java
deleted file mode 100644
index fc511f6..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/dao/XAHiveAuditEventDao.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * 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 com.xasecure.audit.dao;
-
-import com.xasecure.audit.entity.XXHiveAuditEvent;
-
-public class XAHiveAuditEventDao extends BaseDao<XXHiveAuditEvent> {
-
- public XAHiveAuditEventDao(DaoManagerBase daoManager) {
- super(daoManager);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/dao/XAKnoxAuditEventDao.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/dao/XAKnoxAuditEventDao.java b/agents-audit/src/main/java/com/xasecure/audit/dao/XAKnoxAuditEventDao.java
deleted file mode 100644
index 2b7c374..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/dao/XAKnoxAuditEventDao.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * 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 com.xasecure.audit.dao;
-
-import com.xasecure.audit.entity.XXKnoxAuditEvent;
-
-public class XAKnoxAuditEventDao extends BaseDao<XXKnoxAuditEvent> {
-
- public XAKnoxAuditEventDao(DaoManagerBase daoManager) {
- super(daoManager);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/dao/XAStormAuditEventDao.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/dao/XAStormAuditEventDao.java b/agents-audit/src/main/java/com/xasecure/audit/dao/XAStormAuditEventDao.java
deleted file mode 100644
index f7cb97c..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/dao/XAStormAuditEventDao.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * 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 com.xasecure.audit.dao;
-
-import com.xasecure.audit.entity.XXStormAuditEvent;
-
-public class XAStormAuditEventDao extends BaseDao<XXStormAuditEvent> {
-
- public XAStormAuditEventDao(DaoManagerBase daoManager) {
- super(daoManager);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/entity/XXBaseAuditEvent.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/entity/XXBaseAuditEvent.java b/agents-audit/src/main/java/com/xasecure/audit/entity/XXBaseAuditEvent.java
deleted file mode 100644
index aca6963..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/entity/XXBaseAuditEvent.java
+++ /dev/null
@@ -1,228 +0,0 @@
-/*
- * 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 com.xasecure.audit.entity;
-
-import java.io.Serializable;
-import java.util.Date;
-
-import javax.persistence.Column;
-import javax.persistence.DiscriminatorColumn;
-import javax.persistence.DiscriminatorValue;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.Inheritance;
-import javax.persistence.SequenceGenerator;
-import javax.persistence.Table;
-import javax.persistence.Temporal;
-import javax.persistence.TemporalType;
-
-import com.xasecure.audit.model.AuditEventBase;
-
-/**
- * Entity implementation class for Entity: XABaseAuditEvent
- *
- */
-@Entity
-@Inheritance
-@DiscriminatorColumn(name="audit_type", discriminatorType=javax.persistence.DiscriminatorType.INTEGER, length=2)
-@DiscriminatorValue("0")
-@Table(name="xa_access_audit")
-public class XXBaseAuditEvent implements Serializable {
- private static final long serialVersionUID = 1L;
-
- private long auditId;
- private String agentId;
- private String user;
- private Date timeStamp;
- private long policyId;
- private String accessType;
- private int accessResult;
- private String resultReason;
- private String aclEnforcer;
- private int repositoryType;
- private String repositoryName;
- private String sessionId;
- private String clientType;
- private String clientIP;
- private String action;
-
- public XXBaseAuditEvent() {
- super();
- }
-
- public XXBaseAuditEvent(AuditEventBase event) {
- this.agentId = event.getAgentId();
- this.user = event.getUser();
- this.timeStamp = event.getEventTime();
- this.policyId = event.getPolicyId();
- this.accessType = event.getAccessType();
- this.accessResult = event.getAccessResult();
- this.resultReason = event.getResultReason();
- this.aclEnforcer = event.getAclEnforcer();
- this.repositoryType = event.getRepositoryType();
- this.repositoryName = event.getRepositoryName();
- this.sessionId = event.getSessionId();
- this.clientType = event.getClientType();
- this.clientIP = event.getClientIP();
- this.action = event.getAction();
- }
-
- @Id
- @SequenceGenerator(name="XA_ACCESS_AUDIT_SEQ",sequenceName="XA_ACCESS_AUDIT_SEQ",allocationSize=1)
- @GeneratedValue(strategy=GenerationType.AUTO,generator="XA_ACCESS_AUDIT_SEQ")
- @Column(name = "id", unique = true, nullable = false)
- public long getAuditId() {
- return this.auditId;
- }
-
- public void setAuditId(long auditId) {
- this.auditId = auditId;
- }
-
- @Column(name = "agent_id")
- public String getAgentId() {
- return agentId;
- }
-
- public void setAgentId(String agentId) {
- this.agentId = agentId;
- }
-
- @Column(name = "request_user")
- public String getUser() {
- return this.user;
- }
-
- public void setUser(String user) {
- this.user = user;
- }
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "event_time")
- public Date getTimeStamp() {
- return this.timeStamp;
- }
-
- public void setTimeStamp(Date timeStamp) {
- this.timeStamp = timeStamp;
- }
-
- @Column(name = "policy_id")
- public long getPolicyId() {
- return this.policyId;
- }
-
- public void setPolicyId(long policyId) {
- this.policyId = policyId;
- }
-
- @Column(name = "access_type")
- public String getAccessType() {
- return this.accessType;
- }
-
- public void setAccessType(String accessType) {
- this.accessType = accessType;
- }
-
- @Column(name = "access_result")
- public int getAccessResult() {
- return this.accessResult;
- }
-
- public void setAccessResult(int accessResult) {
- this.accessResult = accessResult;
- }
-
- @Column(name = "result_reason")
- public String getResultReason() {
- return this.resultReason;
- }
-
- public void setResultReason(String resultReason) {
- this.resultReason = resultReason;
- }
-
- @Column(name = "acl_enforcer")
- public String getAclEnforcer() {
- return this.aclEnforcer;
- }
-
- public void setAclEnforcer(String aclEnforcer) {
- this.aclEnforcer = aclEnforcer;
- }
-
- @Column(name = "repo_type")
- public int getRepositoryType() {
- return this.repositoryType ;
- }
-
- public void setRepositoryType(int repositoryType) {
- this.repositoryType = repositoryType;
- }
-
- @Column(name = "repo_name")
- public String getRepositoryName() {
- return this.repositoryName;
- }
-
- public void setRepositoryName(String repositoryName) {
- this.repositoryName = repositoryName;
- }
-
- @Column(name = "session_id")
- public String getSessionId() {
- return this.sessionId;
- }
-
- public void setSessionId(String sessionId) {
- this.sessionId = sessionId;
- }
-
- @Column(name = "client_type")
- public String getClientType() {
- return this.clientType;
- }
-
- public void setClientType(String clientType) {
- this.clientType = clientType;
- }
-
- @Column(name = "client_ip")
- public String getClientIP() {
- return this.clientIP;
- }
-
- public void setClientIP(String clientIP) {
- this.clientIP = clientIP;
- }
-
- @Column(name = "action")
- public String getAction() {
- return this.action;
- }
-
- public void setAction(String action) {
- this.action = action;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/entity/XXBaseAuditEvent_.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/entity/XXBaseAuditEvent_.java b/agents-audit/src/main/java/com/xasecure/audit/entity/XXBaseAuditEvent_.java
deleted file mode 100644
index 953e513..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/entity/XXBaseAuditEvent_.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * 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 com.xasecure.audit.entity;
-
-import com.xasecure.audit.model.EnumRepositoryType;
-import java.util.Date;
-import javax.annotation.Generated;
-import javax.persistence.metamodel.SingularAttribute;
-import javax.persistence.metamodel.StaticMetamodel;
-
-@Generated(value="Dali", date="2014-02-04T07:25:42.940-0800")
-@StaticMetamodel(XXBaseAuditEvent.class)
-public class XXBaseAuditEvent_ {
- public static volatile SingularAttribute<XXBaseAuditEvent, Long> auditId;
- public static volatile SingularAttribute<XXBaseAuditEvent, String> agentId;
- public static volatile SingularAttribute<XXBaseAuditEvent, String> user;
- public static volatile SingularAttribute<XXBaseAuditEvent, Date> timeStamp;
- public static volatile SingularAttribute<XXBaseAuditEvent, Long> policyId;
- public static volatile SingularAttribute<XXBaseAuditEvent, String> accessType;
- public static volatile SingularAttribute<XXBaseAuditEvent, Short> accessResult;
- public static volatile SingularAttribute<XXBaseAuditEvent, String> resultReason;
- public static volatile SingularAttribute<XXBaseAuditEvent, String> aclEnforcer;
- public static volatile SingularAttribute<XXBaseAuditEvent, EnumRepositoryType> repositoryType;
- public static volatile SingularAttribute<XXBaseAuditEvent, String> repositoryName;
- public static volatile SingularAttribute<XXBaseAuditEvent, String> sessionId;
- public static volatile SingularAttribute<XXBaseAuditEvent, String> clientType;
- public static volatile SingularAttribute<XXBaseAuditEvent, String> clientIP;
- public static volatile SingularAttribute<XXBaseAuditEvent, String> action;
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/entity/XXHBaseAuditEvent.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/entity/XXHBaseAuditEvent.java b/agents-audit/src/main/java/com/xasecure/audit/entity/XXHBaseAuditEvent.java
deleted file mode 100644
index 0a02e7e..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/entity/XXHBaseAuditEvent.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * 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 com.xasecure.audit.entity;
-
-import java.io.Serializable;
-
-import javax.persistence.Column;
-import javax.persistence.DiscriminatorValue;
-import javax.persistence.Entity;
-
-import com.xasecure.audit.model.EnumRepositoryType;
-import com.xasecure.audit.model.HBaseAuditEvent;
-
-/**
- * Entity implementation class for Entity: XAHBaseAuditEvent
- *
- */
-@Entity
-@DiscriminatorValue("1")
-public class XXHBaseAuditEvent extends XXBaseAuditEvent implements Serializable {
- private static final long serialVersionUID = 1L;
-
- private String resourcePath;
- private String resourceType;
- private String requestData;
-
-
- public XXHBaseAuditEvent() {
- super();
- }
-
- public XXHBaseAuditEvent(HBaseAuditEvent event) {
- super(event);
-
- this.resourcePath = event.getResourcePath();
- this.resourceType = event.getResourceType();
- this.requestData = event.getRequestData();
- }
-
- @Column(name = "resource_path")
- public String getResourcePath() {
- return this.resourcePath;
- }
-
- public void setResourcePath(String resourcePath) {
- this.resourcePath = resourcePath;
- }
-
- @Column(name = "resource_type")
- public String getResourceType() {
- return this.resourceType;
- }
-
- public void setResourceType(String resourceType) {
- this.resourceType = resourceType;
- }
-
- @Column(name = "request_data")
- public String getRequestData() {
- return this.requestData;
- }
-
- public void setRequestData(String requestData) {
- this.requestData = requestData;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/entity/XXHBaseAuditEvent_.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/entity/XXHBaseAuditEvent_.java b/agents-audit/src/main/java/com/xasecure/audit/entity/XXHBaseAuditEvent_.java
deleted file mode 100644
index 03e704f..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/entity/XXHBaseAuditEvent_.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * 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 com.xasecure.audit.entity;
-
-import javax.annotation.Generated;
-import javax.persistence.metamodel.SingularAttribute;
-import javax.persistence.metamodel.StaticMetamodel;
-
-@Generated(value="Dali", date="2014-02-02T14:05:13.483-0800")
-@StaticMetamodel(XXHBaseAuditEvent.class)
-public class XXHBaseAuditEvent_ extends XXBaseAuditEvent_ {
- public static volatile SingularAttribute<XXHBaseAuditEvent, String> resourcePath;
- public static volatile SingularAttribute<XXHBaseAuditEvent, String> resourceType;
- public static volatile SingularAttribute<XXHBaseAuditEvent, String> requestData;
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/entity/XXHdfsAuditEvent.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/entity/XXHdfsAuditEvent.java b/agents-audit/src/main/java/com/xasecure/audit/entity/XXHdfsAuditEvent.java
deleted file mode 100644
index 3afc395..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/entity/XXHdfsAuditEvent.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * 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 com.xasecure.audit.entity;
-
-import java.io.Serializable;
-
-import javax.persistence.Column;
-import javax.persistence.DiscriminatorValue;
-import javax.persistence.Entity;
-import javax.persistence.Inheritance;
-import javax.persistence.InheritanceType;
-import javax.persistence.Table;
-
-import com.xasecure.audit.model.HdfsAuditEvent;
-
-/**
- * Entity implementation class for Entity: XXHdfsAuditEvent
- *
- */
-@Entity
-@DiscriminatorValue("2")
-public class XXHdfsAuditEvent extends XXBaseAuditEvent implements Serializable {
- private static final long serialVersionUID = 1L;
-
- private String resourcePath;
- private String resourceType;
-
-
- public XXHdfsAuditEvent() {
- super();
- }
-
- public XXHdfsAuditEvent(HdfsAuditEvent event) {
- super(event);
-
- this.resourcePath = event.getResourcePath();
- this.resourceType = event.getResourceType();
- }
-
- @Column(name = "resource_path")
- public String getResourcePath() {
- return this.resourcePath;
- }
-
- public void setResourcePath(String resourcePath) {
- this.resourcePath = resourcePath;
- }
-
- @Column(name = "resource_type")
- public String getResourceType() {
- return this.resourceType;
- }
-
- public void setResourceType(String resourceType) {
- this.resourceType = resourceType;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/entity/XXHdfsAuditEvent_.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/entity/XXHdfsAuditEvent_.java b/agents-audit/src/main/java/com/xasecure/audit/entity/XXHdfsAuditEvent_.java
deleted file mode 100644
index c7f2d71..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/entity/XXHdfsAuditEvent_.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * 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 com.xasecure.audit.entity;
-
-import javax.annotation.Generated;
-import javax.persistence.metamodel.SingularAttribute;
-import javax.persistence.metamodel.StaticMetamodel;
-
-@Generated(value="Dali", date="2014-02-02T14:05:13.489-0800")
-@StaticMetamodel(XXHdfsAuditEvent.class)
-public class XXHdfsAuditEvent_ extends XXBaseAuditEvent_ {
- public static volatile SingularAttribute<XXHdfsAuditEvent, String> resourcePath;
- public static volatile SingularAttribute<XXHdfsAuditEvent, String> resourceType;
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/entity/XXHiveAuditEvent.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/entity/XXHiveAuditEvent.java b/agents-audit/src/main/java/com/xasecure/audit/entity/XXHiveAuditEvent.java
deleted file mode 100644
index 4d0b12d..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/entity/XXHiveAuditEvent.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * 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 com.xasecure.audit.entity;
-
-import java.io.Serializable;
-
-import javax.persistence.Column;
-import javax.persistence.DiscriminatorValue;
-import javax.persistence.Entity;
-import javax.persistence.Inheritance;
-import javax.persistence.InheritanceType;
-import javax.persistence.Table;
-
-import com.xasecure.audit.model.HiveAuditEvent;
-
-/**
- * Entity implementation class for Entity: XXHiveAuditEvent
- *
- */
-@Entity
-@DiscriminatorValue("3")
-public class XXHiveAuditEvent extends XXBaseAuditEvent implements Serializable {
- private static final long serialVersionUID = 1L;
-
- private String resourcePath;
- private String resourceType;
- private String requestData;
-
-
- public XXHiveAuditEvent() {
- super();
- }
-
- public XXHiveAuditEvent(HiveAuditEvent event) {
- super(event);
-
- this.resourcePath = event.getResourcePath();
- this.resourceType = event.getResourceType();
- this.requestData = event.getRequestData();
- }
-
- @Column(name = "resource_path")
- public String getResourcePath() {
- return this.resourcePath;
- }
-
- public void setResourcePath(String resourcePath) {
- this.resourcePath = resourcePath;
- }
-
- @Column(name = "resource_type")
- public String getResourceType() {
- return this.resourceType;
- }
-
- public void setResourceType(String resourceType) {
- this.resourceType = resourceType;
- }
-
- @Column(name = "request_data")
- public String getRequestData() {
- return this.requestData;
- }
-
- public void setRequestData(String requestData) {
- this.requestData = requestData;
- }
-
-}
[20/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/entity/XXAsset.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/entity/XXAsset.java b/security-admin/src/main/java/com/xasecure/entity/XXAsset.java
deleted file mode 100644
index bd1652b..0000000
--- a/security-admin/src/main/java/com/xasecure/entity/XXAsset.java
+++ /dev/null
@@ -1,287 +0,0 @@
-/*
- * 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 com.xasecure.entity;
-
-/**
- * Asset
- *
- */
-
-import java.util.*;
-import javax.persistence.*;
-import javax.xml.bind.annotation.*;
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-
-
-@Entity
-@Table(name="x_asset")
-@XmlRootElement
-public class XXAsset extends XXDBBase implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
- @Id
- @SequenceGenerator(name="X_ASSET_SEQ",sequenceName="X_ASSET_SEQ",allocationSize=1)
- @GeneratedValue(strategy=GenerationType.AUTO,generator="X_ASSET_SEQ")
- @Column(name="ID")
- protected Long id;
-
- @Override
- public void setId(Long id) {
- this.id=id;
- }
- @Override
- public Long getId() {
- return id;
- }
- /**
- * Name
- * <ul>
- * <li>The maximum length for this attribute is <b>1024</b>.
- * </ul>
- *
- */
- @Column(name="ASSET_NAME" , nullable=false , length=1024)
- protected String name;
-
- /**
- * Description
- * <ul>
- * <li>The maximum length for this attribute is <b>4000</b>.
- * </ul>
- *
- */
- @Column(name="DESCR" , nullable=false , length=4000)
- protected String description;
-
- /**
- * Status
- * <ul>
- * <li>This attribute is of type enum CommonEnums::ActiveStatus
- * </ul>
- *
- */
- @Column(name="ACT_STATUS" , nullable=false )
- protected int activeStatus = XAConstants.STATUS_DISABLED;
-
- /**
- * Type of asset
- * <ul>
- * <li>This attribute is of type enum CommonEnums::AssetType
- * </ul>
- *
- */
- @Column(name="ASSET_TYPE" , nullable=false )
- protected int assetType = AppConstants.ASSET_UNKNOWN;
-
- /**
- * Config in json format
- * <ul>
- * <li>The maximum length for this attribute is <b>10000</b>.
- * </ul>
- *
- */
- @Column(name="CONFIG" , length=10000)
- protected String config;
-
- /**
- * Support native authorization
- * <ul>
- * </ul>
- *
- */
- @Column(name="SUP_NATIVE" , nullable=false )
- protected boolean supportNative = false;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public XXAsset ( ) {
- activeStatus = XAConstants.STATUS_DISABLED;
- assetType = AppConstants.ASSET_UNKNOWN;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_XA_ASSET;
- }
-
- @Override
- public String getMyDisplayValue() {
- return getDescription( );
- }
-
- /**
- * This method sets the value to the member attribute <b>name</b>.
- * You cannot set null to the attribute.
- * @param name Value to set member attribute <b>name</b>
- */
- public void setName( String name ) {
- this.name = name;
- }
-
- /**
- * Returns the value for the member attribute <b>name</b>
- * @return String - value of member attribute <b>name</b>.
- */
- public String getName( ) {
- return this.name;
- }
-
- /**
- * This method sets the value to the member attribute <b>description</b>.
- * You cannot set null to the attribute.
- * @param description Value to set member attribute <b>description</b>
- */
- public void setDescription( String description ) {
- this.description = description;
- }
-
- /**
- * Returns the value for the member attribute <b>description</b>
- * @return String - value of member attribute <b>description</b>.
- */
- public String getDescription( ) {
- return this.description;
- }
-
- /**
- * This method sets the value to the member attribute <b>activeStatus</b>.
- * You cannot set null to the attribute.
- * @param activeStatus Value to set member attribute <b>activeStatus</b>
- */
- public void setActiveStatus( int activeStatus ) {
- this.activeStatus = activeStatus;
- }
-
- /**
- * Returns the value for the member attribute <b>activeStatus</b>
- * @return int - value of member attribute <b>activeStatus</b>.
- */
- public int getActiveStatus( ) {
- return this.activeStatus;
- }
-
- /**
- * This method sets the value to the member attribute <b>assetType</b>.
- * You cannot set null to the attribute.
- * @param assetType Value to set member attribute <b>assetType</b>
- */
- public void setAssetType( int assetType ) {
- this.assetType = assetType;
- }
-
- /**
- * Returns the value for the member attribute <b>assetType</b>
- * @return int - value of member attribute <b>assetType</b>.
- */
- public int getAssetType( ) {
- return this.assetType;
- }
-
- /**
- * This method sets the value to the member attribute <b>config</b>.
- * You cannot set null to the attribute.
- * @param config Value to set member attribute <b>config</b>
- */
- public void setConfig( String config ) {
- this.config = config;
- }
-
- /**
- * Returns the value for the member attribute <b>config</b>
- * @return String - value of member attribute <b>config</b>.
- */
- public String getConfig( ) {
- return this.config;
- }
-
- /**
- * This method sets the value to the member attribute <b>supportNative</b>.
- * You cannot set null to the attribute.
- * @param supportNative Value to set member attribute <b>supportNative</b>
- */
- public void setSupportNative( boolean supportNative ) {
- this.supportNative = supportNative;
- }
-
- /**
- * Returns the value for the member attribute <b>supportNative</b>
- * @return boolean - value of member attribute <b>supportNative</b>.
- */
- public boolean isSupportNative( ) {
- return this.supportNative;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- @Override
- public String toString( ) {
- String str = "XXAsset={";
- str += super.toString();
- str += "name={" + name + "} ";
- str += "description={" + description + "} ";
- str += "activeStatus={" + activeStatus + "} ";
- str += "assetType={" + assetType + "} ";
- str += "config={" + config + "} ";
- str += "supportNative={" + supportNative + "} ";
- str += "}";
- return str;
- }
-
- /**
- * Checks for all attributes except referenced db objects
- * @return true if all attributes match
- */
- @Override
- public boolean equals( Object obj) {
- if ( !super.equals(obj) ) {
- return false;
- }
- XXAsset other = (XXAsset) obj;
- if ((this.name == null && other.name != null) || (this.name != null && !this.name.equals(other.name))) {
- return false;
- }
- if ((this.description == null && other.description != null) || (this.description != null && !this.description.equals(other.description))) {
- return false;
- }
- if( this.activeStatus != other.activeStatus ) return false;
- if( this.assetType != other.assetType ) return false;
- if ((this.config == null && other.config != null) || (this.config != null && !this.config.equals(other.config))) {
- return false;
- }
- if( this.supportNative != other.supportNative ) return false;
- return true;
- }
- public static String getEnumName(String fieldName ) {
- if( fieldName.equals("activeStatus") ) {
- return "CommonEnums.ActiveStatus";
- }
- if( fieldName.equals("assetType") ) {
- return "CommonEnums.AssetType";
- }
- //Later TODO
- //return super.getEnumName(fieldName);
- return null;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/entity/XXAuditMap.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/entity/XXAuditMap.java b/security-admin/src/main/java/com/xasecure/entity/XXAuditMap.java
deleted file mode 100644
index 900fc76..0000000
--- a/security-admin/src/main/java/com/xasecure/entity/XXAuditMap.java
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * 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 com.xasecure.entity;
-
-/**
- * Audi map
- *
- */
-
-import java.util.*;
-import javax.persistence.*;
-import javax.xml.bind.annotation.*;
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-
-
-@Entity
-@Table(name="x_audit_map")
-@XmlRootElement
-public class XXAuditMap extends XXDBBase implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- @Id
- @SequenceGenerator(name="X_AUDIT_MAP_SEQ",sequenceName="X_AUDIT_MAP_SEQ",allocationSize=1)
- @GeneratedValue(strategy=GenerationType.AUTO,generator="X_AUDIT_MAP_SEQ")
- @Column(name="ID")
- protected Long id;
- @Override
- public void setId(Long id) {
- this.id=id;
- }
-
- @Override
- public Long getId() {
- return id;
- }
-
- /**
- * Id of the resource
- * <ul>
- * </ul>
- *
- */
- @Column(name="RES_ID" )
- protected Long resourceId;
-
-
- /**
- * Id of the group
- * <ul>
- * </ul>
- *
- */
- @Column(name="GROUP_ID" )
- protected Long groupId;
-
-
- /**
- * Id of the user
- * <ul>
- * </ul>
- *
- */
- @Column(name="USER_ID" )
- protected Long userId;
-
-
- /**
- * Type of audit
- * <ul>
- * <li>This attribute is of type enum CommonEnums::XAAuditType
- * </ul>
- *
- */
- @Column(name="AUDIT_TYPE" , nullable=false )
- protected int auditType = AppConstants.XA_AUDIT_TYPE_UNKNOWN;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public XXAuditMap ( ) {
- auditType = AppConstants.XA_AUDIT_TYPE_UNKNOWN;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_XA_AUDIT_MAP;
- }
-
- /**
- * This method sets the value to the member attribute <b>resourceId</b>.
- * You cannot set null to the attribute.
- * @param resourceId Value to set member attribute <b>resourceId</b>
- */
- public void setResourceId( Long resourceId ) {
- this.resourceId = resourceId;
- }
-
- /**
- * Returns the value for the member attribute <b>resourceId</b>
- * @return Long - value of member attribute <b>resourceId</b>.
- */
- public Long getResourceId( ) {
- return this.resourceId;
- }
-
-
- /**
- * This method sets the value to the member attribute <b>groupId</b>.
- * You cannot set null to the attribute.
- * @param groupId Value to set member attribute <b>groupId</b>
- */
- public void setGroupId( Long groupId ) {
- this.groupId = groupId;
- }
-
- /**
- * Returns the value for the member attribute <b>groupId</b>
- * @return Long - value of member attribute <b>groupId</b>.
- */
- public Long getGroupId( ) {
- return this.groupId;
- }
-
-
- /**
- * This method sets the value to the member attribute <b>userId</b>.
- * You cannot set null to the attribute.
- * @param userId Value to set member attribute <b>userId</b>
- */
- public void setUserId( Long userId ) {
- this.userId = userId;
- }
-
- /**
- * Returns the value for the member attribute <b>userId</b>
- * @return Long - value of member attribute <b>userId</b>.
- */
- public Long getUserId( ) {
- return this.userId;
- }
-
-
- /**
- * This method sets the value to the member attribute <b>auditType</b>.
- * You cannot set null to the attribute.
- * @param auditType Value to set member attribute <b>auditType</b>
- */
- public void setAuditType( int auditType ) {
- this.auditType = auditType;
- }
-
- /**
- * Returns the value for the member attribute <b>auditType</b>
- * @return int - value of member attribute <b>auditType</b>.
- */
- public int getAuditType( ) {
- return this.auditType;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- @Override
- public String toString( ) {
- String str = "XXAuditMap={";
- str += super.toString();
- str += "resourceId={" + resourceId + "} ";
- str += "groupId={" + groupId + "} ";
- str += "userId={" + userId + "} ";
- str += "auditType={" + auditType + "} ";
- str += "}";
- return str;
- }
-
- /**
- * Checks for all attributes except referenced db objects
- * @return true if all attributes match
- */
- @Override
- public boolean equals( Object obj) {
- if ( !super.equals(obj) ) {
- return false;
- }
- XXAuditMap other = (XXAuditMap) obj;
- if ((this.resourceId == null && other.resourceId != null) || (this.resourceId != null && !this.resourceId.equals(other.resourceId))) {
- return false;
- }
- if ((this.groupId == null && other.groupId != null) || (this.groupId != null && !this.groupId.equals(other.groupId))) {
- return false;
- }
- if ((this.userId == null && other.userId != null) || (this.userId != null && !this.userId.equals(other.userId))) {
- return false;
- }
- if( this.auditType != other.auditType ) return false;
- return true;
- }
- public static String getEnumName(String fieldName ) {
- if( fieldName.equals("auditType") ) {
- return "CommonEnums.XAAuditType";
- }
- //Later TODO
- //return super.getEnumName(fieldName);
- return null;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/entity/XXAuthSession.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/entity/XXAuthSession.java b/security-admin/src/main/java/com/xasecure/entity/XXAuthSession.java
deleted file mode 100644
index d66fd07..0000000
--- a/security-admin/src/main/java/com/xasecure/entity/XXAuthSession.java
+++ /dev/null
@@ -1,470 +0,0 @@
-/*
- * 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 com.xasecure.entity;
-
-/**
- * Authentication session
- *
- */
-
-import java.util.*;
-import javax.persistence.*;
-import javax.xml.bind.annotation.*;
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-
-
-@Entity
-@Table(name="x_auth_sess")
-@XmlRootElement
-public class XXAuthSession extends XXDBBase implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
- @Id
- @SequenceGenerator(name="X_AUTH_SESS_SEQ",sequenceName="X_AUTH_SESS_SEQ",allocationSize=1)
- @GeneratedValue(strategy=GenerationType.AUTO,generator="X_AUTH_SESS_SEQ")
- @Column(name="ID")
- protected Long id;
- @Override
- public void setId(Long id) {
- this.id=id;
- }
-
- @Override
- public Long getId() {
- return id;
- }
- /**
- * Enum values for AuthStatus
- */
- /**
- * AUTH_STATUS_UNKNOWN is an element of enum AuthStatus. Its value is "AUTH_STATUS_UNKNOWN".
- */
- public static final int AUTH_STATUS_UNKNOWN = 0;
- /**
- * AUTH_STATUS_SUCCESS is an element of enum AuthStatus. Its value is "AUTH_STATUS_SUCCESS".
- */
- public static final int AUTH_STATUS_SUCCESS = 1;
- /**
- * AUTH_STATUS_WRONG_PASSWORD is an element of enum AuthStatus. Its value is "AUTH_STATUS_WRONG_PASSWORD".
- */
- public static final int AUTH_STATUS_WRONG_PASSWORD = 2;
- /**
- * AUTH_STATUS_DISABLED is an element of enum AuthStatus. Its value is "AUTH_STATUS_DISABLED".
- */
- public static final int AUTH_STATUS_DISABLED = 3;
- /**
- * AUTH_STATUS_LOCKED is an element of enum AuthStatus. Its value is "AUTH_STATUS_LOCKED".
- */
- public static final int AUTH_STATUS_LOCKED = 4;
- /**
- * AUTH_STATUS_PASSWORD_EXPIRED is an element of enum AuthStatus. Its value is "AUTH_STATUS_PASSWORD_EXPIRED".
- */
- public static final int AUTH_STATUS_PASSWORD_EXPIRED = 5;
- /**
- * AUTH_STATUS_USER_NOT_FOUND is an element of enum AuthStatus. Its value is "AUTH_STATUS_USER_NOT_FOUND".
- */
- public static final int AUTH_STATUS_USER_NOT_FOUND = 6;
-
- /**
- * Max value for enum AuthStatus_MAX
- */
- public static final int AuthStatus_MAX = 6;
-
- /**
- * Enum values for AuthType
- */
- /**
- * AUTH_TYPE_UNKNOWN is an element of enum AuthType. Its value is "AUTH_TYPE_UNKNOWN".
- */
- public static final int AUTH_TYPE_UNKNOWN = 0;
- /**
- * AUTH_TYPE_PASSWORD is an element of enum AuthType. Its value is "AUTH_TYPE_PASSWORD".
- */
- public static final int AUTH_TYPE_PASSWORD = 1;
-
- /**
- * Max value for enum AuthType_MAX
- */
- public static final int AuthType_MAX = 1;
-
-
-
- /**
- * Login ID of the user
- * <ul>
- * <li>The maximum length for this attribute is <b>767</b>.
- * </ul>
- *
- */
- @Column(name="LOGIN_ID" , nullable=false , length=767)
- protected String loginId;
-
- /**
- * Id of the user
- * <ul>
- * </ul>
- *
- */
- @Column(name="USER_ID" )
- protected Long userId;
-
-
- /**
- * External session id. Currently spring/http session
- * <ul>
- * <li>The maximum length for this attribute is <b>512</b>.
- * </ul>
- *
- */
- @Column(name="EXT_SESS_ID" , length=512)
- protected String extSessionId;
-
- /**
- * Date and time of authentication
- * <ul>
- * </ul>
- *
- */
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name="AUTH_TIME" , nullable=false )
- protected Date authTime = DateUtil.getUTCDate();
-
- /**
- * Authentication status
- * <ul>
- * <li>This attribute is of type enum XXAuthSession::AuthStatus
- * </ul>
- *
- */
- @Column(name="AUTH_STATUS" , nullable=false )
- protected int authStatus = AUTH_STATUS_UNKNOWN;
-
- /**
- * Authentication type
- * <ul>
- * <li>This attribute is of type enum XXAuthSession::AuthType
- * </ul>
- *
- */
- @Column(name="AUTH_TYPE" , nullable=false )
- protected int authType = AUTH_TYPE_UNKNOWN;
-
- /**
- * Authentication provider
- * <ul>
- * <li>This attribute is of type enum XXAuthSession::AuthType
- * </ul>
- *
- */
- @Column(name="AUTH_PROVIDER" , nullable=false )
- protected int authProvider = AUTH_TYPE_UNKNOWN;
-
- /**
- * Type of the device
- * <ul>
- * <li>This attribute is of type enum CommonEnums::DeviceType
- * </ul>
- *
- */
- @Column(name="DEVICE_TYPE" , nullable=false )
- protected int deviceType = XAConstants.DEVICE_UNKNOWN;
-
- /**
- * IP where the request came from
- * <ul>
- * <li>The maximum length for this attribute is <b>48</b>.
- * </ul>
- *
- */
- @Column(name="REQ_IP" , nullable=false , length=48)
- protected String requestIP;
-
- /**
- * UserAgent of the requesting device
- * <ul>
- * <li>The maximum length for this attribute is <b>1024</b>.
- * </ul>
- *
- */
- @Column(name="REQ_UA" , length=1024)
- protected String requestUserAgent;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public XXAuthSession ( ) {
- authStatus = AUTH_STATUS_UNKNOWN;
- authType = AUTH_TYPE_UNKNOWN;
- authProvider = AUTH_TYPE_UNKNOWN;
- deviceType = XAConstants.DEVICE_UNKNOWN;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_AUTH_SESS;
- }
-
- /**
- * This method sets the value to the member attribute <b>loginId</b>.
- * You cannot set null to the attribute.
- * @param loginId Value to set member attribute <b>loginId</b>
- */
- public void setLoginId( String loginId ) {
- this.loginId = loginId;
- }
-
- /**
- * Returns the value for the member attribute <b>loginId</b>
- * @return String - value of member attribute <b>loginId</b>.
- */
- public String getLoginId( ) {
- return this.loginId;
- }
-
- /**
- * This method sets the value to the member attribute <b>userId</b>.
- * You cannot set null to the attribute.
- * @param userId Value to set member attribute <b>userId</b>
- */
- public void setUserId( Long userId ) {
- this.userId = userId;
- }
-
- /**
- * Returns the value for the member attribute <b>userId</b>
- * @return Long - value of member attribute <b>userId</b>.
- */
- public Long getUserId( ) {
- return this.userId;
- }
-
-
- /**
- * This method sets the value to the member attribute <b>extSessionId</b>.
- * You cannot set null to the attribute.
- * @param extSessionId Value to set member attribute <b>extSessionId</b>
- */
- public void setExtSessionId( String extSessionId ) {
- this.extSessionId = extSessionId;
- }
-
- /**
- * Returns the value for the member attribute <b>extSessionId</b>
- * @return String - value of member attribute <b>extSessionId</b>.
- */
- public String getExtSessionId( ) {
- return this.extSessionId;
- }
-
- /**
- * This method sets the value to the member attribute <b>authTime</b>.
- * You cannot set null to the attribute.
- * @param authTime Value to set member attribute <b>authTime</b>
- */
- public void setAuthTime( Date authTime ) {
- this.authTime = authTime;
- }
-
- /**
- * Returns the value for the member attribute <b>authTime</b>
- * @return Date - value of member attribute <b>authTime</b>.
- */
- public Date getAuthTime( ) {
- return this.authTime;
- }
-
- /**
- * This method sets the value to the member attribute <b>authStatus</b>.
- * You cannot set null to the attribute.
- * @param authStatus Value to set member attribute <b>authStatus</b>
- */
- public void setAuthStatus( int authStatus ) {
- this.authStatus = authStatus;
- }
-
- /**
- * Returns the value for the member attribute <b>authStatus</b>
- * @return int - value of member attribute <b>authStatus</b>.
- */
- public int getAuthStatus( ) {
- return this.authStatus;
- }
-
- /**
- * This method sets the value to the member attribute <b>authType</b>.
- * You cannot set null to the attribute.
- * @param authType Value to set member attribute <b>authType</b>
- */
- public void setAuthType( int authType ) {
- this.authType = authType;
- }
-
- /**
- * Returns the value for the member attribute <b>authType</b>
- * @return int - value of member attribute <b>authType</b>.
- */
- public int getAuthType( ) {
- return this.authType;
- }
-
- /**
- * This method sets the value to the member attribute <b>authProvider</b>.
- * You cannot set null to the attribute.
- * @param authProvider Value to set member attribute <b>authProvider</b>
- */
- public void setAuthProvider( int authProvider ) {
- this.authProvider = authProvider;
- }
-
- /**
- * Returns the value for the member attribute <b>authProvider</b>
- * @return int - value of member attribute <b>authProvider</b>.
- */
- public int getAuthProvider( ) {
- return this.authProvider;
- }
-
- /**
- * This method sets the value to the member attribute <b>deviceType</b>.
- * You cannot set null to the attribute.
- * @param deviceType Value to set member attribute <b>deviceType</b>
- */
- public void setDeviceType( int deviceType ) {
- this.deviceType = deviceType;
- }
-
- /**
- * Returns the value for the member attribute <b>deviceType</b>
- * @return int - value of member attribute <b>deviceType</b>.
- */
- public int getDeviceType( ) {
- return this.deviceType;
- }
-
- /**
- * This method sets the value to the member attribute <b>requestIP</b>.
- * You cannot set null to the attribute.
- * @param requestIP Value to set member attribute <b>requestIP</b>
- */
- public void setRequestIP( String requestIP ) {
- this.requestIP = requestIP;
- }
-
- /**
- * Returns the value for the member attribute <b>requestIP</b>
- * @return String - value of member attribute <b>requestIP</b>.
- */
- public String getRequestIP( ) {
- return this.requestIP;
- }
-
- /**
- * This method sets the value to the member attribute <b>requestUserAgent</b>.
- * You cannot set null to the attribute.
- * @param requestUserAgent Value to set member attribute <b>requestUserAgent</b>
- */
- public void setRequestUserAgent( String requestUserAgent ) {
- this.requestUserAgent = requestUserAgent;
- }
-
- /**
- * Returns the value for the member attribute <b>requestUserAgent</b>
- * @return String - value of member attribute <b>requestUserAgent</b>.
- */
- public String getRequestUserAgent( ) {
- return this.requestUserAgent;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- @Override
- public String toString( ) {
- String str = "XXAuthSession={";
- str += super.toString();
- str += "loginId={" + loginId + "} ";
- str += "userId={" + userId + "} ";
- str += "extSessionId={" + extSessionId + "} ";
- str += "authTime={" + authTime + "} ";
- str += "authStatus={" + authStatus + "} ";
- str += "authType={" + authType + "} ";
- str += "authProvider={" + authProvider + "} ";
- str += "deviceType={" + deviceType + "} ";
- str += "requestIP={" + requestIP + "} ";
- str += "requestUserAgent={" + requestUserAgent + "} ";
- str += "}";
- return str;
- }
-
- /**
- * Checks for all attributes except referenced db objects
- * @return true if all attributes match
- */
- @Override
- public boolean equals( Object obj) {
- if ( !super.equals(obj) ) {
- return false;
- }
- XXAuthSession other = (XXAuthSession) obj;
- if ((this.loginId == null && other.loginId != null) || (this.loginId != null && !this.loginId.equals(other.loginId))) {
- return false;
- }
- if ((this.userId == null && other.userId != null) || (this.userId != null && !this.userId.equals(other.userId))) {
- return false;
- }
- if ((this.extSessionId == null && other.extSessionId != null) || (this.extSessionId != null && !this.extSessionId.equals(other.extSessionId))) {
- return false;
- }
- if ((this.authTime == null && other.authTime != null) || (this.authTime != null && !this.authTime.equals(other.authTime))) {
- return false;
- }
- if( this.authStatus != other.authStatus ) return false;
- if( this.authType != other.authType ) return false;
- if( this.authProvider != other.authProvider ) return false;
- if( this.deviceType != other.deviceType ) return false;
- if ((this.requestIP == null && other.requestIP != null) || (this.requestIP != null && !this.requestIP.equals(other.requestIP))) {
- return false;
- }
- if ((this.requestUserAgent == null && other.requestUserAgent != null) || (this.requestUserAgent != null && !this.requestUserAgent.equals(other.requestUserAgent))) {
- return false;
- }
- return true;
- }
- public static String getEnumName(String fieldName ) {
- if( fieldName.equals("authStatus") ) {
- return "CommonEnums.AuthStatus";
- }
- if( fieldName.equals("authType") ) {
- return "CommonEnums.AuthType";
- }
- if( fieldName.equals("authProvider") ) {
- return "CommonEnums.AuthType";
- }
- if( fieldName.equals("deviceType") ) {
- return "CommonEnums.DeviceType";
- }
- //Later TODO
- //return super.getEnumName(fieldName);
- return null;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/entity/XXCredentialStore.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/entity/XXCredentialStore.java b/security-admin/src/main/java/com/xasecure/entity/XXCredentialStore.java
deleted file mode 100644
index c884421..0000000
--- a/security-admin/src/main/java/com/xasecure/entity/XXCredentialStore.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * 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 com.xasecure.entity;
-
-/**
- * Credential Store
- *
- */
-
-import java.util.*;
-import javax.persistence.*;
-import javax.xml.bind.annotation.*;
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-
-
-@Entity
-@Table(name="x_cred_store")
-@XmlRootElement
-public class XXCredentialStore extends XXDBBase implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
- @Id
- @SequenceGenerator(name="X_CRED_STORE_SEQ",sequenceName="X_CRED_STORE_SEQ",allocationSize=1)
- @GeneratedValue(strategy=GenerationType.AUTO,generator="X_CRED_STORE_SEQ")
- @Column(name="ID")
- protected Long id;
-
- @Override
- public void setId(Long id) {
- this.id=id;
- }
- @Override
- public Long getId() {
- return id;
- }
- /**
- * Name
- * <ul>
- * <li>The maximum length for this attribute is <b>1024</b>.
- * </ul>
- *
- */
- @Column(name="STORE_NAME" , nullable=false , length=1024)
- protected String name;
-
- /**
- * Description
- * <ul>
- * <li>The maximum length for this attribute is <b>4000</b>.
- * </ul>
- *
- */
- @Column(name="DESCR" , nullable=false , length=4000)
- protected String description;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public XXCredentialStore ( ) {
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_XA_CRED_STORE;
- }
-
- @Override
- public String getMyDisplayValue() {
- return getDescription( );
- }
-
- /**
- * This method sets the value to the member attribute <b>name</b>.
- * You cannot set null to the attribute.
- * @param name Value to set member attribute <b>name</b>
- */
- public void setName( String name ) {
- this.name = name;
- }
-
- /**
- * Returns the value for the member attribute <b>name</b>
- * @return String - value of member attribute <b>name</b>.
- */
- public String getName( ) {
- return this.name;
- }
-
- /**
- * This method sets the value to the member attribute <b>description</b>.
- * You cannot set null to the attribute.
- * @param description Value to set member attribute <b>description</b>
- */
- public void setDescription( String description ) {
- this.description = description;
- }
-
- /**
- * Returns the value for the member attribute <b>description</b>
- * @return String - value of member attribute <b>description</b>.
- */
- public String getDescription( ) {
- return this.description;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- @Override
- public String toString( ) {
- String str = "XXCredentialStore={";
- str += super.toString();
- str += "name={" + name + "} ";
- str += "description={" + description + "} ";
- str += "}";
- return str;
- }
-
- /**
- * Checks for all attributes except referenced db objects
- * @return true if all attributes match
- */
- @Override
- public boolean equals( Object obj) {
- if ( !super.equals(obj) ) {
- return false;
- }
- XXCredentialStore other = (XXCredentialStore) obj;
- if ((this.name == null && other.name != null) || (this.name != null && !this.name.equals(other.name))) {
- return false;
- }
- if ((this.description == null && other.description != null) || (this.description != null && !this.description.equals(other.description))) {
- return false;
- }
- return true;
- }
- public static String getEnumName(String fieldName ) {
- //Later TODO
- //return super.getEnumName(fieldName);
- return null;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/entity/XXDBBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/entity/XXDBBase.java b/security-admin/src/main/java/com/xasecure/entity/XXDBBase.java
deleted file mode 100644
index b6d2d3c..0000000
--- a/security-admin/src/main/java/com/xasecure/entity/XXDBBase.java
+++ /dev/null
@@ -1,232 +0,0 @@
-/*
- * 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 com.xasecure.entity;
-
-/**
- * Base JPA class with id, versionNumber and other common attributes
- *
- */
-
-import java.util.*;
-import javax.persistence.*;
-import javax.xml.bind.annotation.*;
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-
-
-@MappedSuperclass @EntityListeners( com.xasecure.common.db.JPABeanCallbacks.class)
-@XmlRootElement
-public abstract class XXDBBase extends Object implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
-
- /**
- * Id for the object
- * <ul>
- * <li>This attribute is the <b>Primary Key</b> for this class<br>.
- * </ul>
- *
- */
-
- /**
- * Date/Time creation of this user.
- * <ul>
- * </ul>
- *
- */
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name="CREATE_TIME" )
- protected Date createTime = DateUtil.getUTCDate();
-
- /**
- * Date value.
- * <ul>
- * </ul>
- *
- */
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name="UPDATE_TIME" )
- protected Date updateTime = DateUtil.getUTCDate();
-
- /**
- * Added by
- * <ul>
- * </ul>
- *
- */
- @Column(name="ADDED_BY_ID" )
- protected Long addedByUserId;
-
-
- /**
- * Last updated by
- * <ul>
- * </ul>
- *
- */
- @Column(name="UPD_BY_ID" )
- protected Long updatedByUserId;
-
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public XXDBBase ( ) {
- }
-
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_NONE;
- }
-
- public String getMyDisplayValue() {
- return null;
- }
-
- /**
- * This method sets the value to the member attribute <b>id</b>.
- * You cannot set null to the attribute.
- * @param id Value to set member attribute <b>id</b>
- */
- public abstract void setId( Long id ) ;
-
- /**
- * Returns the value for the member attribute <b>id</b>
- * @return Long - value of member attribute <b>id</b>.
- */
- public abstract Long getId( );
-
- /**
- * This method sets the value to the member attribute <b>createTime</b>.
- * You cannot set null to the attribute.
- * @param createTime Value to set member attribute <b>createTime</b>
- */
- public void setCreateTime( Date createTime ) {
- this.createTime = createTime;
- }
-
- /**
- * Returns the value for the member attribute <b>createTime</b>
- * @return Date - value of member attribute <b>createTime</b>.
- */
- public Date getCreateTime( ) {
- return this.createTime;
- }
-
- /**
- * This method sets the value to the member attribute <b>updateTime</b>.
- * You cannot set null to the attribute.
- * @param updateTime Value to set member attribute <b>updateTime</b>
- */
- public void setUpdateTime( Date updateTime ) {
- this.updateTime = updateTime;
- }
-
- /**
- * Returns the value for the member attribute <b>updateTime</b>
- * @return Date - value of member attribute <b>updateTime</b>.
- */
- public Date getUpdateTime( ) {
- return this.updateTime;
- }
-
- /**
- * This method sets the value to the member attribute <b>addedByUserId</b>.
- * You cannot set null to the attribute.
- * @param addedByUserId Value to set member attribute <b>addedByUserId</b>
- */
- public void setAddedByUserId( Long addedByUserId ) {
- this.addedByUserId = addedByUserId;
- }
-
- /**
- * Returns the value for the member attribute <b>addedByUserId</b>
- * @return Long - value of member attribute <b>addedByUserId</b>.
- */
- public Long getAddedByUserId( ) {
- return this.addedByUserId;
- }
-
-
- /**
- * This method sets the value to the member attribute <b>updatedByUserId</b>.
- * You cannot set null to the attribute.
- * @param updatedByUserId Value to set member attribute <b>updatedByUserId</b>
- */
- public void setUpdatedByUserId( Long updatedByUserId ) {
- this.updatedByUserId = updatedByUserId;
- }
-
- /**
- * Returns the value for the member attribute <b>updatedByUserId</b>
- * @return Long - value of member attribute <b>updatedByUserId</b>.
- */
- public Long getUpdatedByUserId( ) {
- return this.updatedByUserId;
- }
-
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- @Override
- public String toString( ) {
- String str = "XXDBBase={";
- //`str += "id={" + id + "} ";
- str += "createTime={" + createTime + "} ";
- str += "updateTime={" + updateTime + "} ";
- str += "addedByUserId={" + addedByUserId + "} ";
- str += "updatedByUserId={" + updatedByUserId + "} ";
- str += "}";
- return str;
- }
-
- /**
- * Checks for all attributes except referenced db objects
- * @return true if all attributes match
- */
- @Override
- public boolean equals( Object obj) {
- XXDBBase other = (XXDBBase) obj;
-// if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
-// return false;
-// }
- if ((this.createTime == null && other.createTime != null) || (this.createTime != null && !this.createTime.equals(other.createTime))) {
- return false;
- }
- if ((this.updateTime == null && other.updateTime != null) || (this.updateTime != null && !this.updateTime.equals(other.updateTime))) {
- return false;
- }
- if ((this.addedByUserId == null && other.addedByUserId != null) || (this.addedByUserId != null && !this.addedByUserId.equals(other.addedByUserId))) {
- return false;
- }
- if ((this.updatedByUserId == null && other.updatedByUserId != null) || (this.updatedByUserId != null && !this.updatedByUserId.equals(other.updatedByUserId))) {
- return false;
- }
- return true;
- }
- public static String getEnumName(String fieldName ) {
- //Later TODO
- //return super.getEnumName(fieldName);
- return null;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/entity/XXGroup.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/entity/XXGroup.java b/security-admin/src/main/java/com/xasecure/entity/XXGroup.java
deleted file mode 100644
index 64d8e56..0000000
--- a/security-admin/src/main/java/com/xasecure/entity/XXGroup.java
+++ /dev/null
@@ -1,273 +0,0 @@
-/*
- * 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 com.xasecure.entity;
-
-/**
- * Group
- *
- */
-
-import java.util.*;
-import javax.persistence.*;
-import javax.xml.bind.annotation.*;
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-
-
-@Entity
-@Table(name="x_group")
-@XmlRootElement
-public class XXGroup extends XXDBBase implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
- @Id
- @SequenceGenerator(name="X_GROUP_SEQ",sequenceName="X_GROUP_SEQ",allocationSize=1)
- @GeneratedValue(strategy=GenerationType.AUTO,generator="X_GROUP_SEQ")
- @Column(name="ID")
- protected Long id;
- @Override
- public void setId(Long id) {
- this.id=id;
- }
- @Override
- public Long getId() {
- return id;
- }
- /**
- * Name
- * <ul>
- * <li>The maximum length for this attribute is <b>1024</b>.
- * </ul>
- *
- */
- @Column(name="GROUP_NAME" , nullable=false , length=1024)
- protected String name;
-
- /**
- * Description
- * <ul>
- * <li>The maximum length for this attribute is <b>4000</b>.
- * </ul>
- *
- */
- @Column(name="DESCR" , nullable=false , length=4000)
- protected String description;
-
- /**
- * Status
- * <ul>
- * <li>This attribute is of type enum CommonEnums::ActiveStatus
- * </ul>
- *
- */
- @Column(name="STATUS" , nullable=false )
- protected int status = XAConstants.STATUS_DISABLED;
-
- /**
- * Type of group
- * <ul>
- * <li>This attribute is of type enum CommonEnums::XAGroupType
- * </ul>
- *
- */
- @Column(name="GROUP_TYPE" , nullable=false )
- protected int groupType = AppConstants.XA_GROUP_UNKNOWN;
-
- @Column(name="GROUP_SRC" , nullable=false )
- protected int groupSource = XACommonEnums.GROUP_INTERNAL;
-
- /**
- * Id of the credential store
- * <ul>
- * </ul>
- *
- */
- @Column(name="CRED_STORE_ID" )
- protected Long credStoreId;
-
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public XXGroup ( ) {
- status = XAConstants.STATUS_DISABLED;
- groupType = AppConstants.XA_GROUP_UNKNOWN;
- groupSource = XACommonEnums.GROUP_INTERNAL;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_XA_GROUP;
- }
-
- @Override
- public String getMyDisplayValue() {
- return getDescription( );
- }
-
- /**
- * This method sets the value to the member attribute <b>name</b>.
- * You cannot set null to the attribute.
- * @param name Value to set member attribute <b>name</b>
- */
- public void setName( String name ) {
- this.name = name;
- }
-
- /**
- * Returns the value for the member attribute <b>name</b>
- * @return String - value of member attribute <b>name</b>.
- */
- public String getName( ) {
- return this.name;
- }
-
- /**
- * This method sets the value to the member attribute <b>description</b>.
- * You cannot set null to the attribute.
- * @param description Value to set member attribute <b>description</b>
- */
- public void setDescription( String description ) {
- this.description = description;
- }
-
- /**
- * Returns the value for the member attribute <b>description</b>
- * @return String - value of member attribute <b>description</b>.
- */
- public String getDescription( ) {
- return this.description;
- }
-
- /**
- * This method sets the value to the member attribute <b>status</b>.
- * You cannot set null to the attribute.
- * @param status Value to set member attribute <b>status</b>
- */
- public void setStatus( int status ) {
- this.status = status;
- }
-
- /**
- * Returns the value for the member attribute <b>status</b>
- * @return int - value of member attribute <b>status</b>.
- */
- public int getStatus( ) {
- return this.status;
- }
-
- /**
- * This method sets the value to the member attribute <b>groupType</b>.
- * You cannot set null to the attribute.
- * @param groupType Value to set member attribute <b>groupType</b>
- */
- public void setGroupType( int groupType ) {
- this.groupType = groupType;
- }
-
- /**
- * Returns the value for the member attribute <b>groupType</b>
- * @return int - value of member attribute <b>groupType</b>.
- */
- public int getGroupType( ) {
- return this.groupType;
- }
-
- /**
- * This method sets the value to the member attribute <b>credStoreId</b>.
- * You cannot set null to the attribute.
- * @param credStoreId Value to set member attribute <b>credStoreId</b>
- */
- public void setCredStoreId( Long credStoreId ) {
- this.credStoreId = credStoreId;
- }
-
- /**
- * Returns the value for the member attribute <b>credStoreId</b>
- * @return Long - value of member attribute <b>credStoreId</b>.
- */
- public Long getCredStoreId( ) {
- return this.credStoreId;
- }
-
-
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- @Override
- public String toString( ) {
- String str = "XXGroup={";
- str += super.toString();
- str += "name={" + name + "} ";
- str += "description={" + description + "} ";
- str += "status={" + status + "} ";
- str += "groupType={" + groupType + "} ";
- str += "credStoreId={" + credStoreId + "} ";
- str += "groupSrc={" + groupSource + "} ";
- str += "}";
- return str;
- }
-
- public int getGroupSource() {
- return groupSource;
- }
-
- public void setGroupSource(int groupSource) {
- this.groupSource = groupSource;
- }
-
- /**
- * Checks for all attributes except referenced db objects
- * @return true if all attributes match
- */
- @Override
- public boolean equals( Object obj) {
- if ( !super.equals(obj) ) {
- return false;
- }
- XXGroup other = (XXGroup) obj;
- if ((this.name == null && other.name != null) || (this.name != null && !this.name.equals(other.name))) {
- return false;
- }
- if ((this.description == null && other.description != null) || (this.description != null && !this.description.equals(other.description))) {
- return false;
- }
- if( this.status != other.status ) return false;
- if( this.groupType != other.groupType ) return false;
- if ((this.credStoreId == null && other.credStoreId != null) || (this.credStoreId != null && !this.credStoreId.equals(other.credStoreId))) {
- return false;
- }
- return true;
- }
- public static String getEnumName(String fieldName ) {
- if( fieldName.equals("status") ) {
- return "CommonEnums.ActiveStatus";
- }
- if( fieldName.equals("groupType") ) {
- return "CommonEnums.XAGroupType";
- }
- //Later TODO
- //return super.getEnumName(fieldName);
- return null;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/entity/XXGroupGroup.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/entity/XXGroupGroup.java b/security-admin/src/main/java/com/xasecure/entity/XXGroupGroup.java
deleted file mode 100644
index 9c096eb..0000000
--- a/security-admin/src/main/java/com/xasecure/entity/XXGroupGroup.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * 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 com.xasecure.entity;
-
-/**
- * Group of groups
- *
- */
-
-import java.util.*;
-import javax.persistence.*;
-import javax.xml.bind.annotation.*;
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-
-
-@Entity
-@Table(name="x_group_groups")
-@XmlRootElement
-public class XXGroupGroup extends XXDBBase implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
- @Id
- @SequenceGenerator(name="X_GROUP_GROUPS_SEQ",sequenceName="X_GROUP_GROUPS_SEQ",allocationSize=1)
- @GeneratedValue(strategy=GenerationType.AUTO,generator="X_GROUP_GROUPS_SEQ")
- @Column(name="ID")
- protected Long id;
- @Override
- public void setId(Long id) {
- this.id=id;
- }
- @Override
- public Long getId() {
- return id;
- }
- /**
- * Name
- * <ul>
- * <li>The maximum length for this attribute is <b>1024</b>.
- * </ul>
- *
- */
- @Column(name="GROUP_NAME" , nullable=false , length=1024)
- protected String name;
-
- /**
- * Id of the parent group
- * <ul>
- * </ul>
- *
- */
- @Column(name="P_GROUP_ID" )
- protected Long parentGroupId;
-
-
- /**
- * Id of the group
- * <ul>
- * </ul>
- *
- */
- @Column(name="GROUP_ID" )
- protected Long groupId;
-
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public XXGroupGroup ( ) {
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_XA_GROUP_GROUP;
- }
-
- @Override
- public String getMyDisplayValue() {
- return getName( );
- }
-
- /**
- * This method sets the value to the member attribute <b>name</b>.
- * You cannot set null to the attribute.
- * @param name Value to set member attribute <b>name</b>
- */
- public void setName( String name ) {
- this.name = name;
- }
-
- /**
- * Returns the value for the member attribute <b>name</b>
- * @return String - value of member attribute <b>name</b>.
- */
- public String getName( ) {
- return this.name;
- }
-
- /**
- * This method sets the value to the member attribute <b>parentGroupId</b>.
- * You cannot set null to the attribute.
- * @param parentGroupId Value to set member attribute <b>parentGroupId</b>
- */
- public void setParentGroupId( Long parentGroupId ) {
- this.parentGroupId = parentGroupId;
- }
-
- /**
- * Returns the value for the member attribute <b>parentGroupId</b>
- * @return Long - value of member attribute <b>parentGroupId</b>.
- */
- public Long getParentGroupId( ) {
- return this.parentGroupId;
- }
-
-
- /**
- * This method sets the value to the member attribute <b>groupId</b>.
- * You cannot set null to the attribute.
- * @param groupId Value to set member attribute <b>groupId</b>
- */
- public void setGroupId( Long groupId ) {
- this.groupId = groupId;
- }
-
- /**
- * Returns the value for the member attribute <b>groupId</b>
- * @return Long - value of member attribute <b>groupId</b>.
- */
- public Long getGroupId( ) {
- return this.groupId;
- }
-
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- @Override
- public String toString( ) {
- String str = "XXGroupGroup={";
- str += super.toString();
- str += "name={" + name + "} ";
- str += "parentGroupId={" + parentGroupId + "} ";
- str += "groupId={" + groupId + "} ";
- str += "}";
- return str;
- }
-
- /**
- * Checks for all attributes except referenced db objects
- * @return true if all attributes match
- */
- @Override
- public boolean equals( Object obj) {
- if ( !super.equals(obj) ) {
- return false;
- }
- XXGroupGroup other = (XXGroupGroup) obj;
- if ((this.name == null && other.name != null) || (this.name != null && !this.name.equals(other.name))) {
- return false;
- }
- if ((this.parentGroupId == null && other.parentGroupId != null) || (this.parentGroupId != null && !this.parentGroupId.equals(other.parentGroupId))) {
- return false;
- }
- if ((this.groupId == null && other.groupId != null) || (this.groupId != null && !this.groupId.equals(other.groupId))) {
- return false;
- }
- return true;
- }
- public static String getEnumName(String fieldName ) {
- //Later TODO
- //return super.getEnumName(fieldName);
- return null;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/entity/XXGroupUser.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/entity/XXGroupUser.java b/security-admin/src/main/java/com/xasecure/entity/XXGroupUser.java
deleted file mode 100644
index d8231e3..0000000
--- a/security-admin/src/main/java/com/xasecure/entity/XXGroupUser.java
+++ /dev/null
@@ -1,197 +0,0 @@
-/*
- * 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 com.xasecure.entity;
-
-/**
- * Group of users
- *
- */
-
-import java.util.*;
-import javax.persistence.*;
-import javax.xml.bind.annotation.*;
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-
-
-@Entity
-@Table(name="x_group_users")
-@XmlRootElement
-public class XXGroupUser extends XXDBBase implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- @Id
- @SequenceGenerator(name="X_GROUP_USERS_SEQ",sequenceName="X_GROUP_USERS_SEQ",allocationSize=1)
- @GeneratedValue(strategy=GenerationType.AUTO,generator="X_GROUP_USERS_SEQ")
- @Column(name="ID")
- protected Long id;
- @Override
- public void setId(Long id) {
- this.id=id;
- }
-
- @Override
- public Long getId() {
- return id;
- }
-
- /**
- * Name
- * <ul>
- * <li>The maximum length for this attribute is <b>1024</b>.
- * </ul>
- *
- */
- @Column(name="GROUP_NAME" , nullable=false , length=1024)
- protected String name;
-
- /**
- * Id of the group
- * <ul>
- * </ul>
- *
- */
- @Column(name="P_GROUP_ID" )
- protected Long parentGroupId;
-
-
- /**
- * Id of the user
- * <ul>
- * </ul>
- *
- */
- @Column(name="USER_ID" )
- protected Long userId;
-
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public XXGroupUser ( ) {
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_XA_GROUP_USER;
- }
-
- @Override
- public String getMyDisplayValue() {
- return getName( );
- }
-
- /**
- * This method sets the value to the member attribute <b>name</b>.
- * You cannot set null to the attribute.
- * @param name Value to set member attribute <b>name</b>
- */
- public void setName( String name ) {
- this.name = name;
- }
-
- /**
- * Returns the value for the member attribute <b>name</b>
- * @return String - value of member attribute <b>name</b>.
- */
- public String getName( ) {
- return this.name;
- }
-
- /**
- * This method sets the value to the member attribute <b>parentGroupId</b>.
- * You cannot set null to the attribute.
- * @param parentGroupId Value to set member attribute <b>parentGroupId</b>
- */
- public void setParentGroupId( Long parentGroupId ) {
- this.parentGroupId = parentGroupId;
- }
-
- /**
- * Returns the value for the member attribute <b>parentGroupId</b>
- * @return Long - value of member attribute <b>parentGroupId</b>.
- */
- public Long getParentGroupId( ) {
- return this.parentGroupId;
- }
-
-
- /**
- * This method sets the value to the member attribute <b>userId</b>.
- * You cannot set null to the attribute.
- * @param userId Value to set member attribute <b>userId</b>
- */
- public void setUserId( Long userId ) {
- this.userId = userId;
- }
-
- /**
- * Returns the value for the member attribute <b>userId</b>
- * @return Long - value of member attribute <b>userId</b>.
- */
- public Long getUserId( ) {
- return this.userId;
- }
-
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- @Override
- public String toString( ) {
- String str = "XXGroupUser={";
- str += super.toString();
- str += "name={" + name + "} ";
- str += "parentGroupId={" + parentGroupId + "} ";
- str += "userId={" + userId + "} ";
- str += "}";
- return str;
- }
-
- /**
- * Checks for all attributes except referenced db objects
- * @return true if all attributes match
- */
- @Override
- public boolean equals( Object obj) {
- if ( !super.equals(obj) ) {
- return false;
- }
- XXGroupUser other = (XXGroupUser) obj;
- if ((this.name == null && other.name != null) || (this.name != null && !this.name.equals(other.name))) {
- return false;
- }
- if ((this.parentGroupId == null && other.parentGroupId != null) || (this.parentGroupId != null && !this.parentGroupId.equals(other.parentGroupId))) {
- return false;
- }
- if ((this.userId == null && other.userId != null) || (this.userId != null && !this.userId.equals(other.userId))) {
- return false;
- }
- return true;
- }
- public static String getEnumName(String fieldName ) {
- //Later TODO
- //return super.getEnumName(fieldName);
- return null;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/entity/XXPermMap.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/entity/XXPermMap.java b/security-admin/src/main/java/com/xasecure/entity/XXPermMap.java
deleted file mode 100644
index e211198..0000000
--- a/security-admin/src/main/java/com/xasecure/entity/XXPermMap.java
+++ /dev/null
@@ -1,396 +0,0 @@
-/*
- * 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 com.xasecure.entity;
-
-/**
- * Permission map
- *
- */
-
-import java.util.*;
-import javax.persistence.*;
-import javax.xml.bind.annotation.*;
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-
-
-@Entity
-@Table(name="x_perm_map")
-@XmlRootElement
-public class XXPermMap extends XXDBBase implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- @Id
- @SequenceGenerator(name="X_PERM_MAP_SEQ",sequenceName="X_PERM_MAP_SEQ",allocationSize=1)
- @GeneratedValue(strategy=GenerationType.AUTO,generator="X_PERM_MAP_SEQ")
- @Column(name="ID")
- protected Long id;
- @Override
- public void setId(Long id) {
- this.id=id;
- }
-
- @Override
- public Long getId() {
- return id;
- }
-
- /**
- * Group to which the permission belongs to
- * <ul>
- * <li>The maximum length for this attribute is <b>1024</b>.
- * </ul>
- *
- */
- @Column(name="PERM_GROUP" , length=1024)
- protected String permGroup;
-
- /**
- * Id of the resource
- * <ul>
- * </ul>
- *
- */
- @Column(name="RES_ID" )
- protected Long resourceId;
-
-
- /**
- * Id of the group
- * <ul>
- * </ul>
- *
- */
- @Column(name="GROUP_ID" )
- protected Long groupId;
-
-
- /**
- * Id of the user
- * <ul>
- * </ul>
- *
- */
- @Column(name="USER_ID" )
- protected Long userId;
-
-
- /**
- * Permission for user or group
- * <ul>
- * <li>This attribute is of type enum CommonEnums::XAPermForType
- * </ul>
- *
- */
- @Column(name="PERM_FOR" , nullable=false )
- protected int permFor = AppConstants.XA_PERM_FOR_UNKNOWN;
-
- /**
- * Type of permission
- * <ul>
- * <li>This attribute is of type enum CommonEnums::XAPermType
- * </ul>
- *
- */
- @Column(name="PERM_TYPE" , nullable=false )
- protected int permType = AppConstants.XA_PERM_TYPE_UNKNOWN;
-
- /**
- * Is recursive
- * <ul>
- * <li>This attribute is of type enum CommonEnums::BooleanValue
- * </ul>
- *
- */
- @Column(name="IS_RECURSIVE" , nullable=false )
- protected int isRecursive = XAConstants.BOOL_NONE;
-
- /**
- * Is wild card
- * <ul>
- * </ul>
- *
- */
- @Column(name="IS_WILD_CARD" , nullable=false )
- protected boolean isWildCard = true;
-
- /**
- * Grant is true and revoke is false
- * <ul>
- * </ul>
- *
- */
- @Column(name="GRANT_REVOKE" , nullable=false )
- protected boolean grantOrRevoke = true;
- /**
- * IP address to which the group belongs to
- * <ul>
- * <li>The maximum length for this attribute is <b>1024</b>.
- * </ul>
- *
- */
- @Column(name="IP_ADDRESS" , length=1024)
- protected String ipAddress;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public XXPermMap ( ) {
- permFor = AppConstants.XA_PERM_FOR_UNKNOWN;
- permType = AppConstants.XA_PERM_TYPE_UNKNOWN;
- isRecursive = XAConstants.BOOL_NONE;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_XA_PERM_MAP;
- }
-
- /**
- * This method sets the value to the member attribute <b>permGroup</b>.
- * You cannot set null to the attribute.
- * @param permGroup Value to set member attribute <b>permGroup</b>
- */
- public void setPermGroup( String permGroup ) {
- this.permGroup = permGroup;
- }
-
- /**
- * Returns the value for the member attribute <b>permGroup</b>
- * @return String - value of member attribute <b>permGroup</b>.
- */
- public String getPermGroup( ) {
- return this.permGroup;
- }
-
- /**
- * This method sets the value to the member attribute <b>resourceId</b>.
- * You cannot set null to the attribute.
- * @param resourceId Value to set member attribute <b>resourceId</b>
- */
- public void setResourceId( Long resourceId ) {
- this.resourceId = resourceId;
- }
-
- /**
- * Returns the value for the member attribute <b>resourceId</b>
- * @return Long - value of member attribute <b>resourceId</b>.
- */
- public Long getResourceId( ) {
- return this.resourceId;
- }
-
-
- /**
- * This method sets the value to the member attribute <b>groupId</b>.
- * You cannot set null to the attribute.
- * @param groupId Value to set member attribute <b>groupId</b>
- */
- public void setGroupId( Long groupId ) {
- this.groupId = groupId;
- }
-
- /**
- * Returns the value for the member attribute <b>groupId</b>
- * @return Long - value of member attribute <b>groupId</b>.
- */
- public Long getGroupId( ) {
- return this.groupId;
- }
-
-
- /**
- * This method sets the value to the member attribute <b>userId</b>.
- * You cannot set null to the attribute.
- * @param userId Value to set member attribute <b>userId</b>
- */
- public void setUserId( Long userId ) {
- this.userId = userId;
- }
-
- /**
- * Returns the value for the member attribute <b>userId</b>
- * @return Long - value of member attribute <b>userId</b>.
- */
- public Long getUserId( ) {
- return this.userId;
- }
-
-
- /**
- * This method sets the value to the member attribute <b>permFor</b>.
- * You cannot set null to the attribute.
- * @param permFor Value to set member attribute <b>permFor</b>
- */
- public void setPermFor( int permFor ) {
- this.permFor = permFor;
- }
-
- /**
- * Returns the value for the member attribute <b>permFor</b>
- * @return int - value of member attribute <b>permFor</b>.
- */
- public int getPermFor( ) {
- return this.permFor;
- }
-
- /**
- * This method sets the value to the member attribute <b>permType</b>.
- * You cannot set null to the attribute.
- * @param permType Value to set member attribute <b>permType</b>
- */
- public void setPermType( int permType ) {
- this.permType = permType;
- }
-
- /**
- * Returns the value for the member attribute <b>permType</b>
- * @return int - value of member attribute <b>permType</b>.
- */
- public int getPermType( ) {
- return this.permType;
- }
-
- /**
- * This method sets the value to the member attribute <b>isRecursive</b>.
- * You cannot set null to the attribute.
- * @param isRecursive Value to set member attribute <b>isRecursive</b>
- */
- public void setIsRecursive( int isRecursive ) {
- this.isRecursive = isRecursive;
- }
-
- /**
- * Returns the value for the member attribute <b>isRecursive</b>
- * @return int - value of member attribute <b>isRecursive</b>.
- */
- public int getIsRecursive( ) {
- return this.isRecursive;
- }
-
- /**
- * This method sets the value to the member attribute <b>isWildCard</b>.
- * You cannot set null to the attribute.
- * @param isWildCard Value to set member attribute <b>isWildCard</b>
- */
- public void setIsWildCard( boolean isWildCard ) {
- this.isWildCard = isWildCard;
- }
-
- /**
- * Returns the value for the member attribute <b>isWildCard</b>
- * @return boolean - value of member attribute <b>isWildCard</b>.
- */
- public boolean isIsWildCard( ) {
- return this.isWildCard;
- }
-
- /**
- * This method sets the value to the member attribute <b>grantOrRevoke</b>.
- * You cannot set null to the attribute.
- * @param grantOrRevoke Value to set member attribute <b>grantOrRevoke</b>
- */
- public void setGrantOrRevoke( boolean grantOrRevoke ) {
- this.grantOrRevoke = grantOrRevoke;
- }
-
- /**
- * Returns the value for the member attribute <b>grantOrRevoke</b>
- * @return boolean - value of member attribute <b>grantOrRevoke</b>.
- */
- public boolean isGrantOrRevoke( ) {
- return this.grantOrRevoke;
- }
-
- public String getIpAddress() {
- return ipAddress;
- }
-
- public void setIpAddress(String ipAddress) {
- this.ipAddress = ipAddress;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- @Override
- public String toString( ) {
- String str = "XXPermMap={";
- str += super.toString();
- str += "permGroup={" + permGroup + "} ";
- str += "resourceId={" + resourceId + "} ";
- str += "groupId={" + groupId + "} ";
- str += "userId={" + userId + "} ";
- str += "permFor={" + permFor + "} ";
- str += "permType={" + permType + "} ";
- str += "isRecursive={" + isRecursive + "} ";
- str += "isWildCard={" + isWildCard + "} ";
- str += "grantOrRevoke={" + grantOrRevoke + "} ";
- str += "}";
- return str;
- }
-
- /**
- * Checks for all attributes except referenced db objects
- * @return true if all attributes match
- */
- @Override
- public boolean equals( Object obj) {
- if ( !super.equals(obj) ) {
- return false;
- }
- XXPermMap other = (XXPermMap) obj;
- if ((this.permGroup == null && other.permGroup != null) || (this.permGroup != null && !this.permGroup.equals(other.permGroup))) {
- return false;
- }
- if ((this.resourceId == null && other.resourceId != null) || (this.resourceId != null && !this.resourceId.equals(other.resourceId))) {
- return false;
- }
- if ((this.groupId == null && other.groupId != null) || (this.groupId != null && !this.groupId.equals(other.groupId))) {
- return false;
- }
- if ((this.userId == null && other.userId != null) || (this.userId != null && !this.userId.equals(other.userId))) {
- return false;
- }
- if( this.permFor != other.permFor ) return false;
- if( this.permType != other.permType ) return false;
- if( this.isRecursive != other.isRecursive ) return false;
- if( this.isWildCard != other.isWildCard ) return false;
- if( this.grantOrRevoke != other.grantOrRevoke ) return false;
- return true;
- }
- public static String getEnumName(String fieldName ) {
- if( fieldName.equals("permFor") ) {
- return "CommonEnums.XAPermForType";
- }
- if( fieldName.equals("permType") ) {
- return "CommonEnums.XAPermType";
- }
- if( fieldName.equals("isRecursive") ) {
- return "CommonEnums.BooleanValue";
- }
- //Later TODO
- //return super.getEnumName(fieldName);
- return null;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/entity/XXPolicyExportAudit.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/entity/XXPolicyExportAudit.java b/security-admin/src/main/java/com/xasecure/entity/XXPolicyExportAudit.java
deleted file mode 100644
index f96fec9..0000000
--- a/security-admin/src/main/java/com/xasecure/entity/XXPolicyExportAudit.java
+++ /dev/null
@@ -1,310 +0,0 @@
-/*
- * 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 com.xasecure.entity;
-
-/**
- * Audit Log for Policy Export
- *
- */
-
-import java.util.*;
-import javax.persistence.*;
-import javax.xml.bind.annotation.*;
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-
-
-@Entity
-@Table(name="x_policy_export_audit")
-@XmlRootElement
-public class XXPolicyExportAudit extends XXDBBase implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- @Id
- @SequenceGenerator(name="X_POLICY_EXPORT_SEQ",sequenceName="X_POLICY_EXPORT_SEQ",allocationSize=1)
- @GeneratedValue(strategy=GenerationType.AUTO,generator="X_POLICY_EXPORT_SEQ")
- @Column(name="ID")
- protected Long id;
- @Override
- public void setId(Long id) {
- this.id=id;
- }
-
- @Override
- public Long getId() {
- return id;
- }
-
- /**
- * XA Agent IP Address
- * <ul>
- * <li>The maximum length for this attribute is <b>255</b>.
- * </ul>
- *
- */
- @Column(name="CLIENT_IP" , nullable=false , length=255)
- protected String clientIP;
-
- /**
- * XA Agent Id
- * <ul>
- * <li>The maximum length for this attribute is <b>255</b>.
- * </ul>
- *
- */
- @Column(name="AGENT_ID" , length=255)
- protected String agentId;
-
- /**
- * Last update timestamp in request
- * <ul>
- * </ul>
- *
- */
- @Column(name="REQ_EPOCH" , nullable=false )
- protected Long requestedEpoch;
-
- /**
- * Date and time of the last policy update
- * <ul>
- * </ul>
- *
- */
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name="LAST_UPDATED" )
- protected Date lastUpdated;
-
- /**
- * Name of the Asset
- * <ul>
- * <li>The maximum length for this attribute is <b>1024</b>.
- * </ul>
- *
- */
- @Column(name="REPOSITORY_NAME" , length=1024)
- protected String repositoryName;
-
- /**
- * JSON of the policies exported
- * <ul>
- * <li>The maximum length for this attribute is <b>30000</b>.
- * </ul>
- *
- */
- @Column(name="EXPORTED_JSON" , length=30000)
- protected String exportedJson;
-
- /**
- * HTTP Response Code
- * <ul>
- * </ul>
- *
- */
- @Column(name="HTTP_RET_CODE" , nullable=false )
- protected int httpRetCode;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public XXPolicyExportAudit ( ) {
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_XA_POLICY_EXPORT_AUDIT;
- }
-
- /**
- * This method sets the value to the member attribute <b>clientIP</b>.
- * You cannot set null to the attribute.
- * @param clientIP Value to set member attribute <b>clientIP</b>
- */
- public void setClientIP( String clientIP ) {
- this.clientIP = clientIP;
- }
-
- /**
- * Returns the value for the member attribute <b>clientIP</b>
- * @return String - value of member attribute <b>clientIP</b>.
- */
- public String getClientIP( ) {
- return this.clientIP;
- }
-
- /**
- * This method sets the value to the member attribute <b>agentId</b>.
- * You cannot set null to the attribute.
- * @param agentId Value to set member attribute <b>agentId</b>
- */
- public void setAgentId( String agentId ) {
- this.agentId = agentId;
- }
-
- /**
- * Returns the value for the member attribute <b>agentId</b>
- * @return String - value of member attribute <b>agentId</b>.
- */
- public String getAgentId( ) {
- return this.agentId;
- }
-
- /**
- * This method sets the value to the member attribute <b>requestedEpoch</b>.
- * You cannot set null to the attribute.
- * @param requestedEpoch Value to set member attribute <b>requestedEpoch</b>
- */
- public void setRequestedEpoch( Long requestedEpoch ) {
- this.requestedEpoch = requestedEpoch;
- }
-
- /**
- * Returns the value for the member attribute <b>requestedEpoch</b>
- * @return Long - value of member attribute <b>requestedEpoch</b>.
- */
- public Long getRequestedEpoch( ) {
- return this.requestedEpoch;
- }
-
- /**
- * This method sets the value to the member attribute <b>lastUpdated</b>.
- * You cannot set null to the attribute.
- * @param lastUpdated Value to set member attribute <b>lastUpdated</b>
- */
- public void setLastUpdated( Date lastUpdated ) {
- this.lastUpdated = lastUpdated;
- }
-
- /**
- * Returns the value for the member attribute <b>lastUpdated</b>
- * @return Date - value of member attribute <b>lastUpdated</b>.
- */
- public Date getLastUpdated( ) {
- return this.lastUpdated;
- }
-
- /**
- * This method sets the value to the member attribute <b>repositoryName</b>.
- * You cannot set null to the attribute.
- * @param repositoryName Value to set member attribute <b>repositoryName</b>
- */
- public void setRepositoryName( String repositoryName ) {
- this.repositoryName = repositoryName;
- }
-
- /**
- * Returns the value for the member attribute <b>repositoryName</b>
- * @return String - value of member attribute <b>repositoryName</b>.
- */
- public String getRepositoryName( ) {
- return this.repositoryName;
- }
-
- /**
- * This method sets the value to the member attribute <b>exportedJson</b>.
- * You cannot set null to the attribute.
- * @param exportedJson Value to set member attribute <b>exportedJson</b>
- */
- public void setExportedJson( String exportedJson ) {
- this.exportedJson = exportedJson;
- }
-
- /**
- * Returns the value for the member attribute <b>exportedJson</b>
- * @return String - value of member attribute <b>exportedJson</b>.
- */
- public String getExportedJson( ) {
- return this.exportedJson;
- }
-
- /**
- * This method sets the value to the member attribute <b>httpRetCode</b>.
- * You cannot set null to the attribute.
- * @param httpRetCode Value to set member attribute <b>httpRetCode</b>
- */
- public void setHttpRetCode( int httpRetCode ) {
- this.httpRetCode = httpRetCode;
- }
-
- /**
- * Returns the value for the member attribute <b>httpRetCode</b>
- * @return int - value of member attribute <b>httpRetCode</b>.
- */
- public int getHttpRetCode( ) {
- return this.httpRetCode;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- @Override
- public String toString( ) {
- String str = "XXPolicyExportAudit={";
- str += super.toString();
- str += "clientIP={" + clientIP + "} ";
- str += "agentId={" + agentId + "} ";
- str += "requestedEpoch={" + requestedEpoch + "} ";
- str += "lastUpdated={" + lastUpdated + "} ";
- str += "repositoryName={" + repositoryName + "} ";
- str += "exportedJson={" + exportedJson + "} ";
- str += "httpRetCode={" + httpRetCode + "} ";
- str += "}";
- return str;
- }
-
- /**
- * Checks for all attributes except referenced db objects
- * @return true if all attributes match
- */
- @Override
- public boolean equals( Object obj) {
- if ( !super.equals(obj) ) {
- return false;
- }
- XXPolicyExportAudit other = (XXPolicyExportAudit) obj;
- if ((this.clientIP == null && other.clientIP != null) || (this.clientIP != null && !this.clientIP.equals(other.clientIP))) {
- return false;
- }
- if ((this.agentId == null && other.agentId != null) || (this.agentId != null && !this.agentId.equals(other.agentId))) {
- return false;
- }
- if ((this.requestedEpoch == null && other.requestedEpoch != null) || (this.requestedEpoch != null && !this.requestedEpoch.equals(other.requestedEpoch))) {
- return false;
- }
- if ((this.lastUpdated == null && other.lastUpdated != null) || (this.lastUpdated != null && !this.lastUpdated.equals(other.lastUpdated))) {
- return false;
- }
- if ((this.repositoryName == null && other.repositoryName != null) || (this.repositoryName != null && !this.repositoryName.equals(other.repositoryName))) {
- return false;
- }
- if ((this.exportedJson == null && other.exportedJson != null) || (this.exportedJson != null && !this.exportedJson.equals(other.exportedJson))) {
- return false;
- }
- if( this.httpRetCode != other.httpRetCode ) return false;
- return true;
- }
- public static String getEnumName(String fieldName ) {
- //Later TODO
- //return super.getEnumName(fieldName);
- return null;
- }
-
-}
[06/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/AppConstants.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/AppConstants.java b/security-admin/src/main/java/org/apache/ranger/common/AppConstants.java
new file mode 100644
index 0000000..ac47ef0
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/AppConstants.java
@@ -0,0 +1,955 @@
+/*
+ * 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.*;
+
+import org.apache.ranger.common.*;
+
+public class AppConstants extends XACommonEnums {
+
+ /***************************************************************
+ * Enum values for AssetType
+ **************************************************************/
+ /**
+ * ASSET_UNKNOWN is an element of enum AssetType. Its value is "ASSET_UNKNOWN".
+ */
+ public static final int ASSET_UNKNOWN = 0;
+ /**
+ * ASSET_HDFS is an element of enum AssetType. Its value is "ASSET_HDFS".
+ */
+ public static final int ASSET_HDFS = 1;
+ /**
+ * ASSET_HBASE is an element of enum AssetType. Its value is "ASSET_HBASE".
+ */
+ public static final int ASSET_HBASE = 2;
+ /**
+ * ASSET_HIVE is an element of enum AssetType. Its value is "ASSET_HIVE".
+ */
+ public static final int ASSET_HIVE = 3;
+
+ /**
+ * enum XAAGENT is reserved for internal use
+ */
+ public static final int XAAGENT = 4 ;
+ /**
+ * ASSET_KNOX is an element of enum AssetType. Its value is "ASSET_KNOX".
+ */
+ public static final int ASSET_KNOX = 5;
+ /**
+ * ASSET_STORM is an element of enum AssetType. Its value is "ASSET_STORM".
+ */
+ public static final int ASSET_STORM = 6;
+
+ /**
+ * Max value for enum AssetType_MAX
+ */
+ public static final int AssetType_MAX = 6;
+
+ /***************************************************************
+ * Enum values for PolicyType
+ **************************************************************/
+ /**
+ * POLICY_INCLUSION is an element of enum PolicyType. Its value is "POLICY_INCLUSION".
+ */
+ public static final int POLICY_INCLUSION = 0;
+ /**
+ * POLICY_EXCLUSION is an element of enum PolicyType. Its value is "POLICY_EXCLUSION".
+ */
+ public static final int POLICY_EXCLUSION = 1;
+
+ /***************************************************************
+ * Enum values for XAAuditType
+ **************************************************************/
+ /**
+ * XA_AUDIT_TYPE_UNKNOWN is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_UNKNOWN".
+ */
+ public static final int XA_AUDIT_TYPE_UNKNOWN = 0;
+ /**
+ * XA_AUDIT_TYPE_ALL is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_ALL".
+ */
+ public static final int XA_AUDIT_TYPE_ALL = 1;
+ /**
+ * XA_AUDIT_TYPE_READ is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_READ".
+ */
+ public static final int XA_AUDIT_TYPE_READ = 2;
+ /**
+ * XA_AUDIT_TYPE_WRITE is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_WRITE".
+ */
+ public static final int XA_AUDIT_TYPE_WRITE = 3;
+ /**
+ * XA_AUDIT_TYPE_CREATE is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_CREATE".
+ */
+ public static final int XA_AUDIT_TYPE_CREATE = 4;
+ /**
+ * XA_AUDIT_TYPE_DELETE is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_DELETE".
+ */
+ public static final int XA_AUDIT_TYPE_DELETE = 5;
+ /**
+ * XA_AUDIT_TYPE_LOGIN is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_LOGIN".
+ */
+ public static final int XA_AUDIT_TYPE_LOGIN = 6;
+
+ /**
+ * Max value for enum XAAuditType_MAX
+ */
+ public static final int XAAuditType_MAX = 6;
+
+
+ /***************************************************************
+ * Enum values for ResourceType
+ **************************************************************/
+ /**
+ * RESOURCE_UNKNOWN is an element of enum ResourceType. Its value is "RESOURCE_UNKNOWN".
+ */
+ public static final int RESOURCE_UNKNOWN = 0;
+ /**
+ * RESOURCE_PATH is an element of enum ResourceType. Its value is "RESOURCE_PATH".
+ */
+ public static final int RESOURCE_PATH = 1;
+ /**
+ * RESOURCE_DB is an element of enum ResourceType. Its value is "RESOURCE_DB".
+ */
+ public static final int RESOURCE_DB = 2;
+ /**
+ * RESOURCE_TABLE is an element of enum ResourceType. Its value is "RESOURCE_TABLE".
+ */
+ public static final int RESOURCE_TABLE = 3;
+ /**
+ * RESOURCE_COL_FAM is an element of enum ResourceType. Its value is "RESOURCE_COL_FAM".
+ */
+ public static final int RESOURCE_COL_FAM = 4;
+ /**
+ * RESOURCE_COLUMN is an element of enum ResourceType. Its value is "RESOURCE_COLUMN".
+ */
+ public static final int RESOURCE_COLUMN = 5;
+ /**
+ * RESOURCE_VIEW is an element of enum ResourceType. Its value is "RESOURCE_VIEW".
+ */
+ public static final int RESOURCE_VIEW = 6;
+ /**
+ * RESOURCE_UDF is an element of enum ResourceType. Its value is "RESOURCE_UDF".
+ */
+ public static final int RESOURCE_UDF = 7;
+ /**
+ * RESOURCE_VIEW_COL is an element of enum ResourceType. Its value is "RESOURCE_VIEW_COL".
+ */
+ public static final int RESOURCE_VIEW_COL = 8;
+ /**
+ * RESOURCE_TOPOLOGY is an element of enum ResourceType. Its value is "RESOURCE_TOPOLOGY".
+ */
+ public static final int RESOURCE_TOPOLOGY = 9;
+ /**
+ * RESOURCE_SERVICE_NAME is an element of enum ResourceType. Its value is "RESOURCE_SERVICE_NAME".
+ */
+ public static final int RESOURCE_SERVICE_NAME = 10;
+
+ /**
+ * Max value for enum ResourceType_MAX
+ */
+ public static final int ResourceType_MAX = 10;
+
+
+ /***************************************************************
+ * Enum values for XAGroupType
+ **************************************************************/
+ /**
+ * XA_GROUP_UNKNOWN is an element of enum XAGroupType. Its value is "XA_GROUP_UNKNOWN".
+ */
+ public static final int XA_GROUP_UNKNOWN = 0;
+ /**
+ * XA_GROUP_USER is an element of enum XAGroupType. Its value is "XA_GROUP_USER".
+ */
+ public static final int XA_GROUP_USER = 1;
+ /**
+ * XA_GROUP_GROUP is an element of enum XAGroupType. Its value is "XA_GROUP_GROUP".
+ */
+ public static final int XA_GROUP_GROUP = 2;
+ /**
+ * XA_GROUP_ROLE is an element of enum XAGroupType. Its value is "XA_GROUP_ROLE".
+ */
+ public static final int XA_GROUP_ROLE = 3;
+
+ /**
+ * Max value for enum XAGroupType_MAX
+ */
+ public static final int XAGroupType_MAX = 3;
+
+
+ /***************************************************************
+ * Enum values for XAPermForType
+ **************************************************************/
+ /**
+ * XA_PERM_FOR_UNKNOWN is an element of enum XAPermForType. Its value is "XA_PERM_FOR_UNKNOWN".
+ */
+ public static final int XA_PERM_FOR_UNKNOWN = 0;
+ /**
+ * XA_PERM_FOR_USER is an element of enum XAPermForType. Its value is "XA_PERM_FOR_USER".
+ */
+ public static final int XA_PERM_FOR_USER = 1;
+ /**
+ * XA_PERM_FOR_GROUP is an element of enum XAPermForType. Its value is "XA_PERM_FOR_GROUP".
+ */
+ public static final int XA_PERM_FOR_GROUP = 2;
+
+ /**
+ * Max value for enum XAPermForType_MAX
+ */
+ public static final int XAPermForType_MAX = 2;
+
+
+ /***************************************************************
+ * Enum values for XAPermType
+ **************************************************************/
+ /**
+ * XA_PERM_TYPE_UNKNOWN is an element of enum XAPermType. Its value is "XA_PERM_TYPE_UNKNOWN".
+ */
+ public static final int XA_PERM_TYPE_UNKNOWN = 0;
+ /**
+ * XA_PERM_TYPE_RESET is an element of enum XAPermType. Its value is "XA_PERM_TYPE_RESET".
+ */
+ public static final int XA_PERM_TYPE_RESET = 1;
+ /**
+ * XA_PERM_TYPE_READ is an element of enum XAPermType. Its value is "XA_PERM_TYPE_READ".
+ */
+ public static final int XA_PERM_TYPE_READ = 2;
+ /**
+ * XA_PERM_TYPE_WRITE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_WRITE".
+ */
+ public static final int XA_PERM_TYPE_WRITE = 3;
+ /**
+ * XA_PERM_TYPE_CREATE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_CREATE".
+ */
+ public static final int XA_PERM_TYPE_CREATE = 4;
+ /**
+ * XA_PERM_TYPE_DELETE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_DELETE".
+ */
+ public static final int XA_PERM_TYPE_DELETE = 5;
+ /**
+ * XA_PERM_TYPE_ADMIN is an element of enum XAPermType. Its value is "XA_PERM_TYPE_ADMIN".
+ */
+ public static final int XA_PERM_TYPE_ADMIN = 6;
+ /**
+ * XA_PERM_TYPE_OBFUSCATE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_OBFUSCATE".
+ */
+ public static final int XA_PERM_TYPE_OBFUSCATE = 7;
+ /**
+ * XA_PERM_TYPE_MASK is an element of enum XAPermType. Its value is "XA_PERM_TYPE_MASK".
+ */
+ public static final int XA_PERM_TYPE_MASK = 8;
+ /**
+ * XA_PERM_TYPE_EXECUTE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_EXECUTE".
+ */
+ public static final int XA_PERM_TYPE_EXECUTE = 9;
+ /**
+ * XA_PERM_TYPE_SELECT is an element of enum XAPermType. Its value is "XA_PERM_TYPE_SELECT".
+ */
+ public static final int XA_PERM_TYPE_SELECT = 10;
+ /**
+ * XA_PERM_TYPE_UPDATE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_UPDATE".
+ */
+ public static final int XA_PERM_TYPE_UPDATE = 11;
+ /**
+ * XA_PERM_TYPE_DROP is an element of enum XAPermType. Its value is "XA_PERM_TYPE_DROP".
+ */
+ public static final int XA_PERM_TYPE_DROP = 12;
+ /**
+ * XA_PERM_TYPE_ALTER is an element of enum XAPermType. Its value is "XA_PERM_TYPE_ALTER".
+ */
+ public static final int XA_PERM_TYPE_ALTER = 13;
+ /**
+ * XA_PERM_TYPE_INDEX is an element of enum XAPermType. Its value is "XA_PERM_TYPE_INDEX".
+ */
+ public static final int XA_PERM_TYPE_INDEX = 14;
+ /**
+ * XA_PERM_TYPE_LOCK is an element of enum XAPermType. Its value is "XA_PERM_TYPE_LOCK".
+ */
+ public static final int XA_PERM_TYPE_LOCK = 15;
+ /**
+ * XA_PERM_TYPE_ALL is an element of enum XAPermType. Its value is "XA_PERM_TYPE_ALL".
+ */
+ public static final int XA_PERM_TYPE_ALL = 16;
+ /**
+ * XA_PERM_TYPE_ALLOW is an element of enum XAPermType. Its value is "XA_PERM_TYPE_ALLOW".
+ */
+ public static final int XA_PERM_TYPE_ALLOW = 17;
+ /**
+ * XA_PERM_TYPE_SUBMIT_TOPOLOGY is an element of enum XAPermType. Its value is "XA_PERM_TYPE_SUBMIT_TOPOLOGY".
+ */
+ public static final int XA_PERM_TYPE_SUBMIT_TOPOLOGY = 18;
+ /**
+ * XA_PERM_TYPE_FILE_UPLOAD is an element of enum XAPermType. Its value is "XA_PERM_TYPE_FILE_UPLOAD".
+ */
+ public static final int XA_PERM_TYPE_FILE_UPLOAD = 19;
+ /**
+ * XA_PERM_TYPE_GET_NIMBUS is an element of enum XAPermType. Its value is "XA_PERM_TYPE_GET_NIMBUS".
+ */
+ public static final int XA_PERM_TYPE_GET_NIMBUS = 20;
+ /**
+ * XA_PERM_TYPE_GET_CLUSTER_INFO is an element of enum XAPermType. Its value is "XA_PERM_TYPE_GET_CLUSTER_INFO".
+ */
+ public static final int XA_PERM_TYPE_GET_CLUSTER_INFO = 21;
+ /**
+ * XA_PERM_TYPE_FILE_DOWNLOAD is an element of enum XAPermType. Its value is "XA_PERM_TYPE_FILE_DOWNLOAD".
+ */
+ public static final int XA_PERM_TYPE_FILE_DOWNLOAD = 22;
+ /**
+ * XA_PERM_TYPE_KILL_TOPOLOGY is an element of enum XAPermType. Its value is "XA_PERM_TYPE_KILL_TOPOLOGY".
+ */
+ public static final int XA_PERM_TYPE_KILL_TOPOLOGY = 23;
+ /**
+ * XA_PERM_TYPE_REBALANCE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_REBALANCE".
+ */
+ public static final int XA_PERM_TYPE_REBALANCE = 24;
+ /**
+ * XA_PERM_TYPE_ACTIVATE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_ACTIVATE".
+ */
+ public static final int XA_PERM_TYPE_ACTIVATE = 25;
+ /**
+ * XA_PERM_TYPE_DEACTIVATE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_DEACTIVATE".
+ */
+ public static final int XA_PERM_TYPE_DEACTIVATE = 26;
+ /**
+ * XA_PERM_TYPE_GET_TOPOLOGY_CONF is an element of enum XAPermType. Its value is "XA_PERM_TYPE_GET_TOPOLOGY_CONF".
+ */
+ public static final int XA_PERM_TYPE_GET_TOPOLOGY_CONF = 27;
+ /**
+ * XA_PERM_TYPE_GET_TOPOLOGY is an element of enum XAPermType. Its value is "XA_PERM_TYPE_GET_TOPOLOGY".
+ */
+ public static final int XA_PERM_TYPE_GET_TOPOLOGY = 28;
+ /**
+ * XA_PERM_TYPE_GET_USER_TOPOLOGY is an element of enum XAPermType. Its value is "XA_PERM_TYPE_GET_USER_TOPOLOGY".
+ */
+ public static final int XA_PERM_TYPE_GET_USER_TOPOLOGY = 29;
+ /**
+ * XA_PERM_TYPE_GET_TOPOLOGY_INFO is an element of enum XAPermType. Its value is "XA_PERM_TYPE_GET_TOPOLOGY_INFO".
+ */
+ public static final int XA_PERM_TYPE_GET_TOPOLOGY_INFO = 30;
+ /**
+ * XA_PERM_TYPE_UPLOAD_NEW_CREDENTIAL is an element of enum XAPermType. Its value is "XA_PERM_TYPE_UPLOAD_NEW_CREDENTIAL".
+ */
+ public static final int XA_PERM_TYPE_UPLOAD_NEW_CREDENTIAL = 31;
+
+ /**
+ * Max value for enum XAPermType_MAX
+ */
+ public static final int XAPermType_MAX = 31;
+
+ /***************************************************************
+ * Enum values for DatabaseFavor
+ **************************************************************/
+ /**
+ * DB Favor Unknown
+ */
+ public static final int DB_FLAVOR_UNKNOWN = 0;
+ /**
+ * DB Favor MySql
+ */
+ public static final int DB_FLAVOR_MYSQL = 1;
+ /**
+ * DB Favor Oracle
+ */
+ public static final int DB_FLAVOR_ORACLE = 2;
+
+
+ /***************************************************************
+ * Enum values for ClassTypes
+ **************************************************************/
+ /**
+ * CLASS_TYPE_XA_ASSET is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_ASSET".
+ */
+ public static final int CLASS_TYPE_XA_ASSET = 1000;
+ /**
+ * CLASS_TYPE_XA_RESOURCE is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_RESOURCE".
+ */
+ public static final int CLASS_TYPE_XA_RESOURCE = 1001;
+ /**
+ * CLASS_TYPE_XA_GROUP is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_GROUP".
+ */
+ public static final int CLASS_TYPE_XA_GROUP = 1002;
+ /**
+ * CLASS_TYPE_XA_USER is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_USER".
+ */
+ public static final int CLASS_TYPE_XA_USER = 1003;
+ /**
+ * CLASS_TYPE_XA_GROUP_USER is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_GROUP_USER".
+ */
+ public static final int CLASS_TYPE_XA_GROUP_USER = 1004;
+ /**
+ * CLASS_TYPE_XA_GROUP_GROUP is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_GROUP_GROUP".
+ */
+ public static final int CLASS_TYPE_XA_GROUP_GROUP = 1005;
+ /**
+ * CLASS_TYPE_XA_PERM_MAP is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_PERM_MAP".
+ */
+ public static final int CLASS_TYPE_XA_PERM_MAP = 1006;
+ /**
+ * CLASS_TYPE_XA_AUDIT_MAP is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_AUDIT_MAP".
+ */
+ public static final int CLASS_TYPE_XA_AUDIT_MAP = 1007;
+ /**
+ * CLASS_TYPE_XA_CRED_STORE is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_CRED_STORE".
+ */
+ public static final int CLASS_TYPE_XA_CRED_STORE = 1008;
+ /**
+ * CLASS_TYPE_XA_COMN_REF is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_COMN_REF".
+ */
+ public static final int CLASS_TYPE_XA_COMN_REF = 1009;
+ /**
+ * CLASS_TYPE_XA_LICENSE is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_LICENSE".
+ */
+ public static final int CLASS_TYPE_XA_LICENSE = 1010;
+ /**
+ * CLASS_TYPE_XA_POLICY_EXPORT_AUDIT is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_POLICY_EXPORT_AUDIT".
+ */
+ public static final int CLASS_TYPE_XA_POLICY_EXPORT_AUDIT = 1011;
+ /**
+ * CLASS_TYPE_TRX_LOG is an element of enum ClassTypes. Its value is "CLASS_TYPE_TRX_LOG".
+ */
+ public static final int CLASS_TYPE_TRX_LOG = 1012;
+ /**
+ * CLASS_TYPE_XA_ACCESS_AUDIT is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_ACCESS_AUDIT".
+ */
+ public static final int CLASS_TYPE_XA_ACCESS_AUDIT = 1013;
+ /**
+ * CLASS_TYPE_XA_TRANSACTION_LOG_ATTRIBUTE is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_TRANSACTION_LOG_ATTRIBUTE".
+ */
+ public static final int CLASS_TYPE_XA_TRANSACTION_LOG_ATTRIBUTE = 1014;
+
+ /**
+ * Max value for enum ClassTypes_MAX
+ */
+ public static final int ClassTypes_MAX = 1014;
+
+
+
+ static public String getLabelFor_AssetType( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Unknown"; //ASSET_UNKNOWN
+ }
+ if( elementValue == 1 ) {
+ return "HDFS"; //ASSET_HDFS
+ }
+ if( elementValue == 2 ) {
+ return "HBase"; //ASSET_HBASE
+ }
+ if( elementValue == 3 ) {
+ return "Hive"; //ASSET_HIVE
+ }
+ if( elementValue == 4 ) {
+ return "XAAGENT"; // XAAGENT
+ }
+ if( elementValue == 5 ) {
+ return "Knox"; //ASSET_KNOX
+ }
+ if( elementValue == 6 ) {
+ return "Storm"; //ASSET_STORM
+ }
+ return null;
+ }
+
+ static public String getLabelFor_PolicyType( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Inclusion"; //POLICY_INCLUSION
+ }
+ if( elementValue == 1 ) {
+ return "Exclusion"; //POLICY_EXCLUSION
+ }
+ return null;
+ }
+
+ static public String getLabelFor_XAAuditType( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Unknown"; //XA_AUDIT_TYPE_UNKNOWN
+ }
+ if( elementValue == 1 ) {
+ return "All"; //XA_AUDIT_TYPE_ALL
+ }
+ if( elementValue == 2 ) {
+ return "Read"; //XA_AUDIT_TYPE_READ
+ }
+ if( elementValue == 3 ) {
+ return "Write"; //XA_AUDIT_TYPE_WRITE
+ }
+ if( elementValue == 4 ) {
+ return "Create"; //XA_AUDIT_TYPE_CREATE
+ }
+ if( elementValue == 5 ) {
+ return "Delete"; //XA_AUDIT_TYPE_DELETE
+ }
+ if( elementValue == 6 ) {
+ return "Login"; //XA_AUDIT_TYPE_LOGIN
+ }
+ return null;
+ }
+
+ static public String getLabelFor_ResourceType( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Unknown"; //RESOURCE_UNKNOWN
+ }
+ if( elementValue == 1 ) {
+ return "Path"; //RESOURCE_PATH
+ }
+ if( elementValue == 2 ) {
+ return "Database"; //RESOURCE_DB
+ }
+ if( elementValue == 3 ) {
+ return "Table"; //RESOURCE_TABLE
+ }
+ if( elementValue == 4 ) {
+ return "Column Family"; //RESOURCE_COL_FAM
+ }
+ if( elementValue == 5 ) {
+ return "Column"; //RESOURCE_COLUMN
+ }
+ if( elementValue == 6 ) {
+ return "VIEW"; //RESOURCE_VIEW
+ }
+ if( elementValue == 7 ) {
+ return "UDF"; //RESOURCE_UDF
+ }
+ if( elementValue == 8 ) {
+ return "View Column"; //RESOURCE_VIEW_COL
+ }
+ if( elementValue == 9 ) {
+ return "Topology"; //RESOURCE_TOPOLOGY
+ }
+ if( elementValue == 10 ) {
+ return "Service"; //RESOURCE_SERVICE
+ }
+ return null;
+ }
+
+ static public String getLabelFor_XAGroupType( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Unknown"; //XA_GROUP_UNKNOWN
+ }
+ if( elementValue == 1 ) {
+ return "User"; //XA_GROUP_USER
+ }
+ if( elementValue == 2 ) {
+ return "Group"; //XA_GROUP_GROUP
+ }
+ if( elementValue == 3 ) {
+ return "Role"; //XA_GROUP_ROLE
+ }
+ return null;
+ }
+
+ static public String getLabelFor_XAPermForType( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Unknown"; //XA_PERM_FOR_UNKNOWN
+ }
+ if( elementValue == 1 ) {
+ return "Permission for Users"; //XA_PERM_FOR_USER
+ }
+ if( elementValue == 2 ) {
+ return "Permission for Groups"; //XA_PERM_FOR_GROUP
+ }
+ return null;
+ }
+
+ static public String getLabelFor_XAPermType( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Unknown"; //XA_PERM_TYPE_UNKNOWN
+ }
+ if( elementValue == 1 ) {
+ return "Reset"; //XA_PERM_TYPE_RESET
+ }
+ if( elementValue == 2 ) {
+ return "Read"; //XA_PERM_TYPE_READ
+ }
+ if( elementValue == 3 ) {
+ return "Write"; //XA_PERM_TYPE_WRITE
+ }
+ if( elementValue == 4 ) {
+ return "Create"; //XA_PERM_TYPE_CREATE
+ }
+ if( elementValue == 5 ) {
+ return "Delete"; //XA_PERM_TYPE_DELETE
+ }
+ if( elementValue == 6 ) {
+ return "Admin"; //XA_PERM_TYPE_ADMIN
+ }
+ if( elementValue == 7 ) {
+ return "Obfuscate"; //XA_PERM_TYPE_OBFUSCATE
+ }
+ if( elementValue == 8 ) {
+ return "Mask"; //XA_PERM_TYPE_MASK
+ }
+ if( elementValue == 9 ) {
+ return "Execute"; //XA_PERM_TYPE_EXECUTE
+ }
+ if( elementValue == 10 ) {
+ return "Select"; //XA_PERM_TYPE_SELECT
+ }
+ if( elementValue == 11 ) {
+ return "Update"; //XA_PERM_TYPE_UPDATE
+ }
+ if( elementValue == 12 ) {
+ return "Drop"; //XA_PERM_TYPE_DROP
+ }
+ if( elementValue == 13 ) {
+ return "Alter"; //XA_PERM_TYPE_ALTER
+ }
+ if( elementValue == 14 ) {
+ return "Index"; //XA_PERM_TYPE_INDEX
+ }
+ if( elementValue == 15 ) {
+ return "Lock"; //XA_PERM_TYPE_LOCK
+ }
+ if( elementValue == 16 ) {
+ return "All"; //XA_PERM_TYPE_ALL
+ }
+ if( elementValue == 17 ) {
+ return "Allow"; //XA_PERM_TYPE_ALLOW
+ }
+ if( elementValue == 18 ) {
+ // return "Submit Topology"; //XA_PERM_TYPE_SUBMIT_TOPOLOGY
+ return "submitTopology" ;
+ }
+ if( elementValue == 19 ) {
+ // return "File Upload"; //XA_PERM_TYPE_FILE_UPLOAD
+ return "fileUpload" ;
+ }
+ if( elementValue == 20 ) {
+ // return "Get Nimbus Conf"; //XA_PERM_TYPE_GET_NIMBUS
+ return "getNimbusConf" ;
+ }
+ if( elementValue == 21 ) {
+ // return "Get Cluster Info"; //XA_PERM_TYPE_GET_CLUSTER_INFO
+ return "getClusterInfo" ;
+ }
+ if( elementValue == 22 ) {
+ // return "File Download"; //XA_PERM_TYPE_FILE_DOWNLOAD
+ return "fileDownload" ;
+ }
+ if( elementValue == 23 ) {
+ // return "Kill Topology"; //XA_PERM_TYPE_KILL_TOPOLOGY
+ return "killTopology" ;
+ }
+ if( elementValue == 24 ) {
+ // return "Rebalance"; //XA_PERM_TYPE_REBALANCE
+ return "rebalance" ;
+ }
+ if( elementValue == 25 ) {
+ // return "Activate"; //XA_PERM_TYPE_ACTIVATE
+ return "activate" ;
+ }
+ if( elementValue == 26 ) {
+ // return "Deactivate"; //XA_PERM_TYPE_DEACTIVATE
+ return "deactivate" ;
+ }
+ if( elementValue == 27 ) {
+ // return "Get Topology Conf"; //XA_PERM_TYPE_GET_TOPOLOGY_CONF
+ return "getTopologyConf" ;
+ }
+ if( elementValue == 28 ) {
+ // return "Get Topology"; //XA_PERM_TYPE_GET_TOPOLOGY
+ return "getTopology" ;
+ }
+ if( elementValue == 29 ) {
+ // return "Get User Topology"; //XA_PERM_TYPE_GET_USER_TOPOLOGY
+ return "getUserTopology" ;
+ }
+ if( elementValue == 30 ) {
+ // return "Get Topology Info"; //XA_PERM_TYPE_GET_TOPOLOGY_INFO
+ return "getTopologyInfo" ;
+ }
+ if( elementValue == 31 ) {
+ // return "Upload New Credential"; //XA_PERM_TYPE_UPLOAD_NEW_CREDENTIAL
+ return "uploadNewCredentials" ;
+ }
+ return null;
+ }
+
+ static public String getLabelFor_ClassTypes( int elementValue ) {
+ if( elementValue == 1000 ) {
+ return "Asset"; //CLASS_TYPE_XA_ASSET
+ }
+ if( elementValue == 1001 ) {
+ return "Resource"; //CLASS_TYPE_XA_RESOURCE
+ }
+ if( elementValue == 1002 ) {
+ return "XA Group"; //CLASS_TYPE_XA_GROUP
+ }
+ if( elementValue == 1003 ) {
+ return "XA User"; //CLASS_TYPE_XA_USER
+ }
+ if( elementValue == 1004 ) {
+ return "XA Group of Users"; //CLASS_TYPE_XA_GROUP_USER
+ }
+ if( elementValue == 1005 ) {
+ return "XA Group of groups"; //CLASS_TYPE_XA_GROUP_GROUP
+ }
+ if( elementValue == 1006 ) {
+ return "XA permissions for resource"; //CLASS_TYPE_XA_PERM_MAP
+ }
+ if( elementValue == 1007 ) {
+ return "XA audits for resource"; //CLASS_TYPE_XA_AUDIT_MAP
+ }
+ if( elementValue == 1008 ) {
+ return "XA credential store"; //CLASS_TYPE_XA_CRED_STORE
+ }
+ if( elementValue == 1009 ) {
+ return "XA Common Reference"; //CLASS_TYPE_XA_COMN_REF
+ }
+ if( elementValue == 1010 ) {
+ return "XA License"; //CLASS_TYPE_XA_LICENSE
+ }
+ if( elementValue == 1011 ) {
+ return "XA Policy Export Audit"; //CLASS_TYPE_XA_POLICY_EXPORT_AUDIT
+ }
+ if( elementValue == 1012 ) {
+ return "Transaction log"; //CLASS_TYPE_TRX_LOG
+ }
+ if( elementValue == 1013 ) {
+ return "Access Audit"; //CLASS_TYPE_XA_ACCESS_AUDIT
+ }
+ return null;
+ }
+
+ static public int getEnumFor_AssetType(String label) {
+ if (label == null) {
+ return 0;
+ }
+ if (label.equalsIgnoreCase("Unknown")) {
+ return AppConstants.ASSET_UNKNOWN; // ASSET_UNKNOWN
+ }
+ if (label.equalsIgnoreCase("HDFS")) {
+ return AppConstants.ASSET_HDFS; // ASSET_HDFS
+ }
+ if (label.equalsIgnoreCase("HBase")) {
+ return AppConstants.ASSET_HBASE; // ASSET_HBASE
+ }
+ if (label.equalsIgnoreCase("Hive")) {
+ return AppConstants.ASSET_HIVE; // ASSET_HIVE
+ }
+ if (label.equalsIgnoreCase("Knox")) {
+ return AppConstants.ASSET_KNOX; // ASSET_KNOX
+ }
+ if (label.equalsIgnoreCase("Storm")) {
+ return AppConstants.ASSET_STORM; // ASSET_STORM
+ }
+ return 0;
+ }
+
+ static public int getEnumFor_BooleanValue(boolean label) {
+ if (label) {
+ return AppConstants.BOOL_TRUE;
+ } else {
+ return AppConstants.BOOL_FALSE;
+ }
+ }
+
+ static public boolean getBooleanFor_BooleanValue(int elementValue) {
+ if (elementValue == 1) {
+ return true;
+ }
+ if (elementValue == 2) {
+ return false;
+ }
+ return false;
+ }
+
+ static public int getEnumFor_ResourceType(String label) {
+ if (label == null) {
+ return 0;
+ }
+ if (label.equalsIgnoreCase("Unknown")) {
+ return AppConstants.RESOURCE_UNKNOWN; // RESOURCE_UNKNOWN
+ }
+ if (label.equalsIgnoreCase("Path")) {
+ return AppConstants.RESOURCE_PATH; // RESOURCE_PATH
+ }
+ if (label.equalsIgnoreCase("Database")) {
+ return AppConstants.RESOURCE_DB; // RESOURCE_DB
+ }
+ if (label.equalsIgnoreCase("Table")) {
+ return AppConstants.RESOURCE_TABLE; // RESOURCE_TABLE
+ }
+ if (label.equalsIgnoreCase("Column Family")) {
+ return AppConstants.RESOURCE_COL_FAM; // RESOURCE_COL_FAM
+ }
+ if (label.equalsIgnoreCase("Column")) {
+ return AppConstants.RESOURCE_COLUMN; // RESOURCE_COLUMN
+ }
+ if (label.equalsIgnoreCase("VIEW")) {
+ return AppConstants.RESOURCE_VIEW; // RESOURCE_VIEW
+ }
+ if (label.equalsIgnoreCase("UDF")) {
+ return AppConstants.RESOURCE_UDF; // RESOURCE_UDF
+ }
+ if (label.equalsIgnoreCase("View Column")) {
+ return AppConstants.RESOURCE_VIEW_COL; // RESOURCE_VIEW_COL
+ }
+ if (label.equalsIgnoreCase("Topology")) {
+ return AppConstants.RESOURCE_TOPOLOGY; // RESOURCE_TOPOLOGY
+ }
+ if (label.equalsIgnoreCase("Service")) {
+ return AppConstants.RESOURCE_SERVICE_NAME; // RESOURCE_SERVICE_NAME
+ }
+ return 0;
+ }
+
+ static public int getEnumFor_XAPermType(String label) {
+ if (label == null) {
+ return 0;
+ }
+ if (label.equalsIgnoreCase("Unknown")) {
+ return AppConstants.XA_PERM_TYPE_UNKNOWN; // XA_PERM_TYPE_UNKNOWN
+ }
+ if (label.equalsIgnoreCase("Reset")) {
+ return AppConstants.XA_PERM_TYPE_RESET; // XA_PERM_TYPE_RESET
+ }
+ if (label.equalsIgnoreCase("Read")) {
+ return AppConstants.XA_PERM_TYPE_READ; // XA_PERM_TYPE_READ
+ }
+ if (label.equalsIgnoreCase("Write")) {
+ return AppConstants.XA_PERM_TYPE_WRITE; // XA_PERM_TYPE_WRITE
+ }
+ if (label.equalsIgnoreCase("Create")) {
+ return AppConstants.XA_PERM_TYPE_CREATE; // XA_PERM_TYPE_CREATE
+ }
+ if (label.equalsIgnoreCase("Delete")) {
+ return AppConstants.XA_PERM_TYPE_DELETE; // XA_PERM_TYPE_DELETE
+ }
+ if (label.equalsIgnoreCase("Admin")) {
+ return AppConstants.XA_PERM_TYPE_ADMIN; // XA_PERM_TYPE_ADMIN
+ }
+ if (label.equalsIgnoreCase("Obfuscate")) {
+ return AppConstants.XA_PERM_TYPE_OBFUSCATE; // XA_PERM_TYPE_OBFUSCATE
+ }
+ if (label.equalsIgnoreCase("Mask")) {
+ return AppConstants.XA_PERM_TYPE_MASK; // XA_PERM_TYPE_MASK
+ }
+ if (label.equalsIgnoreCase("Execute")) {
+ return AppConstants.XA_PERM_TYPE_EXECUTE; // XA_PERM_TYPE_EXECUTE
+ }
+ if (label.equalsIgnoreCase("Select")) {
+ return AppConstants.XA_PERM_TYPE_SELECT; // XA_PERM_TYPE_SELECT
+ }
+ if (label.equalsIgnoreCase("Update")) {
+ return AppConstants.XA_PERM_TYPE_UPDATE; // XA_PERM_TYPE_UPDATE
+ }
+ if (label.equalsIgnoreCase("Drop")) {
+ return AppConstants.XA_PERM_TYPE_DROP; // XA_PERM_TYPE_DROP
+ }
+ if (label.equalsIgnoreCase("Alter")) {
+ return AppConstants.XA_PERM_TYPE_ALTER; // XA_PERM_TYPE_ALTER
+ }
+ if (label.equalsIgnoreCase("Index")) {
+ return AppConstants.XA_PERM_TYPE_INDEX; // XA_PERM_TYPE_INDEX
+ }
+ if (label.equalsIgnoreCase("Lock")) {
+ return AppConstants.XA_PERM_TYPE_LOCK; // XA_PERM_TYPE_LOCK
+ }
+ if (label.equalsIgnoreCase("All")) {
+ return AppConstants.XA_PERM_TYPE_ALL; // XA_PERM_TYPE_ALL
+ }
+ if(label.equalsIgnoreCase("Allow")) {
+ return AppConstants.XA_PERM_TYPE_ALLOW; //XA_PERM_TYPE_ALLOW
+ }
+ if(label.equalsIgnoreCase("submitTopology")) {
+ return AppConstants.XA_PERM_TYPE_SUBMIT_TOPOLOGY; //XA_PERM_TYPE_SUBMIT_TOPOLOGY
+ }
+ if(label.equalsIgnoreCase("fileUpload")) {
+ return AppConstants.XA_PERM_TYPE_FILE_UPLOAD; //XA_PERM_TYPE_FILE_UPLOAD
+ }
+ if(label.equalsIgnoreCase("getNimbusConf")) {
+ return AppConstants.XA_PERM_TYPE_GET_NIMBUS; //XA_PERM_TYPE_GET_NIMBUS
+ }
+ if(label.equalsIgnoreCase("getClusterInfo")) {
+ return AppConstants.XA_PERM_TYPE_GET_CLUSTER_INFO; //XA_PERM_TYPE_GET_CLUSTER_INFO
+ }
+ if(label.equalsIgnoreCase("fileDownload")) {
+ return AppConstants.XA_PERM_TYPE_FILE_DOWNLOAD; //XA_PERM_TYPE_FILE_DOWNLOAD
+ }
+ if(label.equalsIgnoreCase("killTopology")) {
+ return AppConstants.XA_PERM_TYPE_KILL_TOPOLOGY; //XA_PERM_TYPE_KILL_TOPOLOGY
+ }
+ if(label.equalsIgnoreCase("rebalance")) {
+ return AppConstants.XA_PERM_TYPE_REBALANCE; //XA_PERM_TYPE_REBALANCE
+ }
+ if(label.equalsIgnoreCase("activate")) {
+ return AppConstants.XA_PERM_TYPE_ACTIVATE; //XA_PERM_TYPE_ACTIVATE
+ }
+ if(label.equalsIgnoreCase("deactivate")) {
+ return AppConstants.XA_PERM_TYPE_DEACTIVATE; //XA_PERM_TYPE_DEACTIVATE
+ }
+ if(label.equalsIgnoreCase("getTopologyConf")) {
+ return AppConstants.XA_PERM_TYPE_GET_TOPOLOGY_CONF; //XA_PERM_TYPE_GET_TOPOLOGY_CONF
+ }
+ if(label.equalsIgnoreCase("getTopology")) {
+ return AppConstants.XA_PERM_TYPE_GET_TOPOLOGY; //XA_PERM_TYPE_GET_TOPOLOGY
+ }
+ if(label.equalsIgnoreCase("getUserTopology")) {
+ return AppConstants.XA_PERM_TYPE_GET_USER_TOPOLOGY; //XA_PERM_TYPE_GET_USER_TOPOLOGY
+ }
+ if(label.equalsIgnoreCase("getTopologyInfo")) {
+ return AppConstants.XA_PERM_TYPE_GET_TOPOLOGY_INFO; //XA_PERM_TYPE_GET_TOPOLOGY_INFO
+ }
+ if(label.equalsIgnoreCase("uploadNewCredentials")) {
+ return AppConstants.XA_PERM_TYPE_UPLOAD_NEW_CREDENTIAL; //XA_PERM_TYPE_UPLOAD_NEW_CREDENTIAL
+ }
+ return 0;
+ }
+
+ static public int getEnumFor_PolicyType(String label) {
+ if (label == null) {
+ return 0;
+ }
+ if (label.equalsIgnoreCase("Inclusion")) {
+ return AppConstants.POLICY_INCLUSION; // POLICY_INCLUSION
+ }
+ if (label.equalsIgnoreCase("Exclusion")) {
+ return AppConstants.POLICY_EXCLUSION; // POLICY_EXCLUSION
+ }
+ return 0;
+ }
+
+ static public int getEnumFor_DatabaseFlavor(String label) {
+ if (label == null) {
+ return DB_FLAVOR_UNKNOWN; // DB_FLAVOR_UNKNOWN
+ }
+ if ("MYSQL".equalsIgnoreCase(label)) {
+ return DB_FLAVOR_MYSQL; // DB_FLAVOR_MYSQL
+ }
+ if ("ORACLE".equalsIgnoreCase(label)) {
+ return DB_FLAVOR_ORACLE; // DB_FLAVOR_ORACLE
+ }
+ return DB_FLAVOR_UNKNOWN;
+ }
+
+ static public String getLabelFor_DatabaseFlavor(int elementValue) {
+ if (elementValue == DB_FLAVOR_UNKNOWN) {
+ return "UNKNOWN"; // Unknown
+ }
+ if (elementValue == DB_FLAVOR_MYSQL) {
+ return "MYSQL"; // MYSQL
+ }
+ if (elementValue == DB_FLAVOR_ORACLE) {
+ return "ORACLE"; // ORACLE
+ }
+ return null;
+ }
+
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/ContextUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/ContextUtil.java b/security-admin/src/main/java/org/apache/ranger/common/ContextUtil.java
new file mode 100644
index 0000000..026e253
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/ContextUtil.java
@@ -0,0 +1,84 @@
+/*
+ * 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 org.apache.ranger.security.context.XAContextHolder;
+import org.apache.ranger.security.context.XASecurityContext;
+
+public class ContextUtil {
+
+ /**
+ * Singleton class
+ */
+ private ContextUtil() {
+ }
+
+ public static Long getCurrentUserId() {
+ XASecurityContext context = XAContextHolder.getSecurityContext();
+ if (context != null) {
+ UserSessionBase userSession = context.getUserSession();
+ if (userSession != null) {
+ return userSession.getUserId();
+ }
+ }
+ return null;
+ }
+
+ public static String getCurrentUserPublicName() {
+ XASecurityContext context = XAContextHolder.getSecurityContext();
+ if (context != null) {
+ UserSessionBase userSession = context.getUserSession();
+ if (userSession != null) {
+ return userSession.getXXPortalUser().getPublicScreenName();
+ // return userSession.getGjUser().getPublicScreenName();
+ }
+ }
+ return null;
+ }
+
+ public static UserSessionBase getCurrentUserSession() {
+ UserSessionBase userSession = null;
+ XASecurityContext context = XAContextHolder.getSecurityContext();
+ if (context != null) {
+ userSession = context.getUserSession();
+ }
+ return userSession;
+ }
+
+ public static RequestContext getCurrentRequestContext() {
+ XASecurityContext context = XAContextHolder.getSecurityContext();
+ if (context != null) {
+ return context.getRequestContext();
+ }
+ return null;
+ }
+
+ public static String getCurrentUserLoginId() {
+ XASecurityContext context = XAContextHolder.getSecurityContext();
+ if (context != null) {
+ UserSessionBase userSession = context.getUserSession();
+ if (userSession != null) {
+ return userSession.getLoginId();
+ }
+ }
+ return null;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/DateUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/DateUtil.java b/security-admin/src/main/java/org/apache/ranger/common/DateUtil.java
new file mode 100644
index 0000000..a553978
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/DateUtil.java
@@ -0,0 +1,108 @@
+/*
+ * 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.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.TimeZone;
+import org.springframework.stereotype.Component;
+
+
+@Component
+public class DateUtil {
+
+ private static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT+0");
+
+ public Date getDateFromNow(int days) {
+ return getDateFromNow(days, 0, 0);
+ }
+
+ public Date getDateFromNow(int days, int hours, int minutes) {
+ Calendar cal = Calendar.getInstance();
+ cal.add(Calendar.DATE, days);
+ cal.add(Calendar.HOUR, hours);
+ cal.add(Calendar.MINUTE, minutes);
+ return cal.getTime();
+ }
+
+ public static String dateToString(Date date, String dateFromat) {
+ SimpleDateFormat formatter = new SimpleDateFormat(dateFromat);
+ return formatter.format(date).toString();
+ }
+
+ public Date getDateFromGivenDate(Date date, int days, int hours,int minutes, int second) {
+ Calendar cal = Calendar.getInstance();
+ cal.setTime(date);
+ cal.add(Calendar.DATE, days);
+ cal.add(Calendar.HOUR, hours);
+ cal.add(Calendar.MINUTE, minutes);
+ cal.add(Calendar.SECOND, second);
+ return cal.getTime();
+ }
+ /**
+ * useful for converting client time zone Date to UTC Date
+ * @param date
+ * @param mins
+ * @return
+ */
+ public Date addTimeOffset(Date date, int mins) {
+ if (date == null) {
+ return date;
+ }
+ long t = date.getTime();
+ Date newDate = new Date(t + (mins * 60000));
+ return newDate;
+ }
+
+
+ public static Date getUTCDate(){
+ try{
+ Calendar local=Calendar.getInstance();
+ int offset = local.getTimeZone().getOffset(local.getTimeInMillis());
+ GregorianCalendar utc = new GregorianCalendar(gmtTimeZone);
+ utc.setTimeInMillis(local.getTimeInMillis());
+ utc.add(Calendar.MILLISECOND, -offset);
+ return utc.getTime();
+ }catch(Exception ex){
+ return null;
+ }
+ }
+
+ public static Date getUTCDate(long epoh) {
+ if(epoh==0){
+ return null;
+ }
+ try{
+ Calendar local=Calendar.getInstance();
+ int offset = local.getTimeZone().getOffset(epoh);
+ GregorianCalendar utc = new GregorianCalendar(gmtTimeZone);
+ utc.setTimeInMillis(epoh);
+ utc.add(Calendar.MILLISECOND, -offset);
+ return utc.getTime();
+ }catch(Exception ex){
+ return null;
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/ErrorMessageUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/ErrorMessageUtil.java b/security-admin/src/main/java/org/apache/ranger/common/ErrorMessageUtil.java
new file mode 100644
index 0000000..582580c
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/ErrorMessageUtil.java
@@ -0,0 +1,61 @@
+/*
+ * 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.HashMap;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+
+import org.springframework.beans.BeansException;
+import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
+import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
+
+public class ErrorMessageUtil extends PropertyPlaceholderConfigurer {
+ private static Map<String, String> messageMap;
+
+ private ErrorMessageUtil() {
+
+ }
+
+ @Override
+ protected void processProperties(
+ ConfigurableListableBeanFactory beanFactory, Properties props)
+ throws BeansException {
+ super.processProperties(beanFactory, props);
+
+ messageMap = new HashMap<String, String>();
+ Set<Object> keySet = props.keySet();
+
+ for (Object key : keySet) {
+ String keyStr = key.toString();
+ messageMap.put(keyStr, props.getProperty(keyStr));
+ }
+ }
+
+
+ public static String getMessage(String key) {
+ return messageMap.get(key);
+ }
+
+}
\ 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/GUIDUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/GUIDUtil.java b/security-admin/src/main/java/org/apache/ranger/common/GUIDUtil.java
new file mode 100644
index 0000000..c4e0403
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/GUIDUtil.java
@@ -0,0 +1,41 @@
+/*
+ * 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.security.SecureRandom;
+
+public class GUIDUtil implements Serializable {
+
+ private static final long serialVersionUID = -7284237762948427019L;
+
+ static SecureRandom secureRandom = new SecureRandom();
+ static int counter = 0;
+
+ static public String genGUI() {
+ return System.currentTimeMillis() + "_" + secureRandom.nextInt(1000)
+ + "_" + counter++;
+ }
+
+ public static long genLong() {
+ return secureRandom.nextLong();
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/HTTPUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/HTTPUtil.java b/security-admin/src/main/java/org/apache/ranger/common/HTTPUtil.java
new file mode 100644
index 0000000..29b1395
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/HTTPUtil.java
@@ -0,0 +1,65 @@
+/*
+ * 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.Map;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.springframework.stereotype.Component;
+
+@Component
+public class HTTPUtil {
+
+ public static final String USER_AGENT = "User-Agent";
+
+ public static final String IPHONE = "iPhone";
+ public static final String IPAD = "iPad";
+ public static final String IPOD = "iPod";
+ public static final String ANDROID = "Android";
+
+ public int getDeviceType(HttpServletRequest httpRequest) {
+ return getDeviceType(httpRequest.getHeader(USER_AGENT));
+
+ }
+
+ public int getDeviceType(String userAgent) {
+ if (userAgent == null) {
+ return XACommonEnums.DEVICE_UNKNOWN;
+ }
+
+ if (userAgent.contains(IPHONE)) {
+ return XACommonEnums.DEVICE_IPHONE;
+ } else if (userAgent.contains(IPAD)) {
+ return XACommonEnums.DEVICE_IPAD;
+ } else if (userAgent.contains(IPOD)) {
+ return XACommonEnums.DEVICE_IPOD;
+ } else if (userAgent.contains(ANDROID)) {
+ return XACommonEnums.DEVICE_ANDROID;
+ } else {
+ return XACommonEnums.DEVICE_BROWSER;
+ }
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/JSONUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/JSONUtil.java b/security-admin/src/main/java/org/apache/ranger/common/JSONUtil.java
new file mode 100644
index 0000000..cb5f26e
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/JSONUtil.java
@@ -0,0 +1,133 @@
+/*
+ * 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.File;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.common.view.ViewBaseBean;
+import org.codehaus.jackson.JsonGenerationException;
+import org.codehaus.jackson.JsonParseException;
+import org.codehaus.jackson.map.JsonMappingException;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.codehaus.jackson.type.TypeReference;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+@Component
+public class JSONUtil {
+
+ @Autowired
+ RESTErrorUtil restErrorUtil;
+
+ static final Logger logger = Logger.getLogger(JSONUtil.class);
+
+ public File writeJsonToFile(ViewBaseBean viewBean, String fileName)
+ throws JsonGenerationException, JsonMappingException, IOException {
+ ObjectMapper objectMapper = new ObjectMapper();
+
+ if (fileName.length() < 3) {
+ fileName = "file_" + fileName;
+ }
+
+ File file = File.createTempFile(fileName, ".json");
+ objectMapper.defaultPrettyPrintingWriter().writeValue(file, viewBean);
+
+ return file;
+ }
+
+ public Map<String, String> jsonToMap(String jsonStr) {
+ if (jsonStr == null || jsonStr.isEmpty()) {
+ return new HashMap<String, String>();
+ }
+
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ Map<String, String> tempObject = mapper.readValue(jsonStr,
+ new TypeReference<Map<String, String>>() {
+ });
+ return tempObject;
+
+ } catch (JsonParseException e) {
+ throw restErrorUtil.createRESTException(
+ "Invalid input data: " + e.getMessage(),
+ MessageEnums.INVALID_INPUT_DATA);
+ } catch (JsonMappingException e) {
+ throw restErrorUtil.createRESTException(
+ "Invalid input data: " + e.getMessage(),
+ MessageEnums.INVALID_INPUT_DATA);
+ } catch (IOException e) {
+ throw restErrorUtil.createRESTException(
+ "Invalid input data: " + e.getMessage(),
+ MessageEnums.INVALID_INPUT_DATA);
+ }
+
+ }
+
+ public String readMapToString(Map<?, ?> map) {
+ ObjectMapper mapper = new ObjectMapper();
+ String jsonString = null;
+ try {
+ jsonString = mapper.writeValueAsString(map);
+ } catch (JsonParseException e) {
+ throw restErrorUtil.createRESTException(
+ "Invalid input data: " + e.getMessage(),
+ MessageEnums.INVALID_INPUT_DATA);
+ } catch (JsonMappingException e) {
+ throw restErrorUtil.createRESTException(
+ "Invalid input data: " + e.getMessage(),
+ MessageEnums.INVALID_INPUT_DATA);
+ } catch (IOException e) {
+ throw restErrorUtil.createRESTException(
+ "Invalid input data: " + e.getMessage(),
+ MessageEnums.INVALID_INPUT_DATA);
+ }
+ return jsonString;
+ }
+
+ public String writeObjectAsString(ViewBaseBean vObj) {
+ ObjectMapper mapper = new ObjectMapper();
+
+ String jsonStr;
+ try {
+ jsonStr = mapper.writeValueAsString(vObj);
+ return jsonStr;
+ } catch (JsonParseException e) {
+ throw restErrorUtil.createRESTException(
+ "Invalid input data: " + e.getMessage(),
+ MessageEnums.INVALID_INPUT_DATA);
+ } catch (JsonMappingException e) {
+ throw restErrorUtil.createRESTException(
+ "Invalid input data: " + e.getMessage(),
+ MessageEnums.INVALID_INPUT_DATA);
+ } catch (IOException e) {
+ throw restErrorUtil.createRESTException(
+ "Invalid input data: " + e.getMessage(),
+ MessageEnums.INVALID_INPUT_DATA);
+ }
+ }
+
+}
\ 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/MessageEnums.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/MessageEnums.java b/security-admin/src/main/java/org/apache/ranger/common/MessageEnums.java
new file mode 100644
index 0000000..b0090ee
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/MessageEnums.java
@@ -0,0 +1,71 @@
+/*
+ * 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 org.apache.ranger.view.VXMessage;
+
+
+public enum MessageEnums {
+
+ // Note: Please do not format this file. It messes up the indentations
+
+ // Common Errors
+ DATA_NOT_FOUND("xa.error.data_not_found", "Data not found"),
+ OPER_NOT_ALLOWED_FOR_STATE( "xa.error.oper_not_allowed_for_state", "Operation not allowed in current state"),
+ OPER_NOT_ALLOWED_FOR_ENTITY( "xa.error.oper_not_allowed_for_state", "Operation not allowed for entity"),
+ OPER_NO_PERMISSION("xa.error.oper_no_permission", "User doesn't have permission to perform this operation"),
+ DATA_NOT_UPDATABLE( "xa.error.data_not_updatable", "Data not updatable"),
+ ERROR_CREATING_OBJECT("xa.error.create_object", "Error creating object"),
+ ERROR_DUPLICATE_OBJECT("xa.error.duplicate_object", "Error creating duplicate object"),
+ ERROR_SYSTEM("xa.error.system", "System Error. Please try later."),
+ OPER_NO_EXPORT("xa.error.oper_no_export", "repository is disabled"),
+
+ // Common Validations
+ INVALID_PASSWORD( "xa.validation.invalid_password", "Invalid password"),
+ INVALID_INPUT_DATA("xa.validation.invalid_input_data", "Invalid input data"),
+ NO_INPUT_DATA("xa.validation.no_input_data", "Input data is not provided"),
+ INPUT_DATA_OUT_OF_BOUND("xa.validation.data_out_of_bound", "Input data if out of bound");
+
+ String rbKey;
+ String messageDesc;
+
+ MessageEnums(String rbKey, String messageDesc) {
+ this.rbKey = rbKey;
+ this.messageDesc = messageDesc;
+ }
+
+ public VXMessage getMessage() {
+ VXMessage msg = new VXMessage();
+ msg.setName(this.toString());
+ msg.setRbKey(rbKey);
+ msg.setMessage(messageDesc);
+ return msg;
+ }
+
+ public VXMessage getMessage(Long objectId, String fieldName) {
+ VXMessage msg = new VXMessage();
+ msg.setName(this.toString());
+ msg.setRbKey(rbKey);
+ msg.setMessage(messageDesc);
+ msg.setObjectId(objectId);
+ msg.setFieldName(fieldName);
+ return msg;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/MyCallBack.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/MyCallBack.java b/security-admin/src/main/java/org/apache/ranger/common/MyCallBack.java
new file mode 100644
index 0000000..f10c40c
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/MyCallBack.java
@@ -0,0 +1,34 @@
+/*
+ * 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 interface MyCallBack {
+ /**
+ * Make sure to add @Transactional annotation to the implementation method.
+ *
+ * @Override
+ * @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
+ */
+ public Object process(Object data);
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/PasswordUtils.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/PasswordUtils.java b/security-admin/src/main/java/org/apache/ranger/common/PasswordUtils.java
new file mode 100644
index 0000000..f735883
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/PasswordUtils.java
@@ -0,0 +1,159 @@
+/*
+ * 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.IOException;
+import java.util.Map;
+
+import javax.crypto.Cipher;
+import javax.crypto.SecretKey;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.PBEKeySpec;
+import javax.crypto.spec.PBEParameterSpec;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.sun.jersey.core.util.Base64;
+public class PasswordUtils {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class) ;
+
+ private static final char[] ENCRYPT_KEY = "tzL1AKl5uc4NKYaoQ4P3WLGIBFPXWPWdu1fRm9004jtQiV".toCharArray() ;
+
+ private static final byte[] SALT = "f77aLYLo".getBytes() ;
+
+ private static final int ITERATION_COUNT = 17 ;
+
+ private static final String CRYPT_ALGO = "PBEWithMD5AndDES" ;
+
+ private static final String PBE_KEY_ALGO = "PBEWithMD5AndDES" ;
+
+ private static final String LEN_SEPARATOR_STR = ":" ;
+
+ public static String encryptPassword(String aPassword) throws IOException {
+ Map<String, String> env = System.getenv();
+ String encryptKeyStr = env.get("ENCRYPT_KEY") ;
+ char[] encryptKey;
+ if (encryptKeyStr == null) {
+ encryptKey=ENCRYPT_KEY;
+ }else{
+ encryptKey=encryptKeyStr.toCharArray();
+ }
+ String saltStr = env.get("ENCRYPT_SALT") ;
+ byte[] salt;
+ if (saltStr == null) {
+ salt = SALT ;
+ }else{
+ salt=saltStr.getBytes();
+ }
+ String ret = null ;
+ String strToEncrypt = null ;
+ if (aPassword == null) {
+ strToEncrypt = "" ;
+ }
+ else {
+ strToEncrypt = aPassword.length() + LEN_SEPARATOR_STR + aPassword ;
+ }
+ try {
+ Cipher engine = Cipher.getInstance(CRYPT_ALGO) ;
+ PBEKeySpec keySpec = new PBEKeySpec(encryptKey) ;
+ SecretKeyFactory skf = SecretKeyFactory.getInstance(PBE_KEY_ALGO) ;
+ SecretKey key = skf.generateSecret(keySpec) ;
+ engine.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(salt, ITERATION_COUNT));
+ byte[] encryptedStr = engine.doFinal(strToEncrypt.getBytes()) ;
+ ret = new String(Base64.encode(encryptedStr)) ;
+ }
+ catch(Throwable t) {
+ LOG.error("Unable to encrypt password due to error", t);
+ throw new IOException("Unable to encrypt password due to error", t) ;
+ }
+ return ret ;
+ }
+
+ public static String decryptPassword(String aPassword) throws IOException {
+ String ret = null ;
+ Map<String, String> env = System.getenv();
+ String encryptKeyStr = env.get("ENCRYPT_KEY") ;
+ char[] encryptKey;
+ if (encryptKeyStr == null) {
+ encryptKey=ENCRYPT_KEY;
+ }else{
+ encryptKey=encryptKeyStr.toCharArray();
+ }
+ String saltStr = env.get("ENCRYPT_SALT") ;
+ byte[] salt;
+ if (saltStr == null) {
+ salt = SALT ;
+ }else{
+ salt=saltStr.getBytes();
+ }
+ try {
+ byte[] decodedPassword = Base64.decode(aPassword) ;
+ Cipher engine = Cipher.getInstance(CRYPT_ALGO) ;
+ PBEKeySpec keySpec = new PBEKeySpec(encryptKey) ;
+ SecretKeyFactory skf = SecretKeyFactory.getInstance(PBE_KEY_ALGO) ;
+ SecretKey key = skf.generateSecret(keySpec) ;
+ engine.init(Cipher.DECRYPT_MODE, key,new PBEParameterSpec(salt, ITERATION_COUNT));
+ String decrypted = new String(engine.doFinal(decodedPassword)) ;
+ int foundAt = decrypted.indexOf(LEN_SEPARATOR_STR) ;
+ if (foundAt > -1) {
+ if (decrypted.length() > foundAt) {
+ ret = decrypted.substring(foundAt+1) ;
+ }
+ else {
+ ret = "" ;
+ }
+ }
+ else {
+ ret = null;
+ }
+ }
+ catch(Throwable t) {
+ LOG.error("Unable to decrypt password due to error", t);
+ throw new IOException("Unable to decrypt password due to error", t) ;
+ }
+ return ret ;
+ }
+
+ public static void main(String[] args) {
+ String[] testPasswords = { "a", "a123", "dsfdsgdg", "*7263^5#", "", null } ;
+ for(String password : testPasswords) {
+ try {
+ String ePassword = PasswordUtils.encryptPassword(password) ;
+ String dPassword = PasswordUtils.decryptPassword(ePassword) ;
+ if (password == null ) {
+ if (dPassword != null) {
+ throw new RuntimeException("The password expected [" + password + "]. Found [" + dPassword + "]") ;
+ }
+ else {
+ System.out.println("Password: [" + password + "] matched after decrypt. Encrypted: [" + ePassword + "]") ;
+ }
+ }
+ else if (! password.equals(dPassword)) {
+ throw new RuntimeException("The password expected [" + password + "]. Found [" + dPassword + "]") ;
+ }
+ else {
+ System.out.println("Password: [" + password + "] matched after decrypt. Encrypted: [" + ePassword + "]") ;
+ }
+ }
+ catch(IOException ioe) {
+ ioe.printStackTrace();
+ System.out.println("Password verification failed for password [" + password + "]:" + ioe) ;
+ }
+ }
+ }
+}
\ 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/PropertiesUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/PropertiesUtil.java b/security-admin/src/main/java/org/apache/ranger/common/PropertiesUtil.java
new file mode 100644
index 0000000..eeacd11
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/PropertiesUtil.java
@@ -0,0 +1,164 @@
+/*
+ * 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.HashMap;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.credentialapi.CredentialReader;
+import org.springframework.beans.BeansException;
+import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
+import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
+
+
+
+public class PropertiesUtil extends PropertyPlaceholderConfigurer {
+ private static Map<String, String> propertiesMap = new HashMap<String, String>();
+ private static Logger logger = Logger.getLogger(PropertiesUtil.class);
+ private PropertiesUtil() {
+
+ }
+
+ @Override
+ protected void processProperties(
+ ConfigurableListableBeanFactory beanFactory, Properties props)
+ throws BeansException {
+
+ // First let's add the system properties
+ Set<Object> keySet = System.getProperties().keySet();
+ for (Object key : keySet) {
+ String keyStr = key.toString();
+ propertiesMap.put(keyStr, System.getProperties()
+ .getProperty(keyStr).trim());
+ }
+
+ // Let's add our properties now
+ keySet = props.keySet();
+ for (Object key : keySet) {
+ String keyStr = key.toString();
+ propertiesMap.put(keyStr, props.getProperty(keyStr).trim());
+ }
+
+ //update credential from keystore
+ if(propertiesMap!=null && propertiesMap.containsKey("xaDB.jdbc.credential.provider.path") && propertiesMap.containsKey("xaDB.jdbc.credential.alias")){
+ String path=propertiesMap.get("xaDB.jdbc.credential.provider.path");
+ String alias=propertiesMap.get("xaDB.jdbc.credential.alias");
+ if(path!=null && alias!=null){
+ String xaDBPassword=CredentialReader.getDecryptedString(path.trim(),alias.trim());
+ if(xaDBPassword!=null&& !xaDBPassword.trim().isEmpty() &&
+ !xaDBPassword.trim().equalsIgnoreCase("none")){
+ propertiesMap.put("jdbc.password", xaDBPassword);
+ props.put("jdbc.password", xaDBPassword);
+ }else{
+ logger.info("Credential keystore password not applied for XA DB; clear text password shall be applicable");
+ }
+ }
+ }
+ if(propertiesMap!=null && propertiesMap.containsKey("auditDB.jdbc.credential.provider.path") && propertiesMap.containsKey("auditDB.jdbc.credential.alias")){
+ String path=propertiesMap.get("auditDB.jdbc.credential.provider.path");
+ String alias=propertiesMap.get("auditDB.jdbc.credential.alias");
+ if(path!=null && alias!=null){
+ String auditDBPassword=CredentialReader.getDecryptedString(path.trim(), alias.trim());
+ if(auditDBPassword!=null&& !auditDBPassword.trim().isEmpty() &&
+ !auditDBPassword.trim().equalsIgnoreCase("none")){
+ propertiesMap.put("auditDB.jdbc.password", auditDBPassword);
+ props.put("auditDB.jdbc.password", auditDBPassword);
+ }else{
+ logger.info("Credential keystore password not applied for Audit DB; clear text password shall be applicable");
+ }
+ }
+ }
+ super.processProperties(beanFactory, props);
+ }
+
+ public static String getProperty(String key, String defaultValue) {
+ if (key == null) {
+ return null;
+ }
+ String rtrnVal = propertiesMap.get(key);
+ if (rtrnVal == null) {
+ rtrnVal = defaultValue;
+ }
+ return rtrnVal;
+ }
+
+ public static String getProperty(String key) {
+ if (key == null) {
+ return null;
+ }
+ return propertiesMap.get(key);
+ }
+
+ public static String[] getPropertyStringList(String key) {
+ if (key == null) {
+ return null;
+ }
+ String value = propertiesMap.get(key);
+ if (value != null) {
+ String[] splitValues = value.split(",");
+ String[] returnValues = new String[splitValues.length];
+ for (int i = 0; i < splitValues.length; i++) {
+ returnValues[i] = splitValues[i].trim();
+ }
+ return returnValues;
+ } else {
+ return new String[0];
+ }
+ }
+
+ public static Integer getIntProperty(String key, int defaultValue) {
+ if (key == null) {
+ return null;
+ }
+ String rtrnVal = propertiesMap.get(key);
+ if (rtrnVal == null) {
+ return defaultValue;
+ }
+ return Integer.valueOf(rtrnVal);
+ }
+
+ public static Integer getIntProperty(String key) {
+ if (key == null) {
+ return null;
+ }
+ String rtrnVal = propertiesMap.get(key);
+ if (rtrnVal == null) {
+ return null;
+ }
+ return Integer.valueOf(rtrnVal);
+ }
+
+ public static boolean getBooleanProperty(String key, boolean defaultValue) {
+ if (key == null) {
+ return defaultValue;
+ }
+ String value = getProperty(key);
+ if (value == null) {
+ return defaultValue;
+ }
+ return Boolean.parseBoolean(value);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/RESTErrorUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/RESTErrorUtil.java b/security-admin/src/main/java/org/apache/ranger/common/RESTErrorUtil.java
new file mode 100644
index 0000000..9d05ca0
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/RESTErrorUtil.java
@@ -0,0 +1,348 @@
+/*
+ * 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.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.Response;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.view.VXMessage;
+import org.apache.ranger.view.VXResponse;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+
+@Component
+public class RESTErrorUtil {
+
+ static final Logger logger = Logger.getLogger(RESTErrorUtil.class);
+
+ @Autowired
+ StringUtil stringUtil;
+
+ public static final String TRUE = "true";
+
+ public WebApplicationException createRESTException(VXResponse gjResponse) {
+ Response errorResponse = Response
+ .status(javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST)
+ .entity(gjResponse).build();
+
+ WebApplicationException restException = new WebApplicationException(
+ errorResponse);
+ restException.fillInStackTrace();
+ UserSessionBase userSession = ContextUtil.getCurrentUserSession();
+ Long sessionId = null;
+ String loginId = null;
+ if (userSession != null) {
+ loginId = userSession.getLoginId();
+ sessionId = userSession.getSessionId();
+ }
+
+ logger.info("Request failed. SessionId=" + sessionId + ", loginId="
+ + loginId + ", logMessage=" + gjResponse.getMsgDesc(),
+ restException);
+
+ return restException;
+ }
+
+ /**
+ *
+ * @param logMessage
+ * This is optional
+ * @return
+ */
+ public WebApplicationException create403RESTException(String logMessage) {
+ Response errorResponse = Response.status(
+ javax.servlet.http.HttpServletResponse.SC_FORBIDDEN).build();
+
+ WebApplicationException restException = new WebApplicationException(
+ errorResponse);
+ restException.fillInStackTrace();
+ // TODO:Future:Open: Need to log all these and add user to
+ // block list if this is deliberate
+ // Get user information
+ UserSessionBase userSession = ContextUtil.getCurrentUserSession();
+ Long sessionId = null;
+ String loginId = null;
+ String sessionInfo = "";
+ if (userSession != null) {
+ loginId = userSession.getLoginId();
+ sessionInfo = userSession.toString();
+ sessionId = userSession.getSessionId();
+ }
+
+ String requestInfo = "";
+ try {
+ RequestContext reqContext = ContextUtil.getCurrentRequestContext();
+ if (reqContext != null) {
+ requestInfo = reqContext.toString();
+ requestInfo += ", timeTaken="
+ + (System.currentTimeMillis() - reqContext
+ .getStartTime());
+ }
+ } catch (Throwable contextEx) {
+ logger.error("Error getting request info", contextEx);
+ }
+
+ logger.error("Access restricted. SessionId=" + sessionId + ", loginId="
+ + loginId + ", logMessage=" + logMessage + ", requestInfo="
+ + requestInfo + ", sessionInfo=" + sessionInfo, restException);
+
+ return restException;
+ }
+
+
+
+
+ public Integer parseInt(String value, String errorMessage,
+ MessageEnums messageEnum, Long objectId, String fieldName) {
+ try {
+ if (stringUtil.isEmpty(value)) {
+ return null;
+ } else {
+ return new Integer(value.trim());
+ }
+ } catch (Throwable t) {
+ throw createRESTException(errorMessage, messageEnum, objectId,
+ fieldName, value);
+ }
+ }
+
+ public Integer parseInt(String value, int defaultValue,
+ String errorMessage, MessageEnums messageEnum, Long objectId,
+ String fieldName) {
+ try {
+ if (stringUtil.isEmpty(value)) {
+ return new Integer(defaultValue);
+ } else {
+ return new Integer(value.trim());
+ }
+ } catch (Throwable t) {
+ throw createRESTException(errorMessage, messageEnum, objectId,
+ fieldName, value);
+ }
+ }
+
+ public Long parseLong(String value, Long defaultValue) {
+ if (stringUtil.isEmpty(value)) {
+ return defaultValue;
+ }
+ return new Long(value.trim());
+ }
+
+ public Long parseLong(String value, String errorMessage,
+ MessageEnums messageEnum, Long objectId, String fieldName) {
+ try {
+ if (stringUtil.isEmpty(value)) {
+ return null;
+ } else {
+ return new Long(value.trim());
+ }
+ } catch (Throwable t) {
+ throw createRESTException(errorMessage, messageEnum, objectId,
+ fieldName, value);
+ }
+ }
+
+
+
+ public String validateString(String value, String regExStr,
+ String errorMessage, MessageEnums messageEnum, Long objectId,
+ String fieldName) {
+ return validateString(value, regExStr, errorMessage, messageEnum,
+ objectId, fieldName, false);
+
+ }
+
+ public String validateString(String value, String regExStr,
+ String errorMessage, MessageEnums messageEnum, Long objectId,
+ String fieldName, boolean isMandatory) {
+ if (stringUtil.isEmpty(value)) {
+ if (isMandatory) {
+ throw createRESTException(errorMessage,
+ MessageEnums.NO_INPUT_DATA, objectId, fieldName, null);
+ }
+ return null;
+ }
+ value = value.trim();
+ if (value.length() != 0) {
+ if (!stringUtil.validateString(regExStr, value)) {
+ throw createRESTException(errorMessage, messageEnum, objectId,
+ fieldName, value);
+ }
+ return value;
+ } else {
+ return null;
+ }
+
+ }
+
+ public String validateStringForUpdate(String value, String originalValue,
+ String regExStr, String errorMessage, MessageEnums messageEnum,
+ Long objectId, String fieldName) {
+ return validateStringForUpdate(value, originalValue, regExStr,
+ errorMessage, messageEnum, objectId, fieldName, false);
+ }
+
+ public String validateStringForUpdate(String value, String originalValue,
+ String regExStr, String errorMessage, MessageEnums messageEnum,
+ Long objectId, String fieldName, boolean isMandatory) {
+ if (stringUtil.isEmpty(value)) {
+ if (isMandatory) {
+ throw createRESTException(errorMessage,
+ MessageEnums.NO_INPUT_DATA, objectId, fieldName, null);
+ }
+ return null;
+ }
+
+ if (!value.equalsIgnoreCase(originalValue)) {
+ return validateString(value, StringUtil.VALIDATION_NAME,
+ errorMessage, messageEnum, objectId, fieldName);
+ } else {
+ return value;
+ }
+ }
+
+ public void validateStringList(String value, String[] validValues,
+ String errorMessage, Long objectId, String fieldName) {
+ for (int i = 0; i < validValues.length; i++) {
+ if (validValues[i].equals(value)) {
+ return;
+ }
+ }
+ throw createRESTException(errorMessage,
+ MessageEnums.INVALID_INPUT_DATA, objectId, fieldName, value);
+ }
+
+
+
+
+
+ public void validateMinMax(int value, int minValue, int maxValue,
+ String errorMessage, Long objectId, String fieldName) {
+ if (value < minValue || value > maxValue) {
+ throw createRESTException(errorMessage,
+ MessageEnums.INPUT_DATA_OUT_OF_BOUND, objectId, fieldName,
+ "" + value);
+ }
+ }
+
+
+ public WebApplicationException createRESTException(String errorMessage,
+ MessageEnums messageEnum, Long objectId, String fieldName,
+ String logMessage) {
+ List<VXMessage> messageList = new ArrayList<VXMessage>();
+ messageList.add(messageEnum.getMessage(objectId, fieldName));
+
+ VXResponse gjResponse = new VXResponse();
+ gjResponse.setStatusCode(VXResponse.STATUS_ERROR);
+ gjResponse.setMsgDesc(errorMessage);
+ gjResponse.setMessageList(messageList);
+ WebApplicationException webAppEx = createRESTException(gjResponse);
+ logger.info("Validation error:logMessage=" + logMessage + ", response="
+ + gjResponse, webAppEx);
+ return webAppEx;
+ }
+
+ public WebApplicationException createRESTException(String errorMessage,
+ MessageEnums messageEnum) {
+ List<VXMessage> messageList = new ArrayList<VXMessage>();
+ messageList.add(messageEnum.getMessage());
+
+ VXResponse gjResponse = new VXResponse();
+ gjResponse.setStatusCode(VXResponse.STATUS_ERROR);
+ gjResponse.setMsgDesc(errorMessage);
+ gjResponse.setMessageList(messageList);
+ WebApplicationException webAppEx = createRESTException(gjResponse);
+ logger.info("Operation error. response=" + gjResponse, webAppEx);
+ return webAppEx;
+ }
+
+ public WebApplicationException createRESTException(int responseCode,
+ String logMessage, boolean logError) {
+ Response errorResponse = Response
+ .status(responseCode).build();
+
+ WebApplicationException restException = new WebApplicationException(
+ errorResponse);
+ restException.fillInStackTrace();
+ UserSessionBase userSession = ContextUtil.getCurrentUserSession();
+ Long sessionId = null;
+ String loginId = null;
+ if (userSession != null) {
+ loginId = userSession.getLoginId();
+ sessionId = userSession.getSessionId();
+ }
+
+ if (logError) {
+ logger.info("Request failed. SessionId=" + sessionId + ", loginId="
+ + loginId + ", logMessage=" + logMessage,
+ restException);
+ }
+
+ return restException;
+ }
+
+
+ public Date parseDate(String value, String errorMessage,
+ MessageEnums messageEnum, Long objectId, String fieldName,
+ String dateFormat) {
+ try {
+ if (stringUtil.isEmpty(value)) {
+ return null;
+ } else {
+ DateFormat formatter = new SimpleDateFormat(dateFormat);
+ return formatter.parse(value);
+
+ }
+ } catch (Throwable t) {
+ throw createRESTException(errorMessage, messageEnum, objectId,
+ fieldName, value);
+ }
+ }
+
+ public boolean parseBoolean(String value, boolean defaultValue) {
+ if (stringUtil.isEmpty(value)) {
+ return defaultValue;
+ }
+ return TRUE.equalsIgnoreCase(value.trim());
+ }
+
+ public Boolean parseBoolean(String value, String errorMessage,
+ MessageEnums messageEnum, Long objectId, String fieldName) {
+ try {
+ if (stringUtil.isEmpty(value)) {
+ return null;
+ } else {
+ return new Boolean(value.trim());
+ }
+ } catch (Throwable t) {
+ throw createRESTException(errorMessage, messageEnum, objectId,
+ fieldName, value);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/RequestContext.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/RequestContext.java b/security-admin/src/main/java/org/apache/ranger/common/RequestContext.java
new file mode 100644
index 0000000..778cc9a
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/RequestContext.java
@@ -0,0 +1,161 @@
+/*
+ * 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;
+
+public class RequestContext implements Serializable {
+ private static final long serialVersionUID = -7083383106845193385L;
+ private String ipAddress = null;
+ private String userAgent = null;
+ private String requestURL = null;
+ private int deviceType = XACommonEnums.DEVICE_UNKNOWN;
+ private String serverRequestId = null;
+ private boolean isSync = true;
+ private long startTime = System.currentTimeMillis();
+ private int clientTimeOffsetInMinute = 0;
+
+ /**
+ * @return the ipAddress
+ */
+ public String getIpAddress() {
+ return ipAddress;
+ }
+
+ /**
+ * @param ipAddress
+ * the ipAddress to set
+ */
+ public void setIpAddress(String ipAddress) {
+ this.ipAddress = ipAddress;
+ }
+
+ /**
+ * @return the userAgent
+ */
+ public String getUserAgent() {
+ return userAgent;
+ }
+
+ /**
+ * @param userAgent
+ * the userAgent to set
+ */
+ public void setUserAgent(String userAgent) {
+ this.userAgent = userAgent;
+ }
+
+ /**
+ * @return the deviceType
+ */
+ public int getDeviceType() {
+ return deviceType;
+ }
+
+ /**
+ * @param deviceType
+ * the deviceType to set
+ */
+ public void setDeviceType(int deviceType) {
+ this.deviceType = deviceType;
+ }
+
+ /**
+ * @return the serverRequestId
+ */
+ public String getServerRequestId() {
+ return serverRequestId;
+ }
+
+ /**
+ * @param serverRequestId
+ * the serverRequestId to set
+ */
+ public void setServerRequestId(String serverRequestId) {
+ this.serverRequestId = serverRequestId;
+ }
+
+ /**
+ * @return the isSync
+ */
+ public boolean isSync() {
+ return isSync;
+ }
+
+ /**
+ * @param isSync
+ * the isSync to set
+ */
+ public void setSync(boolean isSync) {
+ this.isSync = isSync;
+ }
+
+ /**
+ * @return the requestURL
+ */
+ public String getRequestURL() {
+ return requestURL;
+ }
+
+ /**
+ * @param requestURL
+ * the requestURL to set
+ */
+ public void setRequestURL(String requestURL) {
+ this.requestURL = requestURL;
+ }
+
+ /**
+ * @return the startTime
+ */
+ public long getStartTime() {
+ return startTime;
+ }
+
+ /**
+ * @param startTime
+ * the startTime to set
+ */
+ public void setStartTime(long startTime) {
+ this.startTime = startTime;
+ }
+
+ public int getClientTimeOffsetInMinute() {
+ return clientTimeOffsetInMinute;
+ }
+
+ public void setClientTimeOffsetInMinute(int clientTimeOffset) {
+ this.clientTimeOffsetInMinute = clientTimeOffset;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString() {
+ return "RequestContext [ipAddress=" + ipAddress + ", userAgent="
+ + userAgent + ", requestURL=" + requestURL + ", deviceType="
+ + deviceType + ", serverRequestId=" + serverRequestId
+ + ", isSync=" + isSync + ", startTime=" + startTime + "]";
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/SearchCriteria.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/SearchCriteria.java b/security-admin/src/main/java/org/apache/ranger/common/SearchCriteria.java
new file mode 100644
index 0000000..6a93121
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/SearchCriteria.java
@@ -0,0 +1,199 @@
+/*
+ * 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.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.biz.XABizUtil;
+
+
+public class SearchCriteria {
+ Logger logger = Logger.getLogger(SearchCriteria.class);
+
+ int startIndex = 0;
+ int maxRows = Integer.MAX_VALUE;
+ String sortBy = null;
+ String sortType = null;
+ boolean getCount = true;
+ Number ownerId = null;
+ boolean familyOnly = false;
+ boolean getChildren = false;
+ boolean isDistinct = false;
+ HashMap<String, Object> paramList = new HashMap<String, Object>();
+ Set<String> nullParamList = new HashSet<String>();
+ Set<String> notNullParamList = new HashSet<String>();
+
+ List<SearchGroup> searchGroups = new ArrayList<SearchGroup>();
+
+ /**
+ * @return the startIndex
+ */
+ public int getStartIndex() {
+ return startIndex;
+ }
+
+ /**
+ * @param startIndex
+ * the startIndex to set
+ */
+ public void setStartIndex(int startIndex) {
+ this.startIndex = startIndex;
+ }
+
+ /**
+ * @return the maxRows
+ */
+ public int getMaxRows() {
+ return maxRows;
+ }
+
+ /**
+ * @param maxRows
+ * the maxRows to set
+ */
+ public void setMaxRows(int maxRows) {
+ this.maxRows = maxRows;
+ }
+
+ /**
+ * @return the sortBy
+ */
+ public String getSortBy() {
+ return sortBy;
+ }
+
+ /**
+ * @param sortBy
+ * the sortBy to set
+ */
+ public void setSortBy(String sortBy) {
+ this.sortBy = sortBy;
+ }
+
+ /**
+ * @return the sortType
+ */
+ public String getSortType() {
+ return sortType;
+ }
+
+ /**
+ * @param sortType
+ * the sortType to set
+ */
+ public void setSortType(String sortType) {
+ this.sortType = sortType;
+ }
+
+ public boolean isGetCount() {
+ return getCount;
+ }
+
+ public void setGetCount(boolean getCount) {
+ this.getCount = getCount;
+ }
+
+ public Number getOwnerId() {
+ return ownerId;
+ }
+
+ public void setOwnerId(Number ownerId) {
+ this.ownerId = ownerId;
+ }
+
+ public boolean isGetChildren() {
+ return getChildren;
+ }
+
+ public void setGetChildren(boolean getChildren) {
+ this.getChildren = getChildren;
+ }
+
+ /**
+ * @return the paramList
+ */
+ public HashMap<String, Object> getParamList() {
+ return paramList;
+ }
+
+ /**
+ * @param string
+ * @param caId
+ */
+ public void addParam(String name, Object value) {
+ paramList.put(name, value);
+ }
+
+ public Object getParamValue(String name) {
+ return paramList.get(name);
+ }
+
+ /**
+ * @return the nullParamList
+ */
+ public Set<String> getNullParamList() {
+ return nullParamList;
+ }
+
+ /**
+ * @return the notNullParamList
+ */
+ public Set<String> getNotNullParamList() {
+ return notNullParamList;
+ }
+
+ /**
+ * @return the searchGroups
+ */
+ public List<SearchGroup> getSearchGroups() {
+ return searchGroups;
+ }
+
+ /**
+ * @return the isDistinct
+ */
+ public boolean isDistinct() {
+ return isDistinct;
+ }
+
+ /**
+ * @param isDistinct
+ * the isDistinct to set
+ */
+ public void setDistinct(boolean isDistinct) {
+
+ int dbFlavor = XABizUtil.getDBFlavor();
+ if (isDistinct && dbFlavor == AppConstants.DB_FLAVOR_ORACLE) {
+ isDistinct = false;
+ logger.debug("Database flavor is `ORACLE` so ignoring DISTINCT "
+ + "clause from select statement.");
+ }
+ this.isDistinct = isDistinct;
+ }
+
+}
[25/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/biz/XABizUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/biz/XABizUtil.java b/security-admin/src/main/java/com/xasecure/biz/XABizUtil.java
deleted file mode 100644
index 5a071c4..0000000
--- a/security-admin/src/main/java/com/xasecure/biz/XABizUtil.java
+++ /dev/null
@@ -1,1316 +0,0 @@
-/*
- * 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 com.xasecure.biz;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import com.xasecure.common.GUIDUtil;
-import com.xasecure.common.XACommonEnums;
-import com.xasecure.common.XAConstants;
-import com.xasecure.common.ContextUtil;
-import com.xasecure.common.PropertiesUtil;
-import com.xasecure.common.RESTErrorUtil;
-import com.xasecure.common.StringUtil;
-import com.xasecure.common.UserSessionBase;
-import com.xasecure.common.db.BaseDao;
-import com.xasecure.entity.XXDBBase;
-import com.xasecure.entity.XXPortalUser;
-import com.xasecure.service.AbstractBaseResourceService;
-import com.xasecure.view.VXDataObject;
-import com.xasecure.view.VXString;
-import com.xasecure.view.VXStringList;
-import com.xasecure.view.VXPortalUser;
-
-import java.util.Random;
-
-import com.xasecure.view.VXResponse;
-
-import org.apache.commons.io.FilenameUtils;
-import org.apache.commons.io.IOCase;
-
-import com.xasecure.common.AppConstants;
-import com.xasecure.db.XADaoManager;
-import com.xasecure.entity.XXAsset;
-import com.xasecure.entity.XXGroup;
-import com.xasecure.entity.XXPermMap;
-import com.xasecure.entity.XXResource;
-import com.xasecure.entity.XXTrxLog;
-import com.xasecure.entity.XXUser;
-import com.xasecure.view.VXResource;
-
-@Component
-public class XABizUtil {
- static final Logger logger = Logger.getLogger(XABizUtil.class);
-
- @Autowired
- RESTErrorUtil restErrorUtil;
-
- @Autowired
- XADaoManager daoManager;
-
- @Autowired
- StringUtil stringUtil;
-
- @Autowired
- UserMgr userMgr;
-
- Set<Class<?>> groupEditableClasses;
- private Class<?>[] groupEditableClassesList = {};
-
- Map<String, Integer> classTypeMappings = new HashMap<String, Integer>();
- private int maxFirstNameLength;
- int maxDisplayNameLength = 150;
- boolean defaultAutoApprove = true;
- boolean showBlockedContent = true;
- public final String EMPTY_CONTENT_DISPLAY_NAME = "...";
- boolean enableResourceAccessControl;
- private Random random;
- private static final String PATH_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrst0123456789-_.";
- private static char[] PATH_CHAR_SET = PATH_CHARS.toCharArray();
- private static int PATH_CHAR_SET_LEN = PATH_CHAR_SET.length;
-
- static String fileSeparator = PropertiesUtil.getProperty(
- "xa.file.separator", "/");
-
- public XABizUtil() {
- maxFirstNameLength = Integer.parseInt(PropertiesUtil.getProperty(
- "xa.user.firstname.maxlength", "16"));
- maxDisplayNameLength = PropertiesUtil.getIntProperty(
- "xa.bookmark.name.maxlen", maxDisplayNameLength);
- showBlockedContent = PropertiesUtil.getBooleanProperty(
- "xa.content.show_blocked", showBlockedContent);
- defaultAutoApprove = PropertiesUtil.getBooleanProperty(
- "xa.mod.default", defaultAutoApprove);
-
- groupEditableClasses = new HashSet<Class<?>>(
- Arrays.asList(groupEditableClassesList));
- enableResourceAccessControl = PropertiesUtil.getBooleanProperty(
- "xa.resource.accessControl.enabled", true);
- random = new Random();
- }
-
- public <T extends XXDBBase> List<? extends XXDBBase> getParentObjects(T object) {
- List<XXDBBase> parentObjectList = null;
- // if (checkParentAcess.contains(object.getMyClassType())) {
- // parentObjectList = new ArrayList<MBase>();
- // }
- return parentObjectList;
- }
-
- public int getClassType(Class<?> klass) {
- String className = klass.getName();
- // See if this mapping is already in the database
- Integer classType = classTypeMappings.get(className);
- if (classType == null) {
- // Instantiate the class and call the getClassType method
- if (XXDBBase.class.isAssignableFrom(klass)) {
- try {
- XXDBBase gjObj = (XXDBBase) klass.newInstance();
- classType = gjObj.getMyClassType();
- classTypeMappings.put(className, classType);
- } catch (Throwable ex) {
- logger.error("Error instantiating object for class "
- + className, ex);
- }
- }
- }
- if (classType == null) {
- return XACommonEnums.CLASS_TYPE_NONE;
- } else {
- return classType;
- }
- }
-
- // Access control methods
- public void checkSystemAdminAccess() {
- UserSessionBase currentUserSession = ContextUtil
- .getCurrentUserSession();
- if (currentUserSession != null && currentUserSession.isUserAdmin()) {
- return;
- }
- throw restErrorUtil
- .create403RESTException("Only System Administrators can add accounts");
- }
-
- /**
- * @param contentType
- * @return
- */
- public int getMimeTypeInt(String contentType) {
- if (contentType.equalsIgnoreCase("JPEG")
- || contentType.equalsIgnoreCase("JPG")
- || contentType.endsWith("jpg") || contentType.endsWith("jpeg")) {
- return XAConstants.MIME_JPEG;
- }
- if (contentType.equalsIgnoreCase("PNG") || contentType.endsWith("png")) {
- return XAConstants.MIME_PNG;
- }
- return XAConstants.MIME_UNKNOWN;
- }
-
- /**
- * @param mimeType
- * @return
- */
- public String getMimeType(int mimeType) {
- switch (mimeType) {
- case XAConstants.MIME_JPEG:
- return "jpg";
- case XAConstants.MIME_PNG:
- return "png";
- }
- return "";
- }
-
- /**
- * @param contentType
- * @return
- */
- public String getImageExtension(String contentType) {
- if (contentType.toLowerCase().endsWith("jpg")
- || contentType.toLowerCase().endsWith("jpeg")) {
- return "jpg";
- } else if (contentType.toLowerCase().endsWith("png")) {
- return "png";
- }
- return "";
- }
-
- /**
- * @param file
- * @return
- */
- public String getFileNameWithoutExtension(File file) {
- if (file != null) {
- String fileName = file.getName();
- if (fileName.indexOf(".") > 0) {
- return fileName.substring(0, fileName.indexOf("."));
- }
- return fileName;
-
- }
- return null;
- }
-
- public String getDisplayNameForClassName(XXDBBase obj) {
- String classTypeDisplayName = XAConstants.getLabelFor_ClassTypes(obj
- .getMyClassType());
- if (classTypeDisplayName == null) {
- logger.error(
- "Error get name for class type. obj=" + obj.toString(),
- new Throwable());
- }
- return classTypeDisplayName;
- }
-
- public String getDisplayName(XXDBBase obj) {
- if (obj != null) {
- return handleGetDisplayName(obj.getMyDisplayValue());
- } else {
- return handleGetDisplayName(null);
- }
- }
-
- /**
- * @param displayValue
- * @return
- */
- private String handleGetDisplayName(String displayValue) {
- if (displayValue == null || displayValue.trim().isEmpty()) {
- return EMPTY_CONTENT_DISPLAY_NAME;
- }
-
- if (displayValue.length() > maxDisplayNameLength) {
- displayValue = displayValue.substring(0, maxDisplayNameLength - 3)
- .concat("...");
- }
- return displayValue;
- }
-
- /**
- * @param userProfile
- * @return
- */
- public String generatePublicName(VXPortalUser userProfile, XXPortalUser gjUser) {
- return generatePublicName(userProfile.getFirstName(),
- userProfile.getLastName());
- }
-
- public String generatePublicName(String firstName, String lastName) {
- String publicName = null;
- String fName = firstName;
- if (firstName.length() > maxFirstNameLength) {
- fName = firstName.substring(0, maxFirstNameLength - (1 + 3))
- + "...";
- }
- if (lastName != null && lastName.length() > 0) {
- publicName = fName + " " + lastName.substring(0, 1) + ".";
- }
- return publicName;
- }
-
- public void updateCloneReferences(XXDBBase obj) {
- if (obj == null) {
- return;
- }
- }
-
- public Long getForUserId(XXDBBase resource) {
- return null;
- }
-
- public XXDBBase getMObject(int objClassType, Long objId) {
- XXDBBase obj = null;
-
- if (objId != null) {
- BaseDao<?> dao = daoManager.getDaoForClassType(objClassType);
-
- if (dao != null) {
- obj = (XXDBBase) dao.getById(objId);
- }
- }
-
- return obj;
- }
-
- public XXDBBase getMObject(VXDataObject vXDataObject) {
- if (vXDataObject != null) {
- return getMObject(vXDataObject.getMyClassType(), vXDataObject.getId());
- }
- return null;
- }
-
- public VXDataObject getVObject(int objClassType, Long objId) {
- if (objId == null) {
- return null;
- }
- if (objClassType == XAConstants.CLASS_TYPE_USER_PROFILE) {
- return userMgr.mapXXPortalUserVXPortalUser(daoManager.getXXPortalUser().getById(
- objId));
- }
- try {
- AbstractBaseResourceService<?, ?> myService = AbstractBaseResourceService
- .getService(objClassType);
- if (myService != null) {
- return myService.readResource(objId);
- }
- } catch (Throwable t) {
- logger.error("Error reading resource. objectClassType="
- + objClassType + ", objectId=" + objId, t);
- }
- return null;
- }
-
- public void deleteReferencedObjects(XXDBBase obj) {
-
- if (obj == null) {
- return;
- }
- if (obj.getMyClassType() == XAConstants.CLASS_TYPE_NONE) {
- return;
- }
-
- }
-
- /**
- * @param obj
- */
- void deleteObjects(List<XXDBBase> objs) {
-
- }
-
- void deleteObject(XXDBBase obj) {
- AbstractBaseResourceService<?, ?> myService = AbstractBaseResourceService
- .getService(obj.getMyClassType());
- if (myService != null) {
- myService.deleteResource(obj.getId());
- } else {
- logger.error("Service not found for obj=" + obj, new Throwable());
- }
- }
-
- public <T extends XXDBBase> Class<? extends XXDBBase> getContextObject(
- int objectClassType, Long objectId) {
- return null;
- }
-
- public VXStringList mapStringListToVStringList(List<String> stringList) {
- if (stringList == null) {
- return null;
- }
-
- List<VXString> vStringList = new ArrayList<VXString>();
- for (String str : stringList) {
- VXString vXString = new VXString();
- vXString.setValue(str);
- vStringList.add(vXString);
- }
-
- return new VXStringList(vStringList);
- }
-
- /**
- * return response object if users is having permission on given resource
- *
- * @param vXResource
- * @param permission
- * @return
- */
- public VXResponse hasPermission(VXResource vXResource, int permission) {
-
- VXResponse vXResponse = new VXResponse();
- if (!enableResourceAccessControl) {
- logger.debug("Resource Access Control is disabled !!!");
- return vXResponse;
- }
-
- if (vXResource == null) {
- vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
- vXResponse.setMsgDesc("Please provide valid policy.");
- return vXResponse;
- }
-
- String resourceNames = vXResource.getName();
- if (stringUtil.isEmpty(resourceNames)) {
- vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
- vXResponse.setMsgDesc("Please provide valid policy.");
- return vXResponse;
- }
-
- if (isAdmin()) {
- return vXResponse;
- }
-
- Long xUserId = getXUserId();
- Long assetId = vXResource.getAssetId();
- List<XXResource> xResourceList = daoManager.getXXResource()
- .findByAssetIdAndResourceStatus(assetId,
- AppConstants.STATUS_ENABLED);
-
- XXAsset xAsset = daoManager.getXXAsset().getById(assetId);
- int assetType = xAsset.getAssetType();
-
- vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
- vXResponse.setMsgDesc("Permission Denied !");
-
- if (assetType == AppConstants.ASSET_HIVE) {
- String[] requestResNameList = resourceNames.split(",");
- if (stringUtil.isEmpty(vXResource.getUdfs())) {
- int reqTableType = vXResource.getTableType();
- int reqColumnType = vXResource.getColumnType();
- for (String resourceName : requestResNameList) {
- boolean matchFound = matchHivePolicy(resourceName,
- xResourceList, xUserId, permission, reqTableType,
- reqColumnType, false);
- if (!matchFound) {
- vXResponse.setMsgDesc("You're not permitted to perform "
- + "the action for resource path : "
- + resourceName);
- vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
- return vXResponse;
- }
- }
- } else {
- for (String resourceName : requestResNameList) {
- boolean matchFound = matchHivePolicy(resourceName,
- xResourceList, xUserId, permission);
- if (!matchFound) {
- vXResponse.setMsgDesc("You're not permitted to perform "
- + "the action for resource path : "
- + resourceName);
- vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
- return vXResponse;
- }
- }
- }
- vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
- return vXResponse;
- } else if (assetType == AppConstants.ASSET_HBASE) {
- String[] requestResNameList = resourceNames.split(",");
- for (String resourceName : requestResNameList) {
- boolean matchFound = matchHbasePolicy(resourceName,
- xResourceList, vXResponse, xUserId, permission);
- if (!matchFound) {
- vXResponse.setMsgDesc("You're not permitted to perform "
- + "the action for resource path : " + resourceName);
- vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
- return vXResponse;
- }
- }
- vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
- return vXResponse;
- } else if (assetType == AppConstants.ASSET_HDFS) {
- String[] requestResNameList = resourceNames.split(",");
- for (String resourceName : requestResNameList) {
- boolean matchFound = matchHdfsPolicy(resourceName,
- xResourceList, xUserId, permission);
- if (!matchFound) {
- vXResponse.setMsgDesc("You're not permitted to perform "
- + "the action for resource path : " + resourceName);
- vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
- return vXResponse;
- }
- }
- vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
- return vXResponse;
- } else if (assetType == AppConstants.ASSET_KNOX) {
- String[] requestResNameList = resourceNames.split(",");
- for (String resourceName : requestResNameList) {
- boolean matchFound = matchKnoxPolicy(resourceName,
- xResourceList, vXResponse, xUserId, permission);
- if (!matchFound) {
- vXResponse.setMsgDesc("You're not permitted to perform "
- + "the action for resource path : " + resourceName);
- vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
- return vXResponse;
- }
- }
- vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
- return vXResponse;
- } else if (assetType == AppConstants.ASSET_STORM) {
- String[] requestResNameList = resourceNames.split(",");
- for (String resourceName : requestResNameList) {
- boolean matchFound = matchStormPolicy(resourceName,
- xResourceList, vXResponse, xUserId, permission);
- if (!matchFound) {
- vXResponse.setMsgDesc("You're not permitted to perform "
- + "the action for resource path : " + resourceName);
- vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
- return vXResponse;
- }
- }
- vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
- return vXResponse;
- }
- return vXResponse;
- }
-
- /**
- * return true id current logged in session is owned by admin
- *
- * @return
- */
- public boolean isAdmin() {
- UserSessionBase currentUserSession = ContextUtil
- .getCurrentUserSession();
- if (currentUserSession == null) {
- logger.debug("Unable to find session.");
- return false;
- }
-
- if (currentUserSession.isUserAdmin()) {
- return true;
- }
- return false;
- }
-
- /**
- * returns current user's userID from active user sessions
- *
- * @return
- */
- public Long getXUserId() {
-
- UserSessionBase currentUserSession = ContextUtil
- .getCurrentUserSession();
- if (currentUserSession == null) {
- logger.debug("Unable to find session.");
- return null;
- }
-
- XXPortalUser user = daoManager.getXXPortalUser().getById(
- currentUserSession.getUserId());
- if (user == null) {
- logger.debug("XXPortalUser not found with logged in user id : "
- + currentUserSession.getUserId());
- return null;
- }
-
- XXUser xUser = daoManager.getXXUser().findByUserName(user.getLoginId());
- if (xUser == null) {
- logger.debug("XXPortalUser not found for user id :" + user.getId()
- + " with name " + user.getFirstName());
- return null;
- }
-
- return xUser.getId();
- }
-
- /**
- * returns true if user is having required permission on given Hdfs resource
- *
- * @param resourceName
- * @param xResourceList
- * @param xUserId
- * @param permission
- * @return
- */
- private boolean matchHdfsPolicy(String resourceName,
- List<XXResource> xResourceList, Long xUserId, int permission) {
- boolean matchFound = false;
- resourceName = replaceMetaChars(resourceName);
-
- for (XXResource xResource : xResourceList) {
- if (xResource.getResourceStatus() != AppConstants.STATUS_ENABLED) {
- continue;
- }
- Long resourceId = xResource.getId();
- matchFound = checkUsrPermForPolicy(xUserId, permission, resourceId);
- if (matchFound) {
- matchFound = false;
- String resource = xResource.getName();
- String[] dbResourceNameList = resource.split(",");
- for (String dbResourceName : dbResourceNameList) {
- if (comparePathsForExactMatch(resourceName, dbResourceName)) {
- matchFound = true;
- } else {
- if (xResource.getIsRecursive() == AppConstants.BOOL_TRUE) {
- matchFound = isRecursiveWildCardMatch(resourceName,
- dbResourceName);
- } else {
- matchFound = nonRecursiveWildCardMatch(
- resourceName, dbResourceName);
- }
- }
- if (matchFound) {
- break;
- }
- }
- if (matchFound) {
- break;
- }
- }
- }
- return matchFound;
- }
-
- /**
- * returns true if user is having required permission on given Hbase
- * resource
- *
- * @param resourceName
- * @param xResourceList
- * @param vXResponse
- * @param xUserId
- * @param permission
- * @return
- */
- public boolean matchHbasePolicy(String resourceName,
- List<XXResource> xResourceList, VXResponse vXResponse, Long xUserId,
- int permission) {
- if(stringUtil.isEmpty(resourceName) || xResourceList==null || xUserId==null){
- return false;
- }
-
- String[] splittedResources = stringUtil.split(resourceName, fileSeparator);
- if (splittedResources.length < 1 || splittedResources.length > 3) {
- logger.debug("Invalid resourceName name : " + resourceName);
- return false;
- }
-
- String tblName = splittedResources.length > 0 ? splittedResources[0] : StringUtil.WILDCARD_ASTERISK;
- String colFamName = splittedResources.length > 1 ? splittedResources[1] : StringUtil.WILDCARD_ASTERISK;
- String colName = splittedResources.length > 2 ? splittedResources[2] : StringUtil.WILDCARD_ASTERISK;
-
- boolean policyMatched = false;
- // check all resources whether Hbase policy is enabled in any resource
- // of provided resource list
- for (XXResource xResource : xResourceList) {
- if (xResource.getResourceStatus() != AppConstants.STATUS_ENABLED) {
- continue;
- }
- Long resourceId = xResource.getId();
- boolean hasPermission = checkUsrPermForPolicy(xUserId, permission, resourceId);
- // if permission is enabled then load Tables,column family and
- // columns list from resource
- if (! hasPermission) {
- continue;
- }
-
- // 1. does the policy match the table?
- String[] xTables = stringUtil.isEmpty(xResource.getTables()) ? null : stringUtil.split(xResource.getTables(), ",");
-
- boolean matchFound = (xTables == null || xTables.length == 0) ? true : matchPath(tblName, xTables);
-
- if(matchFound) {
- // 2. does the policy match the column?
- String[] xColumnFamilies = stringUtil.isEmpty(xResource.getColumnFamilies()) ? null : stringUtil.split(xResource.getColumnFamilies(), ",");
-
- matchFound = (xColumnFamilies == null || xColumnFamilies.length == 0) ? true : matchPath(colFamName, xColumnFamilies);
-
- if(matchFound) {
- // 3. does the policy match the columnFamily?
- String[] xColumns = stringUtil.isEmpty(xResource.getColumns()) ? null : stringUtil.split(xResource.getColumns(), ",");
-
- matchFound = (xColumns == null || xColumns.length == 0) ? true : matchPath(colName, xColumns);
- }
- }
-
- if (matchFound) {
- policyMatched = true;
- break;
- }
- }
- return policyMatched;
- }
-
- public boolean matchHivePolicy(String resourceName,
- List<XXResource> xResourceList, Long xUserId, int permission) {
- return matchHivePolicy(resourceName, xResourceList, xUserId,
- permission, 0, 0, true);
- }
-
- /**
- * returns true if user is having required permission on given Hive resource
- *
- * @param resourceName
- * @param xResourceList
- * @param xUserId
- * @param permission
- * @param reqTableType
- * @param reqColumnType
- * @param isUdfPolicy
- * @return
- */
- public boolean matchHivePolicy(String resourceName,
- List<XXResource> xResourceList, Long xUserId, int permission,
- int reqTableType, int reqColumnType, boolean isUdfPolicy) {
-
- if(stringUtil.isEmpty(resourceName) || xResourceList==null || xUserId==null){
- return false;
- }
-
- String[] splittedResources = stringUtil.split(resourceName, fileSeparator);// get list of resources
- if (splittedResources.length < 1 || splittedResources.length > 3) {
- logger.debug("Invalid resource name : " + resourceName);
- return false;
- }
-
- String dbName = splittedResources.length > 0 ? splittedResources[0] : StringUtil.WILDCARD_ASTERISK;
- String tblName = splittedResources.length > 1 ? splittedResources[1] : StringUtil.WILDCARD_ASTERISK;
- String colName = splittedResources.length > 2 ? splittedResources[2] : StringUtil.WILDCARD_ASTERISK;
-
- boolean policyMatched = false;
- for (XXResource xResource : xResourceList) {
- if (xResource.getResourceStatus() != AppConstants.STATUS_ENABLED) {
- continue;
- }
-
- Long resourceId = xResource.getId();
- boolean hasPermission = checkUsrPermForPolicy(xUserId, permission, resourceId);
-
- if (! hasPermission) {
- continue;
- }
-
- // 1. does the policy match the database?
- String[] xDatabases = stringUtil.isEmpty(xResource.getDatabases()) ? null : stringUtil.split(xResource.getDatabases(), ",");
-
- boolean matchFound = (xDatabases == null || xDatabases.length == 0) ? true : matchPath(dbName, xDatabases);
-
- if (! matchFound) {
- continue;
- }
-
- // Type(either UDFs policy or non-UDFs policy) of current policy
- // should be of same as type of policy being iterated
- if (!stringUtil.isEmpty(xResource.getUdfs()) && !isUdfPolicy) {
- continue;
- }
-
- if (isUdfPolicy) {
- // 2. does the policy match the UDF?
- String[] xUdfs = stringUtil.isEmpty(xResource.getUdfs()) ? null : stringUtil.split(xResource.getUdfs(), ",");
-
- if(! matchPath(tblName, xUdfs)) {
- continue;
- } else {
- policyMatched = true;
- break;
- }
- } else {
- // 2. does the policy match the table?
- String[] xTables = stringUtil.isEmpty(xResource.getTables()) ? null : stringUtil.split(xResource.getTables(), ",");
-
- matchFound = (xTables == null || xTables.length == 0) ? true : matchPath(tblName, xTables);
-
- if(xResource.getTableType() == AppConstants.POLICY_EXCLUSION) {
- matchFound = !matchFound;
- }
-
- if (!matchFound) {
- continue;
- }
-
- // 3. does current policy match the column?
- String[] xColumns = stringUtil.isEmpty(xResource.getColumns()) ? null : stringUtil.split(xResource.getColumns(), ",");
-
- matchFound = (xColumns == null || xColumns.length == 0) ? true : matchPath(colName, xColumns);
-
- if(xResource.getColumnType() == AppConstants.POLICY_EXCLUSION) {
- matchFound = !matchFound;
- }
-
- if (!matchFound) {
- continue;
- } else {
- policyMatched = true;
- break;
- }
- }
- }
- return policyMatched;
- }
- /**
- * returns true if user is having required permission on given Hbase
- * resource
- *
- * @param resourceName
- * @param xResourceList
- * @param vXResponse
- * @param xUserId
- * @param permission
- * @return
- */
- private boolean matchKnoxPolicy(String resourceName,
- List<XXResource> xResourceList, VXResponse vXResponse, Long xUserId,
- int permission) {
-
- String[] splittedResources = stringUtil.split(resourceName,
- fileSeparator);
- int numberOfResources = splittedResources.length;
- if (numberOfResources < 1 || numberOfResources > 3) {
- logger.debug("Invalid policy name : " + resourceName);
- return false;
- }
-
- boolean policyMatched = false;
- // check all resources whether Knox policy is enabled in any resource
- // of provided resource list
- for (XXResource xResource : xResourceList) {
- if (xResource.getResourceStatus() != AppConstants.STATUS_ENABLED) {
- continue;
- }
- Long resourceId = xResource.getId();
- boolean hasPermission = checkUsrPermForPolicy(xUserId, permission,
- resourceId);
- // if permission is enabled then load Topologies,services list from resource
- if (hasPermission) {
- String[] xTopologies = (xResource.getTopologies() == null || xResource
- .getTopologies().equalsIgnoreCase("")) ? null : stringUtil
- .split(xResource.getTopologies(), ",");
- String[] xServices = (xResource.getServices() == null || xResource
- .getServices().equalsIgnoreCase("")) ? null
- : stringUtil.split(xResource.getServices(), ",");
-
- boolean matchFound = false;
-
- for (int index = 0; index < numberOfResources; index++) {
- matchFound = false;
- // check whether given table resource matches with any
- // existing topology resource
- if (index == 0) {
- if(xTopologies!=null){
- for (String xTopology : xTopologies) {
- if (matchPath(splittedResources[index], xTopology)) {
- matchFound = true;
- continue;
- }
- }
- }
- if(!matchFound) {
- break;
- }
- } // check whether given service resource matches with
- // any existing service resource
- else if (index == 1) {
- if(xServices!=null){
- for (String xService : xServices) {
- if (matchPath(splittedResources[index],
- xService)) {
- matchFound = true;
- continue;
- }
- }
- }
- if(!matchFound) {
- break;
- }
- }
- }
- if (matchFound) {
- policyMatched = true;
- break;
- }
- }
- }
- return policyMatched;
- }
-
- /**
- * returns true if user is having required permission on given STORM
- * resource
- *
- * @param resourceName
- * @param xResourceList
- * @param vXResponse
- * @param xUserId
- * @param permission
- * @return
- */
- private boolean matchStormPolicy(String resourceName,
- List<XXResource> xResourceList, VXResponse vXResponse, Long xUserId,
- int permission) {
-
- String[] splittedResources = stringUtil.split(resourceName,
- fileSeparator);
- int numberOfResources = splittedResources.length;
- if (numberOfResources < 1 || numberOfResources > 3) {
- logger.debug("Invalid policy name : " + resourceName);
- return false;
- }
-
- boolean policyMatched = false;
- // check all resources whether Knox policy is enabled in any resource
- // of provided resource list
- for (XXResource xResource : xResourceList) {
- if (xResource.getResourceStatus() != AppConstants.STATUS_ENABLED) {
- continue;
- }
- Long resourceId = xResource.getId();
- boolean hasPermission = checkUsrPermForPolicy(xUserId, permission,
- resourceId);
- // if permission is enabled then load Topologies,services list from resource
- if (hasPermission) {
- String[] xTopologies = (xResource.getTopologies() == null || xResource
- .getTopologies().equalsIgnoreCase("")) ? null : stringUtil
- .split(xResource.getTopologies(), ",");
- /*String[] xServices = (xResource.getServices() == null || xResource
- .getServices().equalsIgnoreCase("")) ? null
- : stringUtil.split(xResource.getServices(), ",");*/
-
- boolean matchFound = false;
-
- for (int index = 0; index < numberOfResources; index++) {
- matchFound = false;
- // check whether given table resource matches with any
- // existing topology resource
- if (index == 0) {
- if(xTopologies!=null){
- for (String xTopology : xTopologies) {
- if (matchPath(splittedResources[index], xTopology)) {
- matchFound = true;
- continue;
- }
- }
- }
- } // check whether given service resource matches with
- // any existing service resource
- /*else if (index == 1) {
- if(xServices!=null){
- for (String xService : xServices) {
- if (matchPath(splittedResources[index],
- xService)) {
- matchFound = true;
- continue;
- }
- }
- }
- }*/
- }
- if (matchFound) {
- policyMatched = true;
- break;
- }
- }
- }
- return policyMatched;
- }
-
- /**
- * returns path without meta characters
- *
- * @param path
- * @return
- */
- public String replaceMetaChars(String path) {
- if (path == null || path.isEmpty()) {
- return path;
- }
-
- if (path.contains("*")) {
- String replacement = getRandomString(5, 60);
- path = path.replaceAll("\\*", replacement);
- }
- if (path.contains("?")) {
- String replacement = getRandomString(1, 1);
- path = path.replaceAll("\\?", replacement);
- }
- return path;
- }
-
- /**
- * returns random String of given length range
- *
- * @param minLen
- * @param maxLen
- * @return
- */
- private String getRandomString(int minLen, int maxLen) {
- StringBuilder sb = new StringBuilder();
- int len = getRandomInt(minLen, maxLen);
- for (int i = 0; i < len; i++) {
- int charIdx = random.nextInt(PATH_CHAR_SET_LEN);
- sb.append(PATH_CHAR_SET[charIdx]);
- }
- return sb.toString();
- }
-
- /**
- * return random integer number for given range
- *
- * @param min
- * @param max
- * @return
- */
- private int getRandomInt(int min, int max) {
- if (min == max) {
- return min;
- } else {
- int interval = max - min;
- int randomNum = random.nextInt();
- return ((Math.abs(randomNum) % interval) + min);
- }
- }
-
- /**
- * returns true if given userID is having specified permission on specified
- * resource
- *
- * @param xUserId
- * @param permission
- * @param resourceId
- * @return
- */
- private boolean checkUsrPermForPolicy(Long xUserId, int permission,
- Long resourceId) {
- // this snippet load user groups and permission map list from DB
- List<XXGroup> userGroups = new ArrayList<XXGroup>();
- List<XXPermMap> permMapList = new ArrayList<XXPermMap>();
- userGroups = daoManager.getXXGroup().findByUserId(xUserId);
- permMapList = daoManager.getXXPermMap().findByResourceId(resourceId);
- Long publicGroupId = getPublicGroupId();
- boolean matchFound = false;
- for (XXPermMap permMap : permMapList) {
- if (permMap.getPermType() == permission) {
- if (permMap.getPermFor() == AppConstants.XA_PERM_FOR_GROUP) {
- // check whether permission is enabled for public group or a group to which user belongs
- matchFound = (publicGroupId != null && publicGroupId == permMap.getGroupId()) || isGroupInList(permMap.getGroupId(), userGroups);
- } else if (permMap.getPermFor() == AppConstants.XA_PERM_FOR_USER) {
- // check whether permission is enabled to user
- matchFound = permMap.getUserId().equals(xUserId);
- }
- }
- if (matchFound) {
- break;
- }
- }
- return matchFound;
- }
-
- public Long getPublicGroupId() {
- XXGroup xXGroupPublic = daoManager.getXXGroup().findByGroupName(XAConstants.GROUP_PUBLIC);
-
- return xXGroupPublic != null ? xXGroupPublic.getId() : null;
- }
-
- /**
- * returns true is given group id is in given group list
- *
- * @param groupId
- * @param xGroupList
- * @return
- */
- public boolean isGroupInList(Long groupId, List<XXGroup> xGroupList) {
- for (XXGroup xGroup : xGroupList) {
- if (xGroup.getId().equals(groupId)) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * returns true if given path matches in same level or sub directories with
- * given wild card pattern
- *
- * @param pathToCheck
- * @param wildcardPath
- * @return
- */
- public boolean isRecursiveWildCardMatch(String pathToCheck,
- String wildcardPath) {
- if (pathToCheck != null) {
- if (wildcardPath != null && wildcardPath.equals(fileSeparator)) {
- return true;
- }
- StringBuilder sb = new StringBuilder();
- for (String p : pathToCheck.split(fileSeparator)) {
- sb.append(p);
- boolean matchFound = FilenameUtils.wildcardMatch(sb.toString(),
- wildcardPath);
- if (matchFound) {
- return true;
- }
- sb.append(fileSeparator);
- }
- sb = null;
- }
- return false;
- }
-
- /**
- * return List<Integer>
- *
- * List of all possible parent return type for some specific resourceType
- *
- * @param resourceType
- * , assetType
- *
- */
- public List<Integer> getResorceTypeParentHirearchy(int resourceType,
- int assetType) {
- List<Integer> resourceTypeList = new ArrayList<Integer>();
-
- if (assetType == AppConstants.ASSET_HDFS) {
- resourceTypeList.add(AppConstants.RESOURCE_PATH);
- } else if (assetType == AppConstants.ASSET_HIVE) {
- resourceTypeList.add(AppConstants.RESOURCE_DB);
- if (resourceType == AppConstants.RESOURCE_TABLE) {
- resourceTypeList.add(AppConstants.RESOURCE_TABLE);
- } else if (resourceType == AppConstants.RESOURCE_UDF) {
- resourceTypeList.add(AppConstants.RESOURCE_UDF);
- } else if (resourceType == AppConstants.RESOURCE_COLUMN) {
- resourceTypeList.add(AppConstants.RESOURCE_TABLE);
- resourceTypeList.add(AppConstants.RESOURCE_COLUMN);
- }
- } else if (assetType == AppConstants.ASSET_HBASE) {
- resourceTypeList.add(AppConstants.RESOURCE_TABLE);
- if (resourceType == AppConstants.RESOURCE_COL_FAM) {
- resourceTypeList.add(AppConstants.RESOURCE_COL_FAM);
- } else if (resourceType == AppConstants.RESOURCE_COLUMN) {
- resourceTypeList.add(AppConstants.RESOURCE_COL_FAM);
- resourceTypeList.add(AppConstants.RESOURCE_COLUMN);
- }
- }
-
- return resourceTypeList;
- }
-
- /**
- * return true if both path matches exactly, wild card matching is not
- * checked
- *
- * @param path1
- * @param path2
- * @return
- */
- public boolean comparePathsForExactMatch(String path1, String path2) {
- String pathSeparator = fileSeparator;
- if (!path1.endsWith(pathSeparator)) {
- path1 = path1.concat(pathSeparator);
- }
- if (!path2.endsWith(pathSeparator)) {
- path2 = path2.concat(pathSeparator);
- }
- return path1.equalsIgnoreCase(path2);
- }
-
- /**
- * return true if both path matches at same level path, this function does
- * not match sub directories
- *
- * @param pathToCheck
- * @param wildcardPath
- * @return
- */
- public boolean nonRecursiveWildCardMatch(String pathToCheck,
- String wildcardPath) {
- if (pathToCheck != null && wildcardPath != null) {
-
- List<String> pathToCheckArray = new ArrayList<String>();
- List<String> wildcardPathArray = new ArrayList<String>();
-
- for (String p : pathToCheck.split(fileSeparator)) {
- pathToCheckArray.add(p);
- }
- for (String w : wildcardPath.split(fileSeparator)) {
- wildcardPathArray.add(w);
- }
-
- if (pathToCheckArray.size() == wildcardPathArray.size()) {
- boolean match = false;
- for (int index = 0; index < pathToCheckArray.size(); index++) {
- match = matchPath(pathToCheckArray.get(index),
- wildcardPathArray.get(index));
- if (!match)
- return match;
- }
- return match;
- }
- }
- return false;
- }
-
- /**
- * returns true if first and second path are same
- *
- * @param pathToCheckFragment
- * @param wildCardPathFragment
- * @return
- */
- private boolean matchPath(String pathToCheckFragment,
- String wildCardPathFragment) {
- if(pathToCheckFragment == null || wildCardPathFragment == null) {
- return false;
- }
-
- if (pathToCheckFragment.contains("*")
- || pathToCheckFragment.contains("?")) {
- pathToCheckFragment = replaceMetaChars(pathToCheckFragment);
-
- if (wildCardPathFragment.contains("*")
- || wildCardPathFragment.contains("?")) {
- return FilenameUtils.wildcardMatch(pathToCheckFragment,
- wildCardPathFragment, IOCase.SENSITIVE);
- } else {
- return false;
- }
- } else {
- if (wildCardPathFragment.contains("*")
- || wildCardPathFragment.contains("?")) {
- return FilenameUtils.wildcardMatch(pathToCheckFragment,
- wildCardPathFragment, IOCase.SENSITIVE);
- } else {
- return pathToCheckFragment.trim().equals(
- wildCardPathFragment.trim());
- }
- }
- }
-
- private boolean matchPath(String pathToCheck, String[] wildCardPaths) {
- if (pathToCheck != null && wildCardPaths != null) {
- for (String wildCardPath : wildCardPaths) {
- if (matchPath(pathToCheck, wildCardPath)) {
- return true;
- }
- }
- }
-
- return false;
- }
-
- /**
- * This method returns true if first parameter value is equal to others
- * argument value passed
- *
- * @param checkValue
- * @param otherValues
- * @return
- */
- public static boolean areAllEqual(int checkValue, int... otherValues) {
- for (int value : otherValues) {
- if (value != checkValue) {
- return false;
- }
- }
- return true;
- }
-
- public void createTrxLog(List<XXTrxLog> trxLogList) {
- if (trxLogList == null) {
- return;
- }
-
- UserSessionBase usb = ContextUtil.getCurrentUserSession();
- Long authSessionId = null;
- if (usb != null) {
- authSessionId = ContextUtil.getCurrentUserSession().getSessionId();
- }
- Long trxId = GUIDUtil.genLong();
-
- for (XXTrxLog xTrxLog : trxLogList) {
- xTrxLog.setTransactionId(trxId.toString());
- if (authSessionId != null) {
- xTrxLog.setSessionId("" + authSessionId);
- }
- xTrxLog.setSessionType("Spring Authenticated Session");
- xTrxLog.setRequestId(trxId.toString());
- daoManager.getXXTrxLog().create(xTrxLog);
- }
- }
-
- public static int getDBFlavor() {
-
- String dbFlavor = "";
- boolean dbFlavorPropFound = true;
-
- dbFlavor = PropertiesUtil.getProperty("xa.db.flavor");
- if (dbFlavor == null || dbFlavor.trim().isEmpty()) {
- dbFlavor = PropertiesUtil.getProperty("jdbc.dialect");
- dbFlavorPropFound = false;
- }
-
- if (dbFlavor != null && !dbFlavor.trim().isEmpty()) {
- if (dbFlavorPropFound) {
- if ("MYSQL".equalsIgnoreCase(dbFlavor)) {
- return AppConstants.DB_FLAVOR_MYSQL;
- } else if ("ORACLE".equalsIgnoreCase(dbFlavor)) {
- return AppConstants.DB_FLAVOR_ORACLE;
- } else {
- return AppConstants.DB_FLAVOR_UNKNOWN;
- }
- } else {
- if (dbFlavor.toUpperCase().contains("MYSQL")) {
- return AppConstants.DB_FLAVOR_MYSQL;
- } else if (dbFlavor.toUpperCase().contains("ORACLE")) {
- return AppConstants.DB_FLAVOR_ORACLE;
- } else {
- return AppConstants.DB_FLAVOR_UNKNOWN;
- }
- }
- } else {
- logger.error("Property : xa.db.flavor or jdbc.dialect, not found");
- return AppConstants.DB_FLAVOR_UNKNOWN;
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/biz/XAuditMgr.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/biz/XAuditMgr.java b/security-admin/src/main/java/com/xasecure/biz/XAuditMgr.java
deleted file mode 100644
index dd27722..0000000
--- a/security-admin/src/main/java/com/xasecure/biz/XAuditMgr.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * 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 com.xasecure.biz;
-
-public class XAuditMgr extends XAuditMgrBase {
-
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/biz/XAuditMgrBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/biz/XAuditMgrBase.java b/security-admin/src/main/java/com/xasecure/biz/XAuditMgrBase.java
deleted file mode 100644
index 39f354d..0000000
--- a/security-admin/src/main/java/com/xasecure/biz/XAuditMgrBase.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * 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 com.xasecure.biz;
-
-import com.xasecure.common.*;
-import com.xasecure.service.*;
-import com.xasecure.view.*;
-import org.springframework.beans.factory.annotation.Autowired;
-public class XAuditMgrBase {
-
- @Autowired
- RESTErrorUtil restErrorUtil;
-
- @Autowired
- XTrxLogService xTrxLogService;
-
- @Autowired
- XAccessAuditService xAccessAuditService;
- public VXTrxLog getXTrxLog(Long id){
- return (VXTrxLog)xTrxLogService.readResource(id);
- }
-
- public VXTrxLog createXTrxLog(VXTrxLog vXTrxLog){
- vXTrxLog = (VXTrxLog)xTrxLogService.createResource(vXTrxLog);
- return vXTrxLog;
- }
-
- public VXTrxLog updateXTrxLog(VXTrxLog vXTrxLog) {
- vXTrxLog = (VXTrxLog)xTrxLogService.updateResource(vXTrxLog);
- return vXTrxLog;
- }
-
- public void deleteXTrxLog(Long id, boolean force) {
- if (force) {
- xTrxLogService.deleteResource(id);
- } else {
- throw restErrorUtil.createRESTException(
- "serverMsg.modelMgrBaseDeleteModel",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
- }
-
- public VXTrxLogList searchXTrxLogs(SearchCriteria searchCriteria) {
- return xTrxLogService.searchXTrxLogs(searchCriteria);
- }
-
- public VXLong getXTrxLogSearchCount(SearchCriteria searchCriteria) {
- return xTrxLogService.getSearchCount(searchCriteria,
- xTrxLogService.searchFields);
- }
-
- public VXAccessAudit getXAccessAudit(Long id){
- return (VXAccessAudit)xAccessAuditService.readResource(id);
- }
-
- public VXAccessAudit createXAccessAudit(VXAccessAudit vXAccessAudit){
- vXAccessAudit = (VXAccessAudit)xAccessAuditService.createResource(vXAccessAudit);
- return vXAccessAudit;
- }
-
- public VXAccessAudit updateXAccessAudit(VXAccessAudit vXAccessAudit) {
- vXAccessAudit = (VXAccessAudit)xAccessAuditService.updateResource(vXAccessAudit);
- return vXAccessAudit;
- }
-
- public void deleteXAccessAudit(Long id, boolean force) {
- if (force) {
- xAccessAuditService.deleteResource(id);
- } else {
- throw restErrorUtil.createRESTException(
- "serverMsg.modelMgrBaseDeleteModel",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
- }
-
- public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) {
- return xAccessAuditService.searchXAccessAudits(searchCriteria);
- }
-
- public VXLong getXAccessAuditSearchCount(SearchCriteria searchCriteria) {
- return xAccessAuditService.getSearchCount(searchCriteria,
- xAccessAuditService.searchFields);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/biz/XUserMgr.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/biz/XUserMgr.java b/security-admin/src/main/java/com/xasecure/biz/XUserMgr.java
deleted file mode 100644
index 45922a9..0000000
--- a/security-admin/src/main/java/com/xasecure/biz/XUserMgr.java
+++ /dev/null
@@ -1,452 +0,0 @@
-/*
- * 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 com.xasecure.biz;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import com.xasecure.biz.XABizUtil;
-import com.xasecure.biz.UserMgr;
-import com.xasecure.common.MessageEnums;
-import com.xasecure.common.PropertiesUtil;
-import com.xasecure.common.SearchCriteria;
-import com.xasecure.common.XAConstants;
-import com.xasecure.view.VXPortalUser;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import com.xasecure.db.XADaoManager;
-import com.xasecure.db.XXGroupUserDao;
-import com.xasecure.entity.XXGroup;
-import com.xasecure.entity.XXPortalUser;
-import com.xasecure.entity.XXTrxLog;
-import com.xasecure.service.XUserService;
-import com.xasecure.view.VXGroup;
-import com.xasecure.view.VXGroupList;
-import com.xasecure.view.VXGroupUser;
-import com.xasecure.view.VXGroupUserList;
-import com.xasecure.view.VXUser;
-import com.xasecure.view.VXUserList;
-
-@Component
-public class XUserMgr extends XUserMgrBase {
-
- @Autowired
- XUserService xUserService;
- @Autowired
- XABizUtil msBizUtil;
-
- @Autowired
- UserMgr userMgr;
-
- @Autowired
- XADaoManager daoManager;
-
- @Autowired
- XABizUtil xaBizUtil;
-
- static final Logger logger = Logger.getLogger(XUserMgr.class);
-
- public void deleteXGroup(Long id, boolean force) {
- if (force) {
- SearchCriteria searchCriteria = new SearchCriteria();
- searchCriteria.addParam("xGroupId", id);
- VXGroupUserList vxGroupUserList = searchXGroupUsers(searchCriteria);
- for (VXGroupUser groupUser : vxGroupUserList.getList()) {
- daoManager.getXXGroupUser().remove(groupUser.getId());
- }
- XXGroup xGroup = daoManager.getXXGroup().getById(id);
- daoManager.getXXGroup().remove(id);
- List<XXTrxLog> trxLogList = xGroupService.getTransactionLog(
- xGroupService.populateViewBean(xGroup), "delete");
- xaBizUtil.createTrxLog(trxLogList);
- } else {
- throw restErrorUtil.createRESTException(
- "serverMsg.modelMgrBaseDeleteModel",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
- }
-
- public void deleteXUser(Long id, boolean force) {
- if (force) {
- SearchCriteria searchCriteria = new SearchCriteria();
- searchCriteria.addParam("xUserId", id);
- VXGroupUserList vxGroupUserList = searchXGroupUsers(searchCriteria);
-
- XXGroupUserDao xGroupUserDao = daoManager.getXXGroupUser();
- for (VXGroupUser groupUser : vxGroupUserList.getList()) {
- xGroupUserDao.remove(groupUser.getId());
- }
- // TODO : Need to discuss, why we were not removing user from the
- // system.
-
- // XXUser xUser = daoManager.getXXUser().getById(id);
- daoManager.getXXUser().remove(id);
- //applicationCache.removeUserID(id);
- // Not Supported So Far
- // List<XXTrxLog> trxLogList = xUserService.getTransactionLog(
- // xUserService.populateViewBean(xUser), "delete");
- // xaBizUtil.createTrxLog(trxLogList);
- } else {
- throw restErrorUtil.createRESTException(
- "serverMsg.modelMgrBaseDeleteModel",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
- }
-
- public VXUser getXUserByUserName(String userName) {
- return xUserService.getXUserByUserName(userName);
- }
-
- public VXUser createXUser(VXUser vXUser) {
-
- String userName = vXUser.getName();
- if (userName == null || userName.isEmpty()) {
- throw restErrorUtil.createRESTException("Please provide a valid "
- + "username.", MessageEnums.INVALID_INPUT_DATA);
- }
-
- if (vXUser.getDescription() == null) {
- setUserDesc(vXUser);
- }
-
- String actualPassword = vXUser.getPassword();
-
- VXPortalUser vXPortalUser = new VXPortalUser();
- vXPortalUser.setLoginId(userName);
- vXPortalUser.setFirstName(vXUser.getFirstName());
- vXPortalUser.setLastName(vXUser.getLastName());
- vXPortalUser.setEmailAddress(vXUser.getEmailAddress());
- vXPortalUser.setPublicScreenName(vXUser.getFirstName() +" "+ vXUser.getLastName());
- vXPortalUser.setPassword(actualPassword);
- vXPortalUser.setUserRoleList(vXUser.getUserRoleList());
- vXPortalUser = userMgr.createDefaultAccountUser(vXPortalUser);
-
- VXUser createdXUser = xUserService.createResource(vXUser);
-
- createdXUser.setPassword(actualPassword);
- List<XXTrxLog> trxLogList = xUserService.getTransactionLog(
- createdXUser, "create");
-
- String hiddenPassword = PropertiesUtil.getProperty(
- "xa.password.hidden", "*****");
- createdXUser.setPassword(hiddenPassword);
-
- Collection<Long> groupIdList = vXUser.getGroupIdList();
- List<VXGroupUser> vXGroupUsers = new ArrayList<VXGroupUser>();
- if (groupIdList != null) {
- for (Long groupId : groupIdList) {
- VXGroupUser vXGroupUser = createXGroupUser(
- createdXUser.getId(), groupId);
- // trxLogList.addAll(xGroupUserService.getTransactionLog(
- // vXGroupUser, "create"));
- vXGroupUsers.add(vXGroupUser);
- }
- }
- for (VXGroupUser vXGroupUser : vXGroupUsers) {
- trxLogList.addAll(xGroupUserService.getTransactionLog(vXGroupUser,
- "create"));
- }
- //
- xaBizUtil.createTrxLog(trxLogList);
-
- return createdXUser;
- }
-
- private VXGroupUser createXGroupUser(Long userId, Long groupId) {
- VXGroupUser vXGroupUser = new VXGroupUser();
- vXGroupUser.setParentGroupId(groupId);
- vXGroupUser.setUserId(userId);
- VXGroup vXGroup = xGroupService.readResource(groupId);
- vXGroupUser.setName(vXGroup.getName());
- vXGroupUser = xGroupUserService.createResource(vXGroupUser);
-
- return vXGroupUser;
- }
-
- public VXUser updateXUser(VXUser vXUser) {
- VXPortalUser oldUserProfile = userMgr.getUserProfileByLoginId(vXUser
- .getName());
- VXPortalUser vXPortalUser = new VXPortalUser();
- if(oldUserProfile!=null && oldUserProfile.getId()!=null){
- vXPortalUser.setId(oldUserProfile.getId());
- }
- // TODO : There is a possibility that old user may not exist.
-
-
- vXPortalUser.setFirstName(vXUser.getFirstName());
- vXPortalUser.setLastName(vXUser.getLastName());
- vXPortalUser.setEmailAddress(vXUser.getEmailAddress());
- vXPortalUser.setLoginId(vXUser.getName());
- vXPortalUser.setStatus(vXUser.getStatus());
- vXPortalUser.setUserRoleList(vXUser.getUserRoleList());
- vXPortalUser.setPublicScreenName(vXUser.getFirstName() + " "
- + vXUser.getLastName());
- vXPortalUser.setUserSource(vXUser.getUserSource());
- String hiddenPasswordString = PropertiesUtil.getProperty(
- "xa.password.hidden", "*****");
- String password = vXUser.getPassword();
- if (password != null && password.equals(hiddenPasswordString)) {
- vXPortalUser.setPassword(oldUserProfile.getPassword());
- }
- vXPortalUser.setPassword(password);
-
- Collection<Long> groupIdList = vXUser.getGroupIdList();
- XXPortalUser xXPortalUser = new XXPortalUser();
- xXPortalUser=userMgr.updateUserWithPass(vXPortalUser);
- Collection<String> roleList = new ArrayList<String>();
- if(xXPortalUser!=null){
- roleList=userMgr.getRolesForUser(xXPortalUser);
- }
- if(roleList==null || roleList.size()==0){
- roleList.add(XAConstants.ROLE_USER);
- }
-
- // TODO I've to get the transaction log from here.
- // There is nothing to log anything in XXUser so far.
- vXUser = xUserService.updateResource(vXUser);
- vXUser.setUserRoleList(roleList);
- vXUser.setPassword(password);
- List<XXTrxLog> trxLogList = xUserService.getTransactionLog(vXUser,
- oldUserProfile, "update");
- vXUser.setPassword(hiddenPasswordString);
-
- Long userId = vXUser.getId();
- List<Long> groupUsersToRemove = new ArrayList<Long>();
-
- if (groupIdList != null) {
- SearchCriteria searchCriteria = new SearchCriteria();
- searchCriteria.addParam("xUserId", userId);
- VXGroupUserList vXGroupUserList = xGroupUserService
- .searchXGroupUsers(searchCriteria);
- List<VXGroupUser> vXGroupUsers = vXGroupUserList.getList();
-
- if (vXGroupUsers != null) {
-
- // Create
- for (Long groupId : groupIdList) {
- boolean found = false;
- for (VXGroupUser vXGroupUser : vXGroupUsers) {
- if (groupId.equals(vXGroupUser.getParentGroupId())) {
- found = true;
- break;
- }
- }
- if (!found) {
- VXGroupUser vXGroupUser = createXGroupUser(userId,
- groupId);
- trxLogList.addAll(xGroupUserService.getTransactionLog(
- vXGroupUser, "create"));
- }
- }
-
- // Delete
- for (VXGroupUser vXGroupUser : vXGroupUsers) {
- boolean found = false;
- for (Long groupId : groupIdList) {
- if (groupId.equals(vXGroupUser.getParentGroupId())) {
- trxLogList.addAll(xGroupUserService
- .getTransactionLog(vXGroupUser, "update"));
- found = true;
- break;
- }
- }
- if (!found) {
- // TODO I've to get the transaction log from here.
- trxLogList.addAll(xGroupUserService.getTransactionLog(
- vXGroupUser, "delete"));
- groupUsersToRemove.add(vXGroupUser.getId());
- // xGroupUserService.deleteResource(vXGroupUser.getId());
- }
- }
-
- } else {
- for (Long groupId : groupIdList) {
- VXGroupUser vXGroupUser = createXGroupUser(userId, groupId);
- trxLogList.addAll(xGroupUserService.getTransactionLog(
- vXGroupUser, "create"));
- }
- }
- vXUser.setGroupIdList(groupIdList);
- } else {
- logger.debug("Group id list can't be null for user. Group user "
- + "mapping not updated for user : " + userId);
- }
-
- xaBizUtil.createTrxLog(trxLogList);
-
- for (Long groupUserId : groupUsersToRemove) {
- xGroupUserService.deleteResource(groupUserId);
- }
-
- return vXUser;
- }
-
- public VXUser createXUserWithOutLogin(VXUser vXUser) {
- return xUserService.createXUserWithOutLogin(vXUser);
- }
-
- public VXGroup createXGroup(VXGroup vXGroup) {
- // FIXME Just a hack
- if (vXGroup.getDescription() == null) {
- vXGroup.setDescription(vXGroup.getName());
- }
-
- vXGroup = xGroupService.createResource(vXGroup);
- List<XXTrxLog> trxLogList = xGroupService.getTransactionLog(vXGroup,
- "create");
- xaBizUtil.createTrxLog(trxLogList);
- return vXGroup;
- }
-
- public VXGroup createXGroupWithoutLogin(VXGroup vXGroup) {
- return xGroupService.createXGroupWithOutLogin(vXGroup);
- }
-
- public VXGroupUser createXGroupUser(VXGroupUser vXGroupUser) {
- vXGroupUser = xGroupUserService
- .createXGroupUserWithOutLogin(vXGroupUser);
- return vXGroupUser;
- }
-
- public VXUser getXUser(Long id) {
- return xUserService.readResourceWithOutLogin(id);
-
- }
-
- public VXGroupUser getXGroupUser(Long id) {
- return xGroupUserService.readResourceWithOutLogin(id);
-
- }
-
- public VXGroup getXGroup(Long id) {
- return xGroupService.readResourceWithOutLogin(id);
-
- }
-
- /**
- * // public void createXGroupAndXUser(String groupName, String userName) {
- *
- * // Long groupId; // Long userId; // XXGroup xxGroup = //
- * appDaoManager.getXXGroup().findByGroupName(groupName); // VXGroup
- * vxGroup; // if (xxGroup == null) { // vxGroup = new VXGroup(); //
- * vxGroup.setName(groupName); // vxGroup.setDescription(groupName); //
- * vxGroup.setGroupType(AppConstants.XA_GROUP_USER); //
- * vxGroup.setPriAcctId(1l); // vxGroup.setPriGrpId(1l); // vxGroup =
- * xGroupService.createResource(vxGroup); // groupId = vxGroup.getId(); // }
- * else { // groupId = xxGroup.getId(); // } // XXUser xxUser =
- * appDaoManager.getXXUser().findByUserName(userName); // VXUser vxUser; //
- * if (xxUser == null) { // vxUser = new VXUser(); //
- * vxUser.setName(userName); // vxUser.setDescription(userName); //
- * vxUser.setPriGrpId(1l); // vxUser.setPriAcctId(1l); // vxUser =
- * xUserService.createResource(vxUser); // userId = vxUser.getId(); // }
- * else { // userId = xxUser.getId(); // } // VXGroupUser vxGroupUser = new
- * VXGroupUser(); // vxGroupUser.setParentGroupId(groupId); //
- * vxGroupUser.setUserId(userId); // vxGroupUser.setName(groupName); //
- * vxGroupUser.setPriAcctId(1l); // vxGroupUser.setPriGrpId(1l); //
- * vxGroupUser = xGroupUserService.createResource(vxGroupUser);
- *
- * // }
- */
-
- public void deleteXGroupAndXUser(String groupName, String userName) {
- VXGroup vxGroup = xGroupService.getGroupByGroupName(groupName);
- VXUser vxUser = xUserService.getXUserByUserName(userName);
- SearchCriteria searchCriteria = new SearchCriteria();
- searchCriteria.addParam("xGroupId", vxGroup.getId());
- searchCriteria.addParam("xUserId", vxUser.getId());
- VXGroupUserList vxGroupUserList = xGroupUserService
- .searchXGroupUsers(searchCriteria);
- for (VXGroupUser vxGroupUser : vxGroupUserList.getList()) {
- daoManager.getXXGroupUser().remove(vxGroupUser.getId());
- }
- }
-
- public VXGroupList getXUserGroups(Long xUserId) {
- SearchCriteria searchCriteria = new SearchCriteria();
- searchCriteria.addParam("xUserId", xUserId);
- VXGroupUserList vXGroupUserList = xGroupUserService
- .searchXGroupUsers(searchCriteria);
- VXGroupList vXGroupList = new VXGroupList();
- List<VXGroup> vXGroups = new ArrayList<VXGroup>();
- if (vXGroupUserList != null) {
- List<VXGroupUser> vXGroupUsers = vXGroupUserList.getList();
- Set<Long> groupIdList = new HashSet<Long>();
- for (VXGroupUser vXGroupUser : vXGroupUsers) {
- groupIdList.add(vXGroupUser.getParentGroupId());
- }
- for (Long groupId : groupIdList) {
- VXGroup vXGroup = xGroupService.readResource(groupId);
- vXGroups.add(vXGroup);
- }
- vXGroupList.setVXGroups(vXGroups);
- } else {
- logger.debug("No groups found for user id : " + xUserId);
- }
- return vXGroupList;
- }
-
- public VXUserList getXGroupUsers(Long xGroupId) {
- SearchCriteria searchCriteria = new SearchCriteria();
- searchCriteria.addParam("xGroupId", xGroupId);
- VXGroupUserList vXGroupUserList = xGroupUserService
- .searchXGroupUsers(searchCriteria);
- VXUserList vXUserList = new VXUserList();
-
- List<VXUser> vXUsers = new ArrayList<VXUser>();
- if (vXGroupUserList != null) {
- List<VXGroupUser> vXGroupUsers = vXGroupUserList.getList();
- Set<Long> userIdList = new HashSet<Long>();
- for (VXGroupUser vXGroupUser : vXGroupUsers) {
- userIdList.add(vXGroupUser.getUserId());
- }
- for (Long userId : userIdList) {
- VXUser vXUser = xUserService.readResource(userId);
- vXUsers.add(vXUser);
-
- }
- vXUserList.setVXUsers(vXUsers);
- } else {
- logger.debug("No users found for group id : " + xGroupId);
- }
- return vXUserList;
- }
-
- // FIXME Hack : Unnecessary, to be removed after discussion.
- private void setUserDesc(VXUser vXUser) {
- vXUser.setDescription(vXUser.getName());
- }
-
- @Override
- public VXGroup updateXGroup(VXGroup vXGroup) {
- XXGroup xGroup = daoManager.getXXGroup().getById(vXGroup.getId());
- List<XXTrxLog> trxLogList = xGroupService.getTransactionLog(vXGroup,
- xGroup, "update");
- xaBizUtil.createTrxLog(trxLogList);
- vXGroup = (VXGroup) xGroupService.updateResource(vXGroup);
- return vXGroup;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/biz/XUserMgrBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/biz/XUserMgrBase.java b/security-admin/src/main/java/com/xasecure/biz/XUserMgrBase.java
deleted file mode 100644
index ffb1849..0000000
--- a/security-admin/src/main/java/com/xasecure/biz/XUserMgrBase.java
+++ /dev/null
@@ -1,246 +0,0 @@
-/*
- * 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 com.xasecure.biz;
-
-import com.xasecure.common.*;
-import com.xasecure.service.*;
-import com.xasecure.view.*;
-import org.springframework.beans.factory.annotation.Autowired;
-public class XUserMgrBase {
-
- @Autowired
- RESTErrorUtil restErrorUtil;
-
- @Autowired
- XGroupService xGroupService;
-
- @Autowired
- XUserService xUserService;
-
- @Autowired
- XGroupUserService xGroupUserService;
-
- @Autowired
- XGroupGroupService xGroupGroupService;
-
- @Autowired
- XPermMapService xPermMapService;
-
- @Autowired
- XAuditMapService xAuditMapService;
- public VXGroup getXGroup(Long id){
- return (VXGroup)xGroupService.readResource(id);
- }
-
- public VXGroup createXGroup(VXGroup vXGroup){
- vXGroup = (VXGroup)xGroupService.createResource(vXGroup);
- return vXGroup;
- }
-
- public VXGroup updateXGroup(VXGroup vXGroup) {
- vXGroup = (VXGroup)xGroupService.updateResource(vXGroup);
- return vXGroup;
- }
-
- public void deleteXGroup(Long id, boolean force) {
- if (force) {
- xGroupService.deleteResource(id);
- } else {
- throw restErrorUtil.createRESTException(
- "serverMsg.modelMgrBaseDeleteModel",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
- }
-
- public VXGroupList searchXGroups(SearchCriteria searchCriteria) {
- return xGroupService.searchXGroups(searchCriteria);
- }
-
- public VXLong getXGroupSearchCount(SearchCriteria searchCriteria) {
- return xGroupService.getSearchCount(searchCriteria,
- xGroupService.searchFields);
- }
-
- public VXUser getXUser(Long id){
- return (VXUser)xUserService.readResource(id);
- }
-
- public VXUser createXUser(VXUser vXUser){
- vXUser = (VXUser)xUserService.createResource(vXUser);
- return vXUser;
- }
-
- public VXUser updateXUser(VXUser vXUser) {
- vXUser = (VXUser)xUserService.updateResource(vXUser);
- return vXUser;
- }
-
- public void deleteXUser(Long id, boolean force) {
- if (force) {
- xUserService.deleteResource(id);
- } else {
- throw restErrorUtil.createRESTException(
- "serverMsg.modelMgrBaseDeleteModel",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
- }
-
- public VXUserList searchXUsers(SearchCriteria searchCriteria) {
- return xUserService.searchXUsers(searchCriteria);
- }
-
- public VXLong getXUserSearchCount(SearchCriteria searchCriteria) {
- return xUserService.getSearchCount(searchCriteria,
- xUserService.searchFields);
- }
-
- public VXGroupUser getXGroupUser(Long id){
- return (VXGroupUser)xGroupUserService.readResource(id);
- }
-
- public VXGroupUser createXGroupUser(VXGroupUser vXGroupUser){
- vXGroupUser = (VXGroupUser)xGroupUserService.createResource(vXGroupUser);
- return vXGroupUser;
- }
-
- public VXGroupUser updateXGroupUser(VXGroupUser vXGroupUser) {
- vXGroupUser = (VXGroupUser)xGroupUserService.updateResource(vXGroupUser);
- return vXGroupUser;
- }
-
- public void deleteXGroupUser(Long id, boolean force) {
- if (force) {
- xGroupUserService.deleteResource(id);
- } else {
- throw restErrorUtil.createRESTException(
- "serverMsg.modelMgrBaseDeleteModel",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
- }
-
- public VXGroupUserList searchXGroupUsers(SearchCriteria searchCriteria) {
- return xGroupUserService.searchXGroupUsers(searchCriteria);
- }
-
- public VXLong getXGroupUserSearchCount(SearchCriteria searchCriteria) {
- return xGroupUserService.getSearchCount(searchCriteria,
- xGroupUserService.searchFields);
- }
-
- public VXGroupGroup getXGroupGroup(Long id){
- return (VXGroupGroup)xGroupGroupService.readResource(id);
- }
-
- public VXGroupGroup createXGroupGroup(VXGroupGroup vXGroupGroup){
- vXGroupGroup = (VXGroupGroup)xGroupGroupService.createResource(vXGroupGroup);
- return vXGroupGroup;
- }
-
- public VXGroupGroup updateXGroupGroup(VXGroupGroup vXGroupGroup) {
- vXGroupGroup = (VXGroupGroup)xGroupGroupService.updateResource(vXGroupGroup);
- return vXGroupGroup;
- }
-
- public void deleteXGroupGroup(Long id, boolean force) {
- if (force) {
- xGroupGroupService.deleteResource(id);
- } else {
- throw restErrorUtil.createRESTException(
- "serverMsg.modelMgrBaseDeleteModel",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
- }
-
- public VXGroupGroupList searchXGroupGroups(SearchCriteria searchCriteria) {
- return xGroupGroupService.searchXGroupGroups(searchCriteria);
- }
-
- public VXLong getXGroupGroupSearchCount(SearchCriteria searchCriteria) {
- return xGroupGroupService.getSearchCount(searchCriteria,
- xGroupGroupService.searchFields);
- }
-
- public VXPermMap getXPermMap(Long id){
- return (VXPermMap)xPermMapService.readResource(id);
- }
-
- public VXPermMap createXPermMap(VXPermMap vXPermMap){
- vXPermMap = (VXPermMap)xPermMapService.createResource(vXPermMap);
- return vXPermMap;
- }
-
- public VXPermMap updateXPermMap(VXPermMap vXPermMap) {
- vXPermMap = (VXPermMap)xPermMapService.updateResource(vXPermMap);
- return vXPermMap;
- }
-
- public void deleteXPermMap(Long id, boolean force) {
- if (force) {
- xPermMapService.deleteResource(id);
- } else {
- throw restErrorUtil.createRESTException(
- "serverMsg.modelMgrBaseDeleteModel",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
- }
-
- public VXPermMapList searchXPermMaps(SearchCriteria searchCriteria) {
- return xPermMapService.searchXPermMaps(searchCriteria);
- }
-
- public VXLong getXPermMapSearchCount(SearchCriteria searchCriteria) {
- return xPermMapService.getSearchCount(searchCriteria,
- xPermMapService.searchFields);
- }
-
- public VXAuditMap getXAuditMap(Long id){
- return (VXAuditMap)xAuditMapService.readResource(id);
- }
-
- public VXAuditMap createXAuditMap(VXAuditMap vXAuditMap){
- vXAuditMap = (VXAuditMap)xAuditMapService.createResource(vXAuditMap);
- return vXAuditMap;
- }
-
- public VXAuditMap updateXAuditMap(VXAuditMap vXAuditMap) {
- vXAuditMap = (VXAuditMap)xAuditMapService.updateResource(vXAuditMap);
- return vXAuditMap;
- }
-
- public void deleteXAuditMap(Long id, boolean force) {
- if (force) {
- xAuditMapService.deleteResource(id);
- } else {
- throw restErrorUtil.createRESTException(
- "serverMsg.modelMgrBaseDeleteModel",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
- }
-
- public VXAuditMapList searchXAuditMaps(SearchCriteria searchCriteria) {
- return xAuditMapService.searchXAuditMaps(searchCriteria);
- }
-
- public VXLong getXAuditMapSearchCount(SearchCriteria searchCriteria) {
- return xAuditMapService.getSearchCount(searchCriteria,
- xAuditMapService.searchFields);
- }
-
-}
[22/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/XACommonEnums.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/XACommonEnums.java b/security-admin/src/main/java/com/xasecure/common/XACommonEnums.java
deleted file mode 100644
index d28d274..0000000
--- a/security-admin/src/main/java/com/xasecure/common/XACommonEnums.java
+++ /dev/null
@@ -1,1443 +0,0 @@
-/*
- * 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 com.xasecure.common;
-
-/**
- *
- */
-
-import java.util.*;
-import com.xasecure.common.*;
-
-public class XACommonEnums {
-
- /***************************************************************
- * Enum values for ActiveStatus
- **************************************************************/
- /**
- * STATUS_DISABLED is an element of enum ActiveStatus. Its value is "STATUS_DISABLED".
- */
- public static final int STATUS_DISABLED = 0;
- /**
- * STATUS_ENABLED is an element of enum ActiveStatus. Its value is "STATUS_ENABLED".
- */
- public static final int STATUS_ENABLED = 1;
- /**
- * STATUS_DELETED is an element of enum ActiveStatus. Its value is "STATUS_DELETED".
- */
- public static final int STATUS_DELETED = 2;
-
- /**
- * Max value for enum ActiveStatus_MAX
- */
- public static final int ActiveStatus_MAX = 2;
-
-
- /***************************************************************
- * Enum values for ActivationStatus
- **************************************************************/
- /**
- * ACT_STATUS_DISABLED is an element of enum ActivationStatus. Its value is "ACT_STATUS_DISABLED".
- */
- public static final int ACT_STATUS_DISABLED = 0;
- /**
- * ACT_STATUS_ACTIVE is an element of enum ActivationStatus. Its value is "ACT_STATUS_ACTIVE".
- */
- public static final int ACT_STATUS_ACTIVE = 1;
- /**
- * ACT_STATUS_PENDING_APPROVAL is an element of enum ActivationStatus. Its value is "ACT_STATUS_PENDING_APPROVAL".
- */
- public static final int ACT_STATUS_PENDING_APPROVAL = 2;
- /**
- * ACT_STATUS_PENDING_ACTIVATION is an element of enum ActivationStatus. Its value is "ACT_STATUS_PENDING_ACTIVATION".
- */
- public static final int ACT_STATUS_PENDING_ACTIVATION = 3;
- /**
- * ACT_STATUS_REJECTED is an element of enum ActivationStatus. Its value is "ACT_STATUS_REJECTED".
- */
- public static final int ACT_STATUS_REJECTED = 4;
- /**
- * ACT_STATUS_DEACTIVATED is an element of enum ActivationStatus. Its value is "ACT_STATUS_DEACTIVATED".
- */
- public static final int ACT_STATUS_DEACTIVATED = 5;
- /**
- * ACT_STATUS_PRE_REGISTRATION is an element of enum ActivationStatus. Its value is "ACT_STATUS_PRE_REGISTRATION".
- */
- public static final int ACT_STATUS_PRE_REGISTRATION = 6;
- /**
- * ACT_STATUS_NO_LOGIN is an element of enum ActivationStatus. Its value is "ACT_STATUS_NO_LOGIN".
- */
- public static final int ACT_STATUS_NO_LOGIN = 7;
-
- /**
- * Max value for enum ActivationStatus_MAX
- */
- public static final int ActivationStatus_MAX = 7;
-
-
- /***************************************************************
- * Enum values for BooleanValue
- **************************************************************/
- /**
- * BOOL_NONE is an element of enum BooleanValue. Its value is "BOOL_NONE".
- */
- public static final int BOOL_NONE = 0;
- /**
- * BOOL_TRUE is an element of enum BooleanValue. Its value is "BOOL_TRUE".
- */
- public static final int BOOL_TRUE = 1;
- /**
- * BOOL_FALSE is an element of enum BooleanValue. Its value is "BOOL_FALSE".
- */
- public static final int BOOL_FALSE = 2;
-
- /**
- * Max value for enum BooleanValue_MAX
- */
- public static final int BooleanValue_MAX = 2;
-
-
- /***************************************************************
- * Enum values for DataType
- **************************************************************/
- /**
- * DATA_TYPE_UNKNOWN is an element of enum DataType. Its value is "DATA_TYPE_UNKNOWN".
- */
- public static final int DATA_TYPE_UNKNOWN = 0;
- /**
- * DATA_TYPE_INTEGER is an element of enum DataType. Its value is "DATA_TYPE_INTEGER".
- */
- public static final int DATA_TYPE_INTEGER = 1;
- /**
- * DATA_TYPE_DOUBLE is an element of enum DataType. Its value is "DATA_TYPE_DOUBLE".
- */
- public static final int DATA_TYPE_DOUBLE = 2;
- /**
- * DATA_TYPE_STRING is an element of enum DataType. Its value is "DATA_TYPE_STRING".
- */
- public static final int DATA_TYPE_STRING = 3;
- /**
- * DATA_TYPE_BOOLEAN is an element of enum DataType. Its value is "DATA_TYPE_BOOLEAN".
- */
- public static final int DATA_TYPE_BOOLEAN = 4;
- /**
- * DATA_TYPE_DATE is an element of enum DataType. Its value is "DATA_TYPE_DATE".
- */
- public static final int DATA_TYPE_DATE = 5;
- /**
- * DATA_TYPE_STRING_ENUM is an element of enum DataType. Its value is "DATA_TYPE_STRING_ENUM".
- */
- public static final int DATA_TYPE_STRING_ENUM = 6;
- /**
- * DATA_TYPE_LONG is an element of enum DataType. Its value is "DATA_TYPE_LONG".
- */
- public static final int DATA_TYPE_LONG = 7;
- /**
- * DATA_TYPE_INTEGER_ENUM is an element of enum DataType. Its value is "DATA_TYPE_INTEGER_ENUM".
- */
- public static final int DATA_TYPE_INTEGER_ENUM = 8;
-
- /**
- * Max value for enum DataType_MAX
- */
- public static final int DataType_MAX = 8;
-
-
- /***************************************************************
- * Enum values for DeviceType
- **************************************************************/
- /**
- * DEVICE_UNKNOWN is an element of enum DeviceType. Its value is "DEVICE_UNKNOWN".
- */
- public static final int DEVICE_UNKNOWN = 0;
- /**
- * DEVICE_BROWSER is an element of enum DeviceType. Its value is "DEVICE_BROWSER".
- */
- public static final int DEVICE_BROWSER = 1;
- /**
- * DEVICE_IPHONE is an element of enum DeviceType. Its value is "DEVICE_IPHONE".
- */
- public static final int DEVICE_IPHONE = 2;
- /**
- * DEVICE_IPAD is an element of enum DeviceType. Its value is "DEVICE_IPAD".
- */
- public static final int DEVICE_IPAD = 3;
- /**
- * DEVICE_IPOD is an element of enum DeviceType. Its value is "DEVICE_IPOD".
- */
- public static final int DEVICE_IPOD = 4;
- /**
- * DEVICE_ANDROID is an element of enum DeviceType. Its value is "DEVICE_ANDROID".
- */
- public static final int DEVICE_ANDROID = 5;
-
- /**
- * Max value for enum DeviceType_MAX
- */
- public static final int DeviceType_MAX = 5;
-
-
- /***************************************************************
- * Enum values for DiffLevel
- **************************************************************/
- /**
- * DIFF_UNKNOWN is an element of enum DiffLevel. Its value is "DIFF_UNKNOWN".
- */
- public static final int DIFF_UNKNOWN = 0;
- /**
- * DIFF_LOW is an element of enum DiffLevel. Its value is "DIFF_LOW".
- */
- public static final int DIFF_LOW = 1;
- /**
- * DIFF_MEDIUM is an element of enum DiffLevel. Its value is "DIFF_MEDIUM".
- */
- public static final int DIFF_MEDIUM = 2;
- /**
- * DIFF_HIGH is an element of enum DiffLevel. Its value is "DIFF_HIGH".
- */
- public static final int DIFF_HIGH = 3;
-
- /**
- * Max value for enum DiffLevel_MAX
- */
- public static final int DiffLevel_MAX = 3;
-
-
- /***************************************************************
- * Enum values for FileType
- **************************************************************/
- /**
- * FILE_FILE is an element of enum FileType. Its value is "FILE_FILE".
- */
- public static final int FILE_FILE = 0;
- /**
- * FILE_DIR is an element of enum FileType. Its value is "FILE_DIR".
- */
- public static final int FILE_DIR = 1;
-
- /**
- * Max value for enum FileType_MAX
- */
- public static final int FileType_MAX = 1;
-
-
- /***************************************************************
- * Enum values for FreqType
- **************************************************************/
- /**
- * FREQ_NONE is an element of enum FreqType. Its value is "FREQ_NONE".
- */
- public static final int FREQ_NONE = 0;
- /**
- * FREQ_MANUAL is an element of enum FreqType. Its value is "FREQ_MANUAL".
- */
- public static final int FREQ_MANUAL = 1;
- /**
- * FREQ_HOURLY is an element of enum FreqType. Its value is "FREQ_HOURLY".
- */
- public static final int FREQ_HOURLY = 2;
- /**
- * FREQ_DAILY is an element of enum FreqType. Its value is "FREQ_DAILY".
- */
- public static final int FREQ_DAILY = 3;
- /**
- * FREQ_WEEKLY is an element of enum FreqType. Its value is "FREQ_WEEKLY".
- */
- public static final int FREQ_WEEKLY = 4;
- /**
- * FREQ_BI_WEEKLY is an element of enum FreqType. Its value is "FREQ_BI_WEEKLY".
- */
- public static final int FREQ_BI_WEEKLY = 5;
- /**
- * FREQ_MONTHLY is an element of enum FreqType. Its value is "FREQ_MONTHLY".
- */
- public static final int FREQ_MONTHLY = 6;
-
- /**
- * Max value for enum FreqType_MAX
- */
- public static final int FreqType_MAX = 6;
-
-
- /***************************************************************
- * Enum values for MimeType
- **************************************************************/
- /**
- * MIME_UNKNOWN is an element of enum MimeType. Its value is "MIME_UNKNOWN".
- */
- public static final int MIME_UNKNOWN = 0;
- /**
- * MIME_TEXT is an element of enum MimeType. Its value is "MIME_TEXT".
- */
- public static final int MIME_TEXT = 1;
- /**
- * MIME_HTML is an element of enum MimeType. Its value is "MIME_HTML".
- */
- public static final int MIME_HTML = 2;
- /**
- * MIME_PNG is an element of enum MimeType. Its value is "MIME_PNG".
- */
- public static final int MIME_PNG = 3;
- /**
- * MIME_JPEG is an element of enum MimeType. Its value is "MIME_JPEG".
- */
- public static final int MIME_JPEG = 4;
-
- /**
- * Max value for enum MimeType_MAX
- */
- public static final int MimeType_MAX = 4;
-
-
- /***************************************************************
- * Enum values for NumberFormat
- **************************************************************/
- /**
- * NUM_FORMAT_NONE is an element of enum NumberFormat. Its value is "NUM_FORMAT_NONE".
- */
- public static final int NUM_FORMAT_NONE = 0;
- /**
- * NUM_FORMAT_NUMERIC is an element of enum NumberFormat. Its value is "NUM_FORMAT_NUMERIC".
- */
- public static final int NUM_FORMAT_NUMERIC = 1;
- /**
- * NUM_FORMAT_ALPHA is an element of enum NumberFormat. Its value is "NUM_FORMAT_ALPHA".
- */
- public static final int NUM_FORMAT_ALPHA = 2;
- /**
- * NUM_FORMAT_ROMAN is an element of enum NumberFormat. Its value is "NUM_FORMAT_ROMAN".
- */
- public static final int NUM_FORMAT_ROMAN = 3;
-
- /**
- * Max value for enum NumberFormat_MAX
- */
- public static final int NumberFormat_MAX = 3;
-
-
- /***************************************************************
- * Enum values for ObjectStatus
- **************************************************************/
- /**
- * OBJ_STATUS_ACTIVE is an element of enum ObjectStatus. Its value is "OBJ_STATUS_ACTIVE".
- */
- public static final int OBJ_STATUS_ACTIVE = 0;
- /**
- * OBJ_STATUS_DELETED is an element of enum ObjectStatus. Its value is "OBJ_STATUS_DELETED".
- */
- public static final int OBJ_STATUS_DELETED = 1;
- /**
- * OBJ_STATUS_ARCHIVED is an element of enum ObjectStatus. Its value is "OBJ_STATUS_ARCHIVED".
- */
- public static final int OBJ_STATUS_ARCHIVED = 2;
-
- /**
- * Max value for enum ObjectStatus_MAX
- */
- public static final int ObjectStatus_MAX = 2;
-
-
- /***************************************************************
- * Enum values for PasswordResetStatus
- **************************************************************/
- /**
- * PWD_RESET_ACTIVE is an element of enum PasswordResetStatus. Its value is "PWD_RESET_ACTIVE".
- */
- public static final int PWD_RESET_ACTIVE = 0;
- /**
- * PWD_RESET_USED is an element of enum PasswordResetStatus. Its value is "PWD_RESET_USED".
- */
- public static final int PWD_RESET_USED = 1;
- /**
- * PWD_RESET_EXPIRED is an element of enum PasswordResetStatus. Its value is "PWD_RESET_EXPIRED".
- */
- public static final int PWD_RESET_EXPIRED = 2;
- /**
- * PWD_RESET_DISABLED is an element of enum PasswordResetStatus. Its value is "PWD_RESET_DISABLED".
- */
- public static final int PWD_RESET_DISABLED = 3;
-
- /**
- * Max value for enum PasswordResetStatus_MAX
- */
- public static final int PasswordResetStatus_MAX = 3;
-
-
- /***************************************************************
- * Enum values for PriorityType
- **************************************************************/
- /**
- * PRIORITY_NORMAL is an element of enum PriorityType. Its value is "PRIORITY_NORMAL".
- */
- public static final int PRIORITY_NORMAL = 0;
- /**
- * PRIORITY_LOW is an element of enum PriorityType. Its value is "PRIORITY_LOW".
- */
- public static final int PRIORITY_LOW = 1;
- /**
- * PRIORITY_MEDIUM is an element of enum PriorityType. Its value is "PRIORITY_MEDIUM".
- */
- public static final int PRIORITY_MEDIUM = 2;
- /**
- * PRIORITY_HIGH is an element of enum PriorityType. Its value is "PRIORITY_HIGH".
- */
- public static final int PRIORITY_HIGH = 3;
-
- /**
- * Max value for enum PriorityType_MAX
- */
- public static final int PriorityType_MAX = 3;
-
-
- /***************************************************************
- * Enum values for ProgressStatus
- **************************************************************/
- /**
- * PROGRESS_PENDING is an element of enum ProgressStatus. Its value is "PROGRESS_PENDING".
- */
- public static final int PROGRESS_PENDING = 0;
- /**
- * PROGRESS_IN_PROGRESS is an element of enum ProgressStatus. Its value is "PROGRESS_IN_PROGRESS".
- */
- public static final int PROGRESS_IN_PROGRESS = 1;
- /**
- * PROGRESS_COMPLETE is an element of enum ProgressStatus. Its value is "PROGRESS_COMPLETE".
- */
- public static final int PROGRESS_COMPLETE = 2;
- /**
- * PROGRESS_ABORTED is an element of enum ProgressStatus. Its value is "PROGRESS_ABORTED".
- */
- public static final int PROGRESS_ABORTED = 3;
- /**
- * PROGRESS_FAILED is an element of enum ProgressStatus. Its value is "PROGRESS_FAILED".
- */
- public static final int PROGRESS_FAILED = 4;
-
- /**
- * Max value for enum ProgressStatus_MAX
- */
- public static final int ProgressStatus_MAX = 4;
-
-
- /***************************************************************
- * Enum values for RelationType
- **************************************************************/
- /**
- * REL_NONE is an element of enum RelationType. Its value is "REL_NONE".
- */
- public static final int REL_NONE = 0;
- /**
- * REL_SELF is an element of enum RelationType. Its value is "REL_SELF".
- */
- public static final int REL_SELF = 1;
-
- /**
- * Max value for enum RelationType_MAX
- */
- public static final int RelationType_MAX = 1;
-
-
- /***************************************************************
- * Enum values for UserSource
- **************************************************************/
- /**
- * USER_APP is an element of enum UserSource. Its value is "USER_APP".
- */
- public static final int USER_APP = 0;
- public static final int USER_EXTERNAL = 1;
- public static final int USER_AD= 2;
- public static final int USER_LDAP = 3;
- public static final int USER_UNIX = 4;
- public static final int USER_REPO = 5;
-
- public static final int GROUP_INTERNAL = 0;
- public static final int GROUP_EXTERNAL = 1;
- public static final int GROUP_AD= 2;
- public static final int GROUP_LDAP = 3;
- public static final int GROUP_UNIX = 4;
- public static final int GROUP_REPO = 5;
- /**
- * USER_GOOGLE is an element of enum UserSource. Its value is "USER_GOOGLE".
- */
- //public static final int USER_GOOGLE = 1;
- /**
- * USER_FB is an element of enum UserSource. Its value is "USER_FB".
- */
- //public static final int USER_FB = 2;
-
- /**
- * Max value for enum UserSource_MAX
- */
- public static final int UserSource_MAX = 5;
-
-
- /***************************************************************
- * Enum values for AssetType
- **************************************************************/
- /**
- * ASSET_UNKNOWN is an element of enum AssetType. Its value is "ASSET_UNKNOWN".
- */
- public static final int ASSET_UNKNOWN = 0;
- /**
- * ASSET_HDFS is an element of enum AssetType. Its value is "ASSET_HDFS".
- */
- public static final int ASSET_HDFS = 1;
- /**
- * ASSET_HBASE is an element of enum AssetType. Its value is "ASSET_HBASE".
- */
- public static final int ASSET_HBASE = 2;
- /**
- * ASSET_HIVE is an element of enum AssetType. Its value is "ASSET_HIVE".
- */
- public static final int ASSET_HIVE = 3;
- /**
- * ASSET_HIVE is an element of enum AssetType. Its value is "ASSET_HIVE".
- */
- public static final int ASSET_AGENT = 4;
- /**
- * ASSET_HIVE is an element of enum AssetType. Its value is "ASSET_HIVE".
- */
- public static final int ASSET_KNOX = 5;
- /**
- * ASSET_HIVE is an element of enum AssetType. Its value is "ASSET_HIVE".
- */
- public static final int ASSET_STORM = 6;
-
- /**
- * Max value for enum AssetType_MAX
- */
- public static final int AssetType_MAX = 6;
-
-
- /***************************************************************
- * Enum values for AccessResult
- **************************************************************/
- /**
- * ACCESS_RESULT_DENIED is an element of enum AccessResult. Its value is "ACCESS_RESULT_DENIED".
- */
- public static final int ACCESS_RESULT_DENIED = 0;
- /**
- * ACCESS_RESULT_ALLOWED is an element of enum AccessResult. Its value is "ACCESS_RESULT_ALLOWED".
- */
- public static final int ACCESS_RESULT_ALLOWED = 1;
-
- /**
- * Max value for enum AccessResult_MAX
- */
- public static final int AccessResult_MAX = 1;
-
-
- /***************************************************************
- * Enum values for PolicyType
- **************************************************************/
- /**
- * POLICY_INCLUSION is an element of enum PolicyType. Its value is "POLICY_INCLUSION".
- */
- public static final int POLICY_INCLUSION = 0;
- /**
- * POLICY_EXCLUSION is an element of enum PolicyType. Its value is "POLICY_EXCLUSION".
- */
- public static final int POLICY_EXCLUSION = 1;
-
- /**
- * Max value for enum PolicyType_MAX
- */
- public static final int PolicyType_MAX = 1;
-
-
- /***************************************************************
- * Enum values for XAAuditType
- **************************************************************/
- /**
- * XA_AUDIT_TYPE_UNKNOWN is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_UNKNOWN".
- */
- public static final int XA_AUDIT_TYPE_UNKNOWN = 0;
- /**
- * XA_AUDIT_TYPE_ALL is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_ALL".
- */
- public static final int XA_AUDIT_TYPE_ALL = 1;
- /**
- * XA_AUDIT_TYPE_READ is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_READ".
- */
- public static final int XA_AUDIT_TYPE_READ = 2;
- /**
- * XA_AUDIT_TYPE_WRITE is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_WRITE".
- */
- public static final int XA_AUDIT_TYPE_WRITE = 3;
- /**
- * XA_AUDIT_TYPE_CREATE is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_CREATE".
- */
- public static final int XA_AUDIT_TYPE_CREATE = 4;
- /**
- * XA_AUDIT_TYPE_DELETE is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_DELETE".
- */
- public static final int XA_AUDIT_TYPE_DELETE = 5;
- /**
- * XA_AUDIT_TYPE_LOGIN is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_LOGIN".
- */
- public static final int XA_AUDIT_TYPE_LOGIN = 6;
-
- /**
- * Max value for enum XAAuditType_MAX
- */
- public static final int XAAuditType_MAX = 6;
-
-
- /***************************************************************
- * Enum values for ResourceType
- **************************************************************/
- /**
- * RESOURCE_UNKNOWN is an element of enum ResourceType. Its value is "RESOURCE_UNKNOWN".
- */
- public static final int RESOURCE_UNKNOWN = 0;
- /**
- * RESOURCE_PATH is an element of enum ResourceType. Its value is "RESOURCE_PATH".
- */
- public static final int RESOURCE_PATH = 1;
- /**
- * RESOURCE_DB is an element of enum ResourceType. Its value is "RESOURCE_DB".
- */
- public static final int RESOURCE_DB = 2;
- /**
- * RESOURCE_TABLE is an element of enum ResourceType. Its value is "RESOURCE_TABLE".
- */
- public static final int RESOURCE_TABLE = 3;
- /**
- * RESOURCE_COL_FAM is an element of enum ResourceType. Its value is "RESOURCE_COL_FAM".
- */
- public static final int RESOURCE_COL_FAM = 4;
- /**
- * RESOURCE_COLUMN is an element of enum ResourceType. Its value is "RESOURCE_COLUMN".
- */
- public static final int RESOURCE_COLUMN = 5;
- /**
- * RESOURCE_VIEW is an element of enum ResourceType. Its value is "RESOURCE_VIEW".
- */
- public static final int RESOURCE_VIEW = 6;
- /**
- * RESOURCE_UDF is an element of enum ResourceType. Its value is "RESOURCE_UDF".
- */
- public static final int RESOURCE_UDF = 7;
- /**
- * RESOURCE_VIEW_COL is an element of enum ResourceType. Its value is "RESOURCE_VIEW_COL".
- */
- public static final int RESOURCE_VIEW_COL = 8;
-
- /**
- * Max value for enum ResourceType_MAX
- */
- public static final int ResourceType_MAX = 8;
-
-
- /***************************************************************
- * Enum values for XAGroupType
- **************************************************************/
- /**
- * XA_GROUP_UNKNOWN is an element of enum XAGroupType. Its value is "XA_GROUP_UNKNOWN".
- */
- public static final int XA_GROUP_UNKNOWN = 0;
- /**
- * XA_GROUP_USER is an element of enum XAGroupType. Its value is "XA_GROUP_USER".
- */
- public static final int XA_GROUP_USER = 1;
- /**
- * XA_GROUP_GROUP is an element of enum XAGroupType. Its value is "XA_GROUP_GROUP".
- */
- public static final int XA_GROUP_GROUP = 2;
- /**
- * XA_GROUP_ROLE is an element of enum XAGroupType. Its value is "XA_GROUP_ROLE".
- */
- public static final int XA_GROUP_ROLE = 3;
-
- /**
- * Max value for enum XAGroupType_MAX
- */
- public static final int XAGroupType_MAX = 3;
-
-
- /***************************************************************
- * Enum values for XAPermForType
- **************************************************************/
- /**
- * XA_PERM_FOR_UNKNOWN is an element of enum XAPermForType. Its value is "XA_PERM_FOR_UNKNOWN".
- */
- public static final int XA_PERM_FOR_UNKNOWN = 0;
- /**
- * XA_PERM_FOR_USER is an element of enum XAPermForType. Its value is "XA_PERM_FOR_USER".
- */
- public static final int XA_PERM_FOR_USER = 1;
- /**
- * XA_PERM_FOR_GROUP is an element of enum XAPermForType. Its value is "XA_PERM_FOR_GROUP".
- */
- public static final int XA_PERM_FOR_GROUP = 2;
-
- /**
- * Max value for enum XAPermForType_MAX
- */
- public static final int XAPermForType_MAX = 2;
-
-
- /***************************************************************
- * Enum values for XAPermType
- **************************************************************/
- /**
- * XA_PERM_TYPE_UNKNOWN is an element of enum XAPermType. Its value is "XA_PERM_TYPE_UNKNOWN".
- */
- public static final int XA_PERM_TYPE_UNKNOWN = 0;
- /**
- * XA_PERM_TYPE_RESET is an element of enum XAPermType. Its value is "XA_PERM_TYPE_RESET".
- */
- public static final int XA_PERM_TYPE_RESET = 1;
- /**
- * XA_PERM_TYPE_READ is an element of enum XAPermType. Its value is "XA_PERM_TYPE_READ".
- */
- public static final int XA_PERM_TYPE_READ = 2;
- /**
- * XA_PERM_TYPE_WRITE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_WRITE".
- */
- public static final int XA_PERM_TYPE_WRITE = 3;
- /**
- * XA_PERM_TYPE_CREATE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_CREATE".
- */
- public static final int XA_PERM_TYPE_CREATE = 4;
- /**
- * XA_PERM_TYPE_DELETE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_DELETE".
- */
- public static final int XA_PERM_TYPE_DELETE = 5;
- /**
- * XA_PERM_TYPE_ADMIN is an element of enum XAPermType. Its value is "XA_PERM_TYPE_ADMIN".
- */
- public static final int XA_PERM_TYPE_ADMIN = 6;
- /**
- * XA_PERM_TYPE_OBFUSCATE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_OBFUSCATE".
- */
- public static final int XA_PERM_TYPE_OBFUSCATE = 7;
- /**
- * XA_PERM_TYPE_MASK is an element of enum XAPermType. Its value is "XA_PERM_TYPE_MASK".
- */
- public static final int XA_PERM_TYPE_MASK = 8;
- /**
- * XA_PERM_TYPE_EXECUTE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_EXECUTE".
- */
- public static final int XA_PERM_TYPE_EXECUTE = 9;
- /**
- * XA_PERM_TYPE_SELECT is an element of enum XAPermType. Its value is "XA_PERM_TYPE_SELECT".
- */
- public static final int XA_PERM_TYPE_SELECT = 10;
- /**
- * XA_PERM_TYPE_UPDATE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_UPDATE".
- */
- public static final int XA_PERM_TYPE_UPDATE = 11;
- /**
- * XA_PERM_TYPE_DROP is an element of enum XAPermType. Its value is "XA_PERM_TYPE_DROP".
- */
- public static final int XA_PERM_TYPE_DROP = 12;
- /**
- * XA_PERM_TYPE_ALTER is an element of enum XAPermType. Its value is "XA_PERM_TYPE_ALTER".
- */
- public static final int XA_PERM_TYPE_ALTER = 13;
- /**
- * XA_PERM_TYPE_INDEX is an element of enum XAPermType. Its value is "XA_PERM_TYPE_INDEX".
- */
- public static final int XA_PERM_TYPE_INDEX = 14;
- /**
- * XA_PERM_TYPE_LOCK is an element of enum XAPermType. Its value is "XA_PERM_TYPE_LOCK".
- */
- public static final int XA_PERM_TYPE_LOCK = 15;
- /**
- * XA_PERM_TYPE_ALL is an element of enum XAPermType. Its value is "XA_PERM_TYPE_ALL".
- */
- public static final int XA_PERM_TYPE_ALL = 16;
-
- /**
- * XA_PERM_TYPE_ALL is an element of enum XAPermType. Its value is "XA_PERM_TYPE_ALLOW".
- */
- public static final int XA_PERM_TYPE_ALLOW = 17;
-
- /**
- * Max value for enum XAPermType_MAX
- */
- public static final int XAPermType_MAX = 17;
-
-
- /***************************************************************
- * Enum values for ClassTypes
- **************************************************************/
- /**
- * CLASS_TYPE_NONE is an element of enum ClassTypes. Its value is "CLASS_TYPE_NONE".
- */
- public static final int CLASS_TYPE_NONE = 0;
- /**
- * CLASS_TYPE_MESSAGE is an element of enum ClassTypes. Its value is "CLASS_TYPE_MESSAGE".
- */
- public static final int CLASS_TYPE_MESSAGE = 1;
- /**
- * CLASS_TYPE_USER_PROFILE is an element of enum ClassTypes. Its value is "CLASS_TYPE_USER_PROFILE".
- */
- public static final int CLASS_TYPE_USER_PROFILE = 2;
- /**
- * CLASS_TYPE_AUTH_SESS is an element of enum ClassTypes. Its value is "CLASS_TYPE_AUTH_SESS".
- */
- public static final int CLASS_TYPE_AUTH_SESS = 3;
- /**
- * CLASS_TYPE_DATA_OBJECT is an element of enum ClassTypes. Its value is "CLASS_TYPE_DATA_OBJECT".
- */
- public static final int CLASS_TYPE_DATA_OBJECT = 4;
- /**
- * CLASS_TYPE_NAMEVALUE is an element of enum ClassTypes. Its value is "CLASS_TYPE_NAMEVALUE".
- */
- public static final int CLASS_TYPE_NAMEVALUE = 5;
- /**
- * CLASS_TYPE_LONG is an element of enum ClassTypes. Its value is "CLASS_TYPE_LONG".
- */
- public static final int CLASS_TYPE_LONG = 6;
- /**
- * CLASS_TYPE_PASSWORD_CHANGE is an element of enum ClassTypes. Its value is "CLASS_TYPE_PASSWORD_CHANGE".
- */
- public static final int CLASS_TYPE_PASSWORD_CHANGE = 7;
- /**
- * CLASS_TYPE_STRING is an element of enum ClassTypes. Its value is "CLASS_TYPE_STRING".
- */
- public static final int CLASS_TYPE_STRING = 8;
- /**
- * CLASS_TYPE_ENUM is an element of enum ClassTypes. Its value is "CLASS_TYPE_ENUM".
- */
- public static final int CLASS_TYPE_ENUM = 9;
- /**
- * CLASS_TYPE_ENUM_ELEMENT is an element of enum ClassTypes. Its value is "CLASS_TYPE_ENUM_ELEMENT".
- */
- public static final int CLASS_TYPE_ENUM_ELEMENT = 10;
- /**
- * CLASS_TYPE_RESPONSE is an element of enum ClassTypes. Its value is "CLASS_TYPE_RESPONSE".
- */
- public static final int CLASS_TYPE_RESPONSE = 11;
- /**
- * CLASS_TYPE_XA_ASSET is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_ASSET".
- */
- public static final int CLASS_TYPE_XA_ASSET = 1000;
- /**
- * CLASS_TYPE_XA_RESOURCE is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_RESOURCE".
- */
- public static final int CLASS_TYPE_XA_RESOURCE = 1001;
- /**
- * CLASS_TYPE_XA_GROUP is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_GROUP".
- */
- public static final int CLASS_TYPE_XA_GROUP = 1002;
- /**
- * CLASS_TYPE_XA_USER is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_USER".
- */
- public static final int CLASS_TYPE_XA_USER = 1003;
- /**
- * CLASS_TYPE_XA_GROUP_USER is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_GROUP_USER".
- */
- public static final int CLASS_TYPE_XA_GROUP_USER = 1004;
- /**
- * CLASS_TYPE_XA_GROUP_GROUP is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_GROUP_GROUP".
- */
- public static final int CLASS_TYPE_XA_GROUP_GROUP = 1005;
- /**
- * CLASS_TYPE_XA_PERM_MAP is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_PERM_MAP".
- */
- public static final int CLASS_TYPE_XA_PERM_MAP = 1006;
- /**
- * CLASS_TYPE_XA_AUDIT_MAP is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_AUDIT_MAP".
- */
- public static final int CLASS_TYPE_XA_AUDIT_MAP = 1007;
- /**
- * CLASS_TYPE_XA_CRED_STORE is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_CRED_STORE".
- */
- public static final int CLASS_TYPE_XA_CRED_STORE = 1008;
- /**
- * CLASS_TYPE_XA_POLICY_EXPORT_AUDIT is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_POLICY_EXPORT_AUDIT".
- */
- public static final int CLASS_TYPE_XA_POLICY_EXPORT_AUDIT = 1009;
- /**
- * CLASS_TYPE_TRX_LOG is an element of enum ClassTypes. Its value is "CLASS_TYPE_TRX_LOG".
- */
- public static final int CLASS_TYPE_TRX_LOG = 1010;
- /**
- * CLASS_TYPE_XA_ACCESS_AUDIT is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_ACCESS_AUDIT".
- */
- public static final int CLASS_TYPE_XA_ACCESS_AUDIT = 1011;
- /**
- * CLASS_TYPE_XA_TRANSACTION_LOG_ATTRIBUTE is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_TRANSACTION_LOG_ATTRIBUTE".
- */
- public static final int CLASS_TYPE_XA_TRANSACTION_LOG_ATTRIBUTE = 1012;
-
- /**
- * Max value for enum ClassTypes_MAX
- */
- public static final int ClassTypes_MAX = 1012;
-
-
-
- static public String getLabelFor_ActiveStatus( int elementValue ) {
- if( elementValue == 0 ) {
- return "Disabled"; //STATUS_DISABLED
- }
- if( elementValue == 1 ) {
- return "Enabled"; //STATUS_ENABLED
- }
- if( elementValue == 2 ) {
- return "Deleted"; //STATUS_DELETED
- }
- return null;
- }
-
- static public String getLabelFor_ActivationStatus( int elementValue ) {
- if( elementValue == 0 ) {
- return "Disabled"; //ACT_STATUS_DISABLED
- }
- if( elementValue == 1 ) {
- return "Active"; //ACT_STATUS_ACTIVE
- }
- if( elementValue == 2 ) {
- return "Pending Approval"; //ACT_STATUS_PENDING_APPROVAL
- }
- if( elementValue == 3 ) {
- return "Pending Activation"; //ACT_STATUS_PENDING_ACTIVATION
- }
- if( elementValue == 4 ) {
- return "Rejected"; //ACT_STATUS_REJECTED
- }
- if( elementValue == 5 ) {
- return "Deactivated"; //ACT_STATUS_DEACTIVATED
- }
- if( elementValue == 6 ) {
- return "Registration Pending"; //ACT_STATUS_PRE_REGISTRATION
- }
- if( elementValue == 7 ) {
- return "No login privilege"; //ACT_STATUS_NO_LOGIN
- }
- return null;
- }
-
- static public String getLabelFor_BooleanValue( int elementValue ) {
- if( elementValue == 0 ) {
- return "None"; //BOOL_NONE
- }
- if( elementValue == 1 ) {
- return "True"; //BOOL_TRUE
- }
- if( elementValue == 2 ) {
- return "False"; //BOOL_FALSE
- }
- return null;
- }
-
- static public String getLabelFor_DataType( int elementValue ) {
- if( elementValue == 0 ) {
- return "Unknown"; //DATA_TYPE_UNKNOWN
- }
- if( elementValue == 1 ) {
- return "Integer"; //DATA_TYPE_INTEGER
- }
- if( elementValue == 2 ) {
- return "Double"; //DATA_TYPE_DOUBLE
- }
- if( elementValue == 3 ) {
- return "String"; //DATA_TYPE_STRING
- }
- if( elementValue == 4 ) {
- return "Boolean"; //DATA_TYPE_BOOLEAN
- }
- if( elementValue == 5 ) {
- return "Date"; //DATA_TYPE_DATE
- }
- if( elementValue == 6 ) {
- return "String enumeration"; //DATA_TYPE_STRING_ENUM
- }
- if( elementValue == 7 ) {
- return "Long"; //DATA_TYPE_LONG
- }
- if( elementValue == 8 ) {
- return "Integer enumeration"; //DATA_TYPE_INTEGER_ENUM
- }
- return null;
- }
-
- static public String getLabelFor_DeviceType( int elementValue ) {
- if( elementValue == 0 ) {
- return "Unknown"; //DEVICE_UNKNOWN
- }
- if( elementValue == 1 ) {
- return "Browser"; //DEVICE_BROWSER
- }
- if( elementValue == 2 ) {
- return "iPhone"; //DEVICE_IPHONE
- }
- if( elementValue == 3 ) {
- return "iPad"; //DEVICE_IPAD
- }
- if( elementValue == 4 ) {
- return "iPod"; //DEVICE_IPOD
- }
- if( elementValue == 5 ) {
- return "Android"; //DEVICE_ANDROID
- }
- return null;
- }
-
- static public String getLabelFor_DiffLevel( int elementValue ) {
- if( elementValue == 0 ) {
- return "Unknown"; //DIFF_UNKNOWN
- }
- if( elementValue == 1 ) {
- return "Low"; //DIFF_LOW
- }
- if( elementValue == 2 ) {
- return "Medium"; //DIFF_MEDIUM
- }
- if( elementValue == 3 ) {
- return "High"; //DIFF_HIGH
- }
- return null;
- }
-
- static public String getLabelFor_FileType( int elementValue ) {
- if( elementValue == 0 ) {
- return "File"; //FILE_FILE
- }
- if( elementValue == 1 ) {
- return "Directory"; //FILE_DIR
- }
- return null;
- }
-
- static public String getLabelFor_FreqType( int elementValue ) {
- if( elementValue == 0 ) {
- return "None"; //FREQ_NONE
- }
- if( elementValue == 1 ) {
- return "Manual"; //FREQ_MANUAL
- }
- if( elementValue == 2 ) {
- return "Hourly"; //FREQ_HOURLY
- }
- if( elementValue == 3 ) {
- return "Daily"; //FREQ_DAILY
- }
- if( elementValue == 4 ) {
- return "Weekly"; //FREQ_WEEKLY
- }
- if( elementValue == 5 ) {
- return "Bi Weekly"; //FREQ_BI_WEEKLY
- }
- if( elementValue == 6 ) {
- return "Monthly"; //FREQ_MONTHLY
- }
- return null;
- }
-
- static public String getLabelFor_MimeType( int elementValue ) {
- if( elementValue == 0 ) {
- return "Unknown"; //MIME_UNKNOWN
- }
- if( elementValue == 1 ) {
- return "Text"; //MIME_TEXT
- }
- if( elementValue == 2 ) {
- return "Html"; //MIME_HTML
- }
- if( elementValue == 3 ) {
- return "png"; //MIME_PNG
- }
- if( elementValue == 4 ) {
- return "jpeg"; //MIME_JPEG
- }
- return null;
- }
-
- static public String getLabelFor_NumberFormat( int elementValue ) {
- if( elementValue == 0 ) {
- return "None"; //NUM_FORMAT_NONE
- }
- if( elementValue == 1 ) {
- return "Numeric"; //NUM_FORMAT_NUMERIC
- }
- if( elementValue == 2 ) {
- return "Alphabhet"; //NUM_FORMAT_ALPHA
- }
- if( elementValue == 3 ) {
- return "Roman"; //NUM_FORMAT_ROMAN
- }
- return null;
- }
-
- static public String getLabelFor_ObjectStatus( int elementValue ) {
- if( elementValue == 0 ) {
- return "Active"; //OBJ_STATUS_ACTIVE
- }
- if( elementValue == 1 ) {
- return "Deleted"; //OBJ_STATUS_DELETED
- }
- if( elementValue == 2 ) {
- return "Archived"; //OBJ_STATUS_ARCHIVED
- }
- return null;
- }
-
- static public String getLabelFor_PasswordResetStatus( int elementValue ) {
- if( elementValue == 0 ) {
- return "Active"; //PWD_RESET_ACTIVE
- }
- if( elementValue == 1 ) {
- return "Used"; //PWD_RESET_USED
- }
- if( elementValue == 2 ) {
- return "Expired"; //PWD_RESET_EXPIRED
- }
- if( elementValue == 3 ) {
- return "Disabled"; //PWD_RESET_DISABLED
- }
- return null;
- }
-
- static public String getLabelFor_PriorityType( int elementValue ) {
- if( elementValue == 0 ) {
- return "Normal"; //PRIORITY_NORMAL
- }
- if( elementValue == 1 ) {
- return "Low"; //PRIORITY_LOW
- }
- if( elementValue == 2 ) {
- return "Medium"; //PRIORITY_MEDIUM
- }
- if( elementValue == 3 ) {
- return "High"; //PRIORITY_HIGH
- }
- return null;
- }
-
- static public String getLabelFor_ProgressStatus( int elementValue ) {
- if( elementValue == 0 ) {
- return "Pending"; //PROGRESS_PENDING
- }
- if( elementValue == 1 ) {
- return "In Progress"; //PROGRESS_IN_PROGRESS
- }
- if( elementValue == 2 ) {
- return "Complete"; //PROGRESS_COMPLETE
- }
- if( elementValue == 3 ) {
- return "Aborted"; //PROGRESS_ABORTED
- }
- if( elementValue == 4 ) {
- return "Failed"; //PROGRESS_FAILED
- }
- return null;
- }
-
- static public String getLabelFor_RelationType( int elementValue ) {
- if( elementValue == 0 ) {
- return "None"; //REL_NONE
- }
- if( elementValue == 1 ) {
- return "Self"; //REL_SELF
- }
- return null;
- }
-
- static public String getLabelFor_UserSource( int elementValue ) {
- if( elementValue == 0 ) {
- return "Application"; //USER_APP
- }
- if( elementValue == 1 ) {
- return "External"; //USER_EXTERNAL
- }
- /*if( elementValue == 1 ) {
- return "Google"; //USER_GOOGLE
- }
- if( elementValue == 2 ) {
- return "FaceBook"; //USER_FB
- }*/
- return null;
- }
-
- static public String getLabelFor_AssetType( int elementValue ) {
- if( elementValue == 0 ) {
- return "Unknown"; //ASSET_UNKNOWN
- }
- if( elementValue == 1 ) {
- return "HDFS"; //ASSET_HDFS
- }
- if( elementValue == 2 ) {
- return "HBase"; //ASSET_HBASE
- }
- if( elementValue == 3 ) {
- return "Hive"; //ASSET_HIVE
- }
- if( elementValue == 4 ) {
- return "Agent"; //ASSET_HIVE
- }
- if( elementValue == 5 ) {
- return "Knox"; //ASSET_HIVE
- }
- if( elementValue == 6 ) {
- return "Storm"; //ASSET_HIVE
- }
- return null;
- }
-
- static public String getLabelFor_AccessResult( int elementValue ) {
- if( elementValue == 0 ) {
- return "Denied"; //ACCESS_RESULT_DENIED
- }
- if( elementValue == 1 ) {
- return "Allowed"; //ACCESS_RESULT_ALLOWED
- }
- return null;
- }
-
- static public String getLabelFor_PolicyType( int elementValue ) {
- if( elementValue == 0 ) {
- return "Inclusion"; //POLICY_INCLUSION
- }
- if( elementValue == 1 ) {
- return "Exclusion"; //POLICY_EXCLUSION
- }
- return null;
- }
-
- static public String getLabelFor_XAAuditType( int elementValue ) {
- if( elementValue == 0 ) {
- return "Unknown"; //XA_AUDIT_TYPE_UNKNOWN
- }
- if( elementValue == 1 ) {
- return "All"; //XA_AUDIT_TYPE_ALL
- }
- if( elementValue == 2 ) {
- return "Read"; //XA_AUDIT_TYPE_READ
- }
- if( elementValue == 3 ) {
- return "Write"; //XA_AUDIT_TYPE_WRITE
- }
- if( elementValue == 4 ) {
- return "Create"; //XA_AUDIT_TYPE_CREATE
- }
- if( elementValue == 5 ) {
- return "Delete"; //XA_AUDIT_TYPE_DELETE
- }
- if( elementValue == 6 ) {
- return "Login"; //XA_AUDIT_TYPE_LOGIN
- }
- return null;
- }
-
- static public String getLabelFor_ResourceType( int elementValue ) {
- if( elementValue == 0 ) {
- return "Unknown"; //RESOURCE_UNKNOWN
- }
- if( elementValue == 1 ) {
- return "Path"; //RESOURCE_PATH
- }
- if( elementValue == 2 ) {
- return "Database"; //RESOURCE_DB
- }
- if( elementValue == 3 ) {
- return "Table"; //RESOURCE_TABLE
- }
- if( elementValue == 4 ) {
- return "Column Family"; //RESOURCE_COL_FAM
- }
- if( elementValue == 5 ) {
- return "Column"; //RESOURCE_COLUMN
- }
- if( elementValue == 6 ) {
- return "VIEW"; //RESOURCE_VIEW
- }
- if( elementValue == 7 ) {
- return "UDF"; //RESOURCE_UDF
- }
- if( elementValue == 8 ) {
- return "View Column"; //RESOURCE_VIEW_COL
- }
- return null;
- }
-
- static public String getLabelFor_XAGroupType( int elementValue ) {
- if( elementValue == 0 ) {
- return "Unknown"; //XA_GROUP_UNKNOWN
- }
- if( elementValue == 1 ) {
- return "User"; //XA_GROUP_USER
- }
- if( elementValue == 2 ) {
- return "Group"; //XA_GROUP_GROUP
- }
- if( elementValue == 3 ) {
- return "Role"; //XA_GROUP_ROLE
- }
- return null;
- }
-
- static public String getLabelFor_XAPermForType( int elementValue ) {
- if( elementValue == 0 ) {
- return "Unknown"; //XA_PERM_FOR_UNKNOWN
- }
- if( elementValue == 1 ) {
- return "Permission for Users"; //XA_PERM_FOR_USER
- }
- if( elementValue == 2 ) {
- return "Permission for Groups"; //XA_PERM_FOR_GROUP
- }
- return null;
- }
-
- static public String getLabelFor_XAPermType( int elementValue ) {
- if( elementValue == 0 ) {
- return "Unknown"; //XA_PERM_TYPE_UNKNOWN
- }
- if( elementValue == 1 ) {
- return "Reset"; //XA_PERM_TYPE_RESET
- }
- if( elementValue == 2 ) {
- return "Read"; //XA_PERM_TYPE_READ
- }
- if( elementValue == 3 ) {
- return "Write"; //XA_PERM_TYPE_WRITE
- }
- if( elementValue == 4 ) {
- return "Create"; //XA_PERM_TYPE_CREATE
- }
- if( elementValue == 5 ) {
- return "Delete"; //XA_PERM_TYPE_DELETE
- }
- if( elementValue == 6 ) {
- return "Admin"; //XA_PERM_TYPE_ADMIN
- }
- if( elementValue == 7 ) {
- return "Obfuscate"; //XA_PERM_TYPE_OBFUSCATE
- }
- if( elementValue == 8 ) {
- return "Mask"; //XA_PERM_TYPE_MASK
- }
- if( elementValue == 9 ) {
- return "Execute"; //XA_PERM_TYPE_EXECUTE
- }
- if( elementValue == 10 ) {
- return "Select"; //XA_PERM_TYPE_SELECT
- }
- if( elementValue == 11 ) {
- return "Update"; //XA_PERM_TYPE_UPDATE
- }
- if( elementValue == 12 ) {
- return "Drop"; //XA_PERM_TYPE_DROP
- }
- if( elementValue == 13 ) {
- return "Alter"; //XA_PERM_TYPE_ALTER
- }
- if( elementValue == 14 ) {
- return "Index"; //XA_PERM_TYPE_INDEX
- }
- if( elementValue == 15 ) {
- return "Lock"; //XA_PERM_TYPE_LOCK
- }
- if( elementValue == 16 ) {
- return "All"; //XA_PERM_TYPE_ALL
- }
- if( elementValue == 17 ) {
- return "Allow"; //XA_PERM_TYPE_ALLOW
- }
- return null;
- }
-
- static public String getLabelFor_ClassTypes( int elementValue ) {
- if( elementValue == 0 ) {
- return "None"; //CLASS_TYPE_NONE
- }
- if( elementValue == 1 ) {
- return "Message"; //CLASS_TYPE_MESSAGE
- }
- if( elementValue == 2 ) {
- return "User Profile"; //CLASS_TYPE_USER_PROFILE
- }
- if( elementValue == 3 ) {
- return "Authentication Session"; //CLASS_TYPE_AUTH_SESS
- }
- if( elementValue == 4 ) {
- return null; //CLASS_TYPE_DATA_OBJECT
- }
- if( elementValue == 5 ) {
- return null; //CLASS_TYPE_NAMEVALUE
- }
- if( elementValue == 6 ) {
- return null; //CLASS_TYPE_LONG
- }
- if( elementValue == 7 ) {
- return null; //CLASS_TYPE_PASSWORD_CHANGE
- }
- if( elementValue == 8 ) {
- return null; //CLASS_TYPE_STRING
- }
- if( elementValue == 9 ) {
- return null; //CLASS_TYPE_ENUM
- }
- if( elementValue == 10 ) {
- return null; //CLASS_TYPE_ENUM_ELEMENT
- }
- if( elementValue == 11 ) {
- return "Response"; //CLASS_TYPE_RESPONSE
- }
- if( elementValue == 1000 ) {
- return "Asset"; //CLASS_TYPE_XA_ASSET
- }
- if( elementValue == 1001 ) {
- return "Resource"; //CLASS_TYPE_XA_RESOURCE
- }
- if( elementValue == 1002 ) {
- return "XA Group"; //CLASS_TYPE_XA_GROUP
- }
- if( elementValue == 1003 ) {
- return "XA User"; //CLASS_TYPE_XA_USER
- }
- if( elementValue == 1004 ) {
- return "XA Group of Users"; //CLASS_TYPE_XA_GROUP_USER
- }
- if( elementValue == 1005 ) {
- return "XA Group of groups"; //CLASS_TYPE_XA_GROUP_GROUP
- }
- if( elementValue == 1006 ) {
- return "XA permissions for resource"; //CLASS_TYPE_XA_PERM_MAP
- }
- if( elementValue == 1007 ) {
- return "XA audits for resource"; //CLASS_TYPE_XA_AUDIT_MAP
- }
- if( elementValue == 1008 ) {
- return "XA credential store"; //CLASS_TYPE_XA_CRED_STORE
- }
- if( elementValue == 1009 ) {
- return "XA Policy Export Audit"; //CLASS_TYPE_XA_POLICY_EXPORT_AUDIT
- }
- if( elementValue == 1010 ) {
- return "Transaction log"; //CLASS_TYPE_TRX_LOG
- }
- if( elementValue == 1011 ) {
- return "Access Audit"; //CLASS_TYPE_XA_ACCESS_AUDIT
- }
- if( elementValue == 1012 ) {
- return "Transaction log attribute"; //CLASS_TYPE_XA_TRANSACTION_LOG_ATTRIBUTE
- }
- return null;
- }
-
-
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/XAConfigUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/XAConfigUtil.java b/security-admin/src/main/java/com/xasecure/common/XAConfigUtil.java
deleted file mode 100644
index 8e02504..0000000
--- a/security-admin/src/main/java/com/xasecure/common/XAConfigUtil.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * 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 com.xasecure.common;
-
-import org.apache.log4j.Logger;
-import org.springframework.stereotype.Component;
-
-import com.xasecure.common.PropertiesUtil;
-
-/**
- *
- *
- */
-@Component
-public class XAConfigUtil {
- static Logger logger = Logger.getLogger(XAConfigUtil.class);
-
- String webappRootURL;
- int defaultMaxRows = 250;
- String[] roles;
- boolean accessFilterEnabled = true;
- boolean isModerationEnabled = false;
- boolean isUserPrefEnabled = false;
-
- public XAConfigUtil() {
- webappRootURL = PropertiesUtil
- .getProperty("xa.webapp.url.root");
- if (webappRootURL == null || webappRootURL.trim().length() == 0) {
- logger.error("webapp URL is not set. Please xa.webapp.url.root property");
- }
-
- defaultMaxRows = PropertiesUtil.getIntProperty(
- "xa.db.maxrows.default", defaultMaxRows);
-
- roles = PropertiesUtil
- .getPropertyStringList("xa.users.roles.list");
-
- accessFilterEnabled = PropertiesUtil.getBooleanProperty(
- "xa.db.access.filter.enable", true);
-
- isModerationEnabled = PropertiesUtil.getBooleanProperty(
- "xa.moderation.enabled", isModerationEnabled);
- isUserPrefEnabled = PropertiesUtil.getBooleanProperty(
- "xa.userpref.enabled", isUserPrefEnabled);
- }
-
- /**
- * @return the defaultMaxRows
- */
- public int getDefaultMaxRows() {
- return defaultMaxRows;
- }
-
- /**
- * @return the roles
- */
- public String[] getRoles() {
- return roles;
- }
-
- /**
- * @return the accessFilterEnabled
- */
- public boolean isAccessFilterEnabled() {
- return accessFilterEnabled;
- }
-
- /**
- * @return the webAppRootURL
- */
- public String getWebAppRootURL() {
- return webappRootURL;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/XAConstants.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/XAConstants.java b/security-admin/src/main/java/com/xasecure/common/XAConstants.java
deleted file mode 100644
index b0bafcf..0000000
--- a/security-admin/src/main/java/com/xasecure/common/XAConstants.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * 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 com.xasecure.common;
-
-public class XAConstants extends XACommonEnums {
-
- // Default Roles
- public final static String ROLE_SYS_ADMIN = "ROLE_SYS_ADMIN";
- public final static String ROLE_ADMIN = "ROLE_ADMIN";
- public final static String ROLE_INTEGRATOR = "ROLE_INTEGRATOR";
- public final static String ROLE_DATA_ANALYST = "ROLE_DATA_ANALYST";
- public final static String ROLE_BIZ_MGR = "ROLE_BIZ_MGR";
-
- public final static String ROLE_USER = "ROLE_USER";
- public final static String ROLE_ANON = "ROLE_ANON";
- public final static String ROLE_OTHER = "ROLE_OTHER";
- public final static String GROUP_PUBLIC = "public";
- // Action constants
- public final static String ACTION_EDIT = "edit";
- public final static String ACTION_CHANGE = "change";
- public final static String ACTION_DELETE = "delete";
- public final static String ACTION_MARK_SPAM = "mark_spam";
- public final static String ACTION_RATE = "rate";
- public final static String ACTION_SELECT = "select";
- public final static String ACTION_UNSELECT = "unselect";
- public final static String ACTION_HIDE = "hide";
- public final static String ACTION_UNHIDE = "unhide";
- public final static String ACTION_SHARE = "share";
- public final static String ACTION_UNSHARE = "unshare";
- public final static String ACTION_BOOKMARK = "bookmark";
- public final static String ACTION_UNBOOKMARK = "unbookmark";
-
- // Sendgrid email API constants
- public static final String SENDGRID_API_USER = "api_user";
- public static final String SENDGRID_API_KEY = "api_key";
- public static final String SENDGRID_TO = "to";
- public static final String SENDGRID_TO_NAME = "toname";
- public static final String SENDGRID_SUBJECT = "subject";
- public static final String SENDGRID_TEXT = "text";
- public static final String SENDGRID_HTML = "html";
- public static final String SENDGRID_FROM_EMAIL = "from";
- public static final String SENDGRID_FROM_NAME = "fromname";
- public static final String SENDGRID_BCC = "bcc";
- public static final String SENDGRID_CC = "cc";
- public static final String SENDGRID_REPLY_TO = "replyto";
-
- // User create validation errors
- public enum ValidationUserProfile {
-
- NO_EMAIL_ADDR("xa.validation.userprofile.no_email_addr",
- "Email address not provided"), INVALID_EMAIL_ADDR(
- "xa.validation.userprofile.userprofile.invalid_email_addr",
- "Invalid email address"), NO_FIRST_NAME(
- "xa.validation.userprofile.userprofile.no_first_name",
- "First name not provided"), INVALID_FIRST_NAME(
- "xa.validation.userprofile.invalid_first_name",
- "Invalid first name"), NO_LAST_NAME(
- "xa.validation.userprofile.noemailaddr",
- "Email address not provided"), INVALID_LAST_NAME(
- "xa.validation.userprofile.noemailaddr",
- "Email address not provided"), NO_PUBLIC_SCREEN_NAME(
- "xa.validation.userprofile.noemailaddr",
- "Email address not provided"), INVALID_PUBLIC_SCREEN_NAME(
- "xa.validation.userprofile.noemailaddr",
- "Email address not provided");
-
- String rbKey;
- String message;
-
- ValidationUserProfile(String rbKey, String message) {
- this.rbKey = rbKey;
- this.message = message;
- }
- };
-
- // these constants will be used in setting GjResponse object.
-
- public final static String USER_PENDING_APPROVAL_MSG = "User is yet not reviewed by Administrator. Please contact at <number>.";
- public final static int USER_PENDING_APPROVAL_STATUS_CODE = 0;
-
- public final static String USER_APPROVAL_MSG = "User is approved";
- public final static int USER_APPROVAL_STATUS_CODE = 1;
-
- public final static String USER_REJECTION_MSG = "User is rejected";
- public final static int USER_REJECTION_STATUS_CODE = 1;
-
- public final static String USER_STATUS_ALREADY_CHANGED_MSG = "Can not change user status. it is either already activated/approved/rejected";
- public final static int USER_STATUS_ALREADY_CHANGED_STATUS_CODE = 0;
-
- public final static String USER_ALREADY_ACTIVATED_MSG = "Your account is already activated. If you have forgotten your password, then from the login page, select 'Forgot Password'";
- public final static int USER_ALREADY_ACTIVATED_STATUS_CODE = 0;
-
- public final static String USER_STATUS_NOT_ACTIVE_MSG = "User is not in active status. Please activate your account first.";
- public final static int USER_STATUS_NOT_ACTIVE_STATUS_CODE = 0;
-
- public final static String INVALID_EMAIL_ADDRESS_MSG = "Invalid email address";
- public final static int INVALID_EMAIL_ADDRESS_STATUS_CODE = 0;
-
- public final static String WRONG_ACTIVATION_CODE_MSG = "Wrong activation code";
- public final static int WRONG_ACTIVATION_CODE_STATUS_CODE = 0;
-
- public final static String VALID_EMAIL_ADDRESS_MSG = "Valid email address";
- public final static int VALID_EMAIL_ADDRESS_STATUS_CODE = 1;
-
- public final static String NO_ACTIVATION_RECORD_FOR_USER_ERR_MSG = "No activation record found for user:";
- public final static String NO_ACTIVATION_ENTRY = "activation entry not found";
-
- public final static String VALIDATION_INVALID_DATA_DESC = "Invalid value for";
- public final static int VALIDATION_INVALID_DATA_CODE = 0;
- public static final String GROUP_MODERATORS = "GROUP_MODERATORS";
-
- // public final static String EMAIL_WELCOME_MSG =
- // "Welcome to iSchoolCircle";
- // public final static String EMAIL_LINK_WELCOME_MSG =
- // "Welcome to iSchoolCircle ! Please verify your account by clicking on the link below: ";
- // public static final String EMAIL_EDIT_REJECTED_MSG =
- // "Your changes not approved for public sharing.";
- // public static final String EMAIL_APPROVAL_NEEDED_MSG =
- // "New objects pending approval";
- // public static final String EMAIL_PWD_RESET_CODE_MSG =
- // "iSchoolCircle - Password Reset";
-
- public final static String PWD_RESET_FAILED_MSG = "Invalid password reset request";
-
- public final static String INVALID_NEW_PASSWORD_MSG = "Invalid new password";
- public static final String EMAIL_NEW_FEEDBACK_RECEIVED = "New feedback from";
- public static final int INITIAL_DOCUMENT_VERSION = 1;
-
- public static final int EMAIL_TYPE_ACCOUNT_CREATE = 0;
- public static final int EMAIL_TYPE_USER_CREATE = 1;
- public static final int EMAIL_TYPE_USER_ACCT_ADD = 2;
- public static final int EMAIL_TYPE_DOCUMENT_CREATE = 3;
- public static final int EMAIL_TYPE_DISCUSSION_CREATE = 4;
- public static final int EMAIL_TYPE_NOTE_CREATE = 5;
- public static final int EMAIL_TYPE_TASK_CREATE = 6;
- public static final int EMAIL_TYPE_USER_PASSWORD = 7;
- public static final int EMAIL_TYPE_USER_ACTIVATION = 8;
- public static final int EMAIL_TYPE_USER_ROLE_UPDATED = 9;
- public static final int EMAIL_TYPE_USER_GRP_ADD = 10;
-
- public static enum RBAC_PERM {
- ALLOW_NONE,
- ALLOW_READ,
- ALLOW_WRITE,
- ALLOW_DELETE
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/XAJAXBContextResolver.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/XAJAXBContextResolver.java b/security-admin/src/main/java/com/xasecure/common/XAJAXBContextResolver.java
deleted file mode 100644
index a1bbbf3..0000000
--- a/security-admin/src/main/java/com/xasecure/common/XAJAXBContextResolver.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * 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 com.xasecure.common;
-
-import com.xasecure.common.*;
-import javax.ws.rs.ext.ContextResolver;
-import javax.ws.rs.ext.Provider;
-import javax.xml.bind.JAXBContext;
-
-import com.sun.jersey.api.json.JSONConfiguration;
-import com.sun.jersey.api.json.JSONJAXBContext;
-
-/**
- *
- *
- */
-@Provider
-public class XAJAXBContextResolver implements ContextResolver<JAXBContext> {
-
- private JAXBContext context;
- private Class<?>[] types = {
- com.xasecure.view.VXAuthSessionList.class,
- com.xasecure.view.VXResponse.class,
- com.xasecure.view.VXStringList.class,
- com.xasecure.view.VXPortalUserList.class,
- com.xasecure.view.VXAssetList.class,
- com.xasecure.view.VXResourceList.class,
- com.xasecure.view.VXCredentialStoreList.class,
- com.xasecure.view.VXGroupList.class,
- com.xasecure.view.VXUserList.class,
- com.xasecure.view.VXGroupUserList.class,
- com.xasecure.view.VXGroupGroupList.class,
- com.xasecure.view.VXPermMapList.class,
- com.xasecure.view.VXAuditMapList.class,
- com.xasecure.view.VXPolicyExportAuditList.class,
- com.xasecure.view.VXAccessAuditList.class
- };
-
- public XAJAXBContextResolver() throws Exception {
- JSONConfiguration config = JSONConfiguration.natural().build();
- context = new JSONJAXBContext(config, types);
- }
-
- @Override
- public JAXBContext getContext(Class<?> objectType) {
- // return context;
- for (Class<?> type : types) {
- if (type.getName().equals(objectType.getName())) {
- return context;
- }
- }
- return null;
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/XASearchUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/XASearchUtil.java b/security-admin/src/main/java/com/xasecure/common/XASearchUtil.java
deleted file mode 100644
index 19d65b8..0000000
--- a/security-admin/src/main/java/com/xasecure/common/XASearchUtil.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * 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 com.xasecure.common;
-
-import java.util.List;
-
-import javax.persistence.EntityManager;
-import javax.persistence.Query;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import com.xasecure.db.XADaoManager;
-import com.xasecure.common.SearchCriteria;
-import com.xasecure.common.SearchField;
-import com.xasecure.common.SearchUtil;
-
-@Component
-public class XASearchUtil extends SearchUtil {
- final static Logger logger = Logger.getLogger(XASearchUtil.class);
- /*
- @Override
- 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;
- }
- */
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/annotation/XAAnnotationClassName.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/annotation/XAAnnotationClassName.java b/security-admin/src/main/java/com/xasecure/common/annotation/XAAnnotationClassName.java
deleted file mode 100644
index bd753bb..0000000
--- a/security-admin/src/main/java/com/xasecure/common/annotation/XAAnnotationClassName.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * 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 com.xasecure.common.annotation;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-
-
-@Retention(RetentionPolicy.RUNTIME)
-public @interface XAAnnotationClassName {
- public Class class_name();
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/annotation/XAAnnotationJSMgrName.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/annotation/XAAnnotationJSMgrName.java b/security-admin/src/main/java/com/xasecure/common/annotation/XAAnnotationJSMgrName.java
deleted file mode 100644
index 35ddb06..0000000
--- a/security-admin/src/main/java/com/xasecure/common/annotation/XAAnnotationJSMgrName.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * 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 com.xasecure.common.annotation;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-
-/**
- *
- *
- */
-@Retention(RetentionPolicy.RUNTIME)
-public @interface XAAnnotationJSMgrName {
- public String value();
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/annotation/XAAnnotationRestAPI.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/annotation/XAAnnotationRestAPI.java b/security-admin/src/main/java/com/xasecure/common/annotation/XAAnnotationRestAPI.java
deleted file mode 100644
index 4f2b245..0000000
--- a/security-admin/src/main/java/com/xasecure/common/annotation/XAAnnotationRestAPI.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * 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 com.xasecure.common.annotation;
-
-import java.lang.annotation.*;
-
-/**
- * Annotating the REST APIs
- *
- */
-@Retention(RetentionPolicy.RUNTIME)
-public @interface XAAnnotationRestAPI {
- public String api_name() default "";
- public boolean updates_generic_objects() default false;
- public String updates_classes() default "";
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/db/BaseDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/db/BaseDao.java b/security-admin/src/main/java/com/xasecure/common/db/BaseDao.java
deleted file mode 100644
index 3d22257..0000000
--- a/security-admin/src/main/java/com/xasecure/common/db/BaseDao.java
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
- * 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 com.xasecure.common.db;
-
-
-
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.persistence.EntityManager;
-import javax.persistence.NoResultException;
-import javax.persistence.Query;
-import javax.persistence.TypedQuery;
-
-import org.apache.log4j.Logger;
-
-import com.xasecure.common.ContextUtil;
-import com.xasecure.db.XADaoManager;
-import com.xasecure.db.XADaoManagerBase;
-import com.xasecure.entity.XXDBBase;
-
-public abstract class BaseDao<T> {
- static final Logger logger = Logger.getLogger(BaseDao.class);
-
- protected XADaoManager daoManager;
-
- EntityManager em;
-
- protected Class<T> tClass;
-
- public BaseDao(XADaoManagerBase daoManager) {
- this.daoManager = (XADaoManager) daoManager;
- this.init(daoManager.getEntityManager());
- }
-
- public BaseDao(XADaoManagerBase daoManager, String persistenceContextUnit) {
- this.daoManager = (XADaoManager) daoManager;
-
- EntityManager em = this.daoManager.getEntityManager(persistenceContextUnit);
-
- this.init(em);
- }
-
- @SuppressWarnings("unchecked")
- private void init(EntityManager em) {
- this.em = em;
-
- ParameterizedType genericSuperclass = (ParameterizedType) getClass()
- .getGenericSuperclass();
-
- Type type = genericSuperclass.getActualTypeArguments()[0];
-
- if (type instanceof ParameterizedType) {
- this.tClass = (Class<T>) ((ParameterizedType) type).getRawType();
- } else {
- this.tClass = (Class<T>) type;
- }
- }
-
- public EntityManager getEntityManager() {
- return this.em;
- }
-
- public T create(T obj) {
- T ret = null;
-
- em.persist(obj);
- em.flush();
-
- ret = obj;
- return ret;
- }
-
- public T update(T obj) {
- em.merge(obj);
- em.flush();
- return obj;
- }
-
- public boolean remove(Long id) {
- return remove(getById(id));
- }
-
- public boolean remove(T obj) {
- if (obj == null) {
- return true;
- }
-
- em.remove(obj);
- em.flush();
-
- return true;
- }
-
- public T getById(Long id) {
- if (id == null) {
- return null;
- }
- T ret = null;
- try {
- ret = em.find(tClass, id);
- } catch (NoResultException e) {
- return null;
- }
- return ret;
- }
-
- public List<T> findByNamedQuery(String namedQuery, String paramName,
- Object refId) {
- List<T> ret = new ArrayList<T>();
-
- if (namedQuery == null) {
- return ret;
- }
- try {
- TypedQuery<T> qry = em.createNamedQuery(namedQuery, tClass);
- qry.setParameter(paramName, refId);
- ret = qry.getResultList();
- } catch (NoResultException e) {
- // ignore
- }
- return ret;
- }
-
- public List<T> findByParentId(Long parentId) {
- String namedQuery = tClass.getSimpleName() + ".findByParentId";
- return findByNamedQuery(namedQuery, "parentId", parentId);
- }
-
-
- public List<T> executeQueryInSecurityContext(Class<T> clazz, Query query) {
- return executeQueryInSecurityContext(clazz, query, true);
- }
-
- @SuppressWarnings("unchecked")
- public List<T> executeQueryInSecurityContext(Class<T> clazz, Query query,
- boolean userPrefFilter) {
- // boolean filterEnabled = false;
- List<T> rtrnList = null;
- try {
- // filterEnabled = enableVisiblityFilters(clazz, userPrefFilter);
-
- rtrnList = query.getResultList();
- } finally {
- // if (filterEnabled) {
- // disableVisiblityFilters(clazz);
- // }
-
- }
-
- return rtrnList;
- }
-
- /**
- * @param clazz
- * @param query
- * @param b
- * @return
- */
- private Long executeCountQueryInSecurityContext(Class<T> clazz,
- Query query, boolean userPrefFilter) {
- // boolean filterEnabled = false;
- Long rtrnObj = null;
- try {
- // filterEnabled = enableVisiblityFilters(clazz, userPrefFilter);
- rtrnObj = (Long) query.getSingleResult();
- } finally {
- // if (filterEnabled) {
- // disableVisiblityFilters(clazz);
- // }
- }
-
- return rtrnObj;
- }
-
- public Long executeCountQueryInSecurityContext(Class<T> clazz, Query query) {
- return executeCountQueryInSecurityContext(clazz, query, true);
- }
-
- public List<T> getAll() {
- List<T> ret = null;
- TypedQuery<T> qry = em.createQuery(
- "SELECT t FROM " + tClass.getSimpleName() + " t", tClass);
- ret = qry.getResultList();
- return ret;
- }
-
- public Long getAllCount() {
- Long ret = null;
- TypedQuery<Long> qry = em.createQuery(
- "SELECT count(t) FROM " + tClass.getSimpleName() + " t",
- Long.class);
- ret = qry.getSingleResult();
- return ret;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/db/JPABeanCallbacks.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/db/JPABeanCallbacks.java b/security-admin/src/main/java/com/xasecure/common/db/JPABeanCallbacks.java
deleted file mode 100644
index bcb85d6..0000000
--- a/security-admin/src/main/java/com/xasecure/common/db/JPABeanCallbacks.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * 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 com.xasecure.common.db;
-
-import javax.persistence.PrePersist;
-import javax.persistence.PreUpdate;
-
-import com.xasecure.common.DateUtil;
-import com.xasecure.common.UserSessionBase;
-import com.xasecure.entity.XXDBBase;
-
-import org.apache.log4j.Logger;
-
-import com.xasecure.security.context.XAContextHolder;
-import com.xasecure.security.context.XASecurityContext;
-
-public class JPABeanCallbacks {
- static final Logger logger = Logger.getLogger(JPABeanCallbacks.class);
-
- @PrePersist
- void onPrePersist(Object o) {
- try {
- if (o != null && o instanceof XXDBBase) {
- XXDBBase entity = (XXDBBase) o;
-
- entity.setUpdateTime(DateUtil.getUTCDate());
-
- XASecurityContext context = XAContextHolder
- .getSecurityContext();
- if (context != null) {
- UserSessionBase userSession = context.getUserSession();
- if (userSession != null) {
- entity.setAddedByUserId(userSession.getUserId());
- entity.setUpdatedByUserId(userSession
- .getUserId());
- }
- } else {
- if (logger.isDebugEnabled()) {
- logger.debug(
- "Security context not found for this request. obj="
- + o, new Throwable());
- }
- }
- }
- } catch (Throwable t) {
- logger.error(t);
- }
-
- }
-
- // @PostPersist
- // void onPostPersist(Object o) {
- // if (o != null && o instanceof MBase) {
- // MBase entity = (MBase) o;
- // if (logger.isDebugEnabled()) {
- // logger.debug("DBChange.create:class=" + o.getClass().getName()
- // + entity.getId());
- // }
- //
- // }
- // }
-
- // @PostLoad void onPostLoad(Object o) {}
-
- @PreUpdate
- void onPreUpdate(Object o) {
- try {
- if (o != null && o instanceof XXDBBase) {
- XXDBBase entity = (XXDBBase) o;
- entity.setUpdateTime(DateUtil.getUTCDate());
- }
- } catch (Throwable t) {
- logger.error(t);
- }
-
- }
-
- // @PostUpdate
- // void onPostUpdate(Object o) {
- // }
-
- // @PreRemove void onPreRemove(Object o) {}
-
- // @PostRemove
- // void onPostRemove(Object o) {
- // }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/view/VEnum.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/view/VEnum.java b/security-admin/src/main/java/com/xasecure/common/view/VEnum.java
deleted file mode 100644
index ca8d803..0000000
--- a/security-admin/src/main/java/com/xasecure/common/view/VEnum.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * 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 com.xasecure.common.view;
-
-import java.util.List;
-
-import javax.xml.bind.annotation.XmlRootElement;
-
-import com.xasecure.common.XACommonEnums;
-
-
-@XmlRootElement
-public class VEnum extends ViewBaseBean implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
- /**
- * Name of the enum
- */
- protected String enumName;
- /**
- * List of elements for this enum
- */
- protected List<VEnumElement> elementList;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VEnum() {
- }
-
- /**
- * This method sets the value to the member attribute <b>enumName</b>. You
- * cannot set null to the attribute.
- *
- * @param enumName
- * Value to set member attribute <b>enumName</b>
- */
- public void setEnumName(String enumName) {
- this.enumName = enumName;
- }
-
- /**
- * Returns the value for the member attribute <b>enumName</b>
- *
- * @return String - value of member attribute <b>enumName</b>.
- */
- public String getEnumName() {
- return this.enumName;
- }
-
- /**
- * This method sets the value to the member attribute <b>elementList</b>.
- * You cannot set null to the attribute.
- *
- * @param elementList
- * Value to set member attribute <b>elementList</b>
- */
- public void setElementList(List<VEnumElement> elementList) {
- this.elementList = elementList;
- }
-
- /**
- * Returns the value for the member attribute <b>elementList</b>
- *
- * @return List<VEnumElement> - value of member attribute
- * <b>elementList</b>.
- */
- public List<VEnumElement> getElementList() {
- return this.elementList;
- }
-
- @Override
- public int getMyClassType() {
- return XACommonEnums.CLASS_TYPE_ENUM;
- }
-
- /**
- * This return the bean content in string format
- *
- * @return formatedStr
- */
- public String toString() {
- String str = "VEnum={";
- str += super.toString();
- str += "enumName={" + enumName + "} ";
- str += "elementList={" + elementList + "} ";
- str += "}";
- return str;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/view/VEnumElement.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/view/VEnumElement.java b/security-admin/src/main/java/com/xasecure/common/view/VEnumElement.java
deleted file mode 100644
index f21302a..0000000
--- a/security-admin/src/main/java/com/xasecure/common/view/VEnumElement.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * 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 com.xasecure.common.view;
-
-import javax.xml.bind.annotation.XmlRootElement;
-
-import com.xasecure.common.XACommonEnums;
-
-@XmlRootElement
-public class VEnumElement extends ViewBaseBean implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- /**
- * Name of the element
- */
- protected String elementName;
- /**
- * Name of the enum
- */
- protected String enumName;
- /**
- * Value of the element
- */
- protected int elementValue;
- /**
- * Label for the element
- */
- protected String elementLabel;
- /**
- * Resource bundle key
- */
- protected String rbKey;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VEnumElement ( ) {
- }
-
- /**
- * This method sets the value to the member attribute <b>elementName</b>.
- * You cannot set null to the attribute.
- * @param elementName Value to set member attribute <b>elementName</b>
- */
- public void setElementName( String elementName ) {
- this.elementName = elementName;
- }
-
-
-
- /**
- * @return the elementName
- */
- public String getElementName() {
- return elementName;
- }
-
- /**
- * @return the enumName
- */
- public String getEnumName() {
- return enumName;
- }
-
- /**
- * @return the rbKey
- */
- public String getRbKey() {
- return rbKey;
- }
-
- /**
- * This method sets the value to the member attribute <b>enumName</b>.
- * You cannot set null to the attribute.
- * @param enumName Value to set member attribute <b>enumName</b>
- */
- public void setEnumName( String enumName ) {
- this.enumName = enumName;
- }
-
-
-
- /**
- * This method sets the value to the member attribute <b>elementValue</b>.
- * You cannot set null to the attribute.
- * @param elementValue Value to set member attribute <b>elementValue</b>
- */
- public void setElementValue( int elementValue ) {
- this.elementValue = elementValue;
- }
-
- /**
- * Returns the value for the member attribute <b>elementValue</b>
- * @return int - value of member attribute <b>elementValue</b>.
- */
- public int getElementValue( ) {
- return this.elementValue;
- }
-
- /**
- * This method sets the value to the member attribute <b>elementLabel</b>.
- * You cannot set null to the attribute.
- * @param elementLabel Value to set member attribute <b>elementLabel</b>
- */
- public void setElementLabel( String elementLabel ) {
- this.elementLabel = elementLabel;
- }
-
- /**
- * Returns the value for the member attribute <b>elementLabel</b>
- * @return String - value of member attribute <b>elementLabel</b>.
- */
- public String getElementLabel( ) {
- return this.elementLabel;
- }
-
- /**
- * This method sets the value to the member attribute <b>rbKey</b>.
- * You cannot set null to the attribute.
- * @param rbKey Value to set member attribute <b>rbKey</b>
- */
- public void setRbKey( String rbKey ) {
- this.rbKey = rbKey;
- }
-
-
-
- @Override
- public int getMyClassType( ) {
- return XACommonEnums.CLASS_TYPE_ENUM_ELEMENT;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- public String toString( ) {
- String str = "VEnumElement={";
- str += super.toString();
- str += "elementName={" + elementName + "} ";
- str += "enumName={" + enumName + "} ";
- str += "elementValue={" + elementValue + "} ";
- str += "elementLabel={" + elementLabel + "} ";
- str += "rbKey={" + rbKey + "} ";
- str += "}";
- return str;
- }
-}
[29/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/com/xasecure/storm/client/json/model/Topology.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/com/xasecure/storm/client/json/model/Topology.java b/lookup-client/src/main/java/com/xasecure/storm/client/json/model/Topology.java
deleted file mode 100644
index 229eb54..0000000
--- a/lookup-client/src/main/java/com/xasecure/storm/client/json/model/Topology.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * 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 com.xasecure.storm.client.json.model;
-
-public class Topology {
- private String id ;
- private String name ;
- private String status ;
-
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getStatus() {
- return status;
- }
- public void setStatus(String status) {
- this.status = status;
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/com/xasecure/storm/client/json/model/TopologyListResponse.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/com/xasecure/storm/client/json/model/TopologyListResponse.java b/lookup-client/src/main/java/com/xasecure/storm/client/json/model/TopologyListResponse.java
deleted file mode 100644
index 486f3d2..0000000
--- a/lookup-client/src/main/java/com/xasecure/storm/client/json/model/TopologyListResponse.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * 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 com.xasecure.storm.client.json.model;
-
-import java.util.List;
-
-import com.google.gson.annotations.SerializedName;
-
-public class TopologyListResponse {
- @SerializedName("topologies")
- private List<Topology> topologyList;
-
- public List<Topology> getTopologyList() {
- return topologyList;
- }
-
- public void setTopologyList(List<Topology> topologyList) {
- this.topologyList = topologyList;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/org/apache/ranger/hadoop/client/HadoopFS.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/org/apache/ranger/hadoop/client/HadoopFS.java b/lookup-client/src/main/java/org/apache/ranger/hadoop/client/HadoopFS.java
new file mode 100644
index 0000000..10a83c3
--- /dev/null
+++ b/lookup-client/src/main/java/org/apache/ranger/hadoop/client/HadoopFS.java
@@ -0,0 +1,195 @@
+/*
+ * 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.hadoop.client;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.net.UnknownHostException;
+import java.security.PrivilegedAction;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+import javax.security.auth.Subject;
+
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.ranger.hadoop.client.config.BaseClient;
+import org.apache.ranger.hadoop.client.exceptions.HadoopException;
+
+public class HadoopFS extends BaseClient {
+
+ private static final Log LOG = LogFactory.getLog(HadoopFS.class) ;
+
+ public HadoopFS(String dataSource) {
+ super(dataSource) ;
+ }
+
+ public HadoopFS(String dataSource, HashMap<String,String> connectionProperties) {
+ super(dataSource,connectionProperties) ;
+ }
+
+ private List<String> listFilesInternal(String baseDir, String fileMatching) {
+ List<String> fileList = new ArrayList<String>() ;
+ ClassLoader prevCl = Thread.currentThread().getContextClassLoader() ;
+ String errMsg = " You can still save the repository and start creating "
+ + "policies, but you would not be able to use autocomplete for "
+ + "resource names. Check xa_portal.log for more info.";
+ try {
+ Thread.currentThread().setContextClassLoader(getConfigHolder().getClassLoader());
+ String dirPrefix = (baseDir.endsWith("/") ? baseDir : (baseDir + "/")) ;
+ String filterRegEx = null;
+ if (fileMatching != null && fileMatching.trim().length() > 0) {
+ filterRegEx = fileMatching.trim() ;
+ }
+
+ Configuration conf = new Configuration() ;
+ UserGroupInformation.setConfiguration(conf);
+
+ FileSystem fs = null ;
+ try {
+ fs = FileSystem.get(conf) ;
+
+ FileStatus[] fileStats = fs.listStatus(new Path(baseDir)) ;
+ if (fileStats != null) {
+ for(FileStatus stat : fileStats) {
+ Path path = stat.getPath() ;
+ String pathComponent = path.getName() ;
+ if (filterRegEx == null) {
+ fileList.add(dirPrefix + pathComponent) ;
+ }
+ else if (FilenameUtils.wildcardMatch(pathComponent, fileMatching)) {
+ fileList.add(dirPrefix + pathComponent) ;
+ }
+ }
+ }
+ } catch (UnknownHostException uhe) {
+ String msgDesc = "listFilesInternal: Unable to connect using given config parameters"
+ + " of Hadoop environment [" + getDataSource() + "].";
+ HadoopException hdpException = new HadoopException(msgDesc, uhe);
+ hdpException.generateResponseDataMap(false, getMessage(uhe),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ } catch (FileNotFoundException fne) {
+ String msgDesc = "listFilesInternal: Unable to locate files using given config parameters "
+ + "of Hadoop environment [" + getDataSource() + "].";
+ HadoopException hdpException = new HadoopException(msgDesc, fne);
+ hdpException.generateResponseDataMap(false, getMessage(fne),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ }
+ finally {
+ }
+ } catch (IOException ioe) {
+ String msgDesc = "listFilesInternal: Unable to get listing of files for directory "
+ + baseDir
+ + "] from Hadoop environment ["
+ + getDataSource()
+ + "].";
+ HadoopException hdpException = new HadoopException(msgDesc, ioe);
+ hdpException.generateResponseDataMap(false, getMessage(ioe),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+
+ } catch (IllegalArgumentException iae) {
+ String msgDesc = "Unable to get listing of files for directory ["
+ + baseDir + "] from Hadoop environment [" + getDataSource()
+ + "].";
+ HadoopException hdpException = new HadoopException(msgDesc, iae);
+ hdpException.generateResponseDataMap(false, getMessage(iae),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ }
+ finally {
+ Thread.currentThread().setContextClassLoader(prevCl);
+ }
+ return fileList ;
+ }
+
+
+ public List<String> listFiles(final String baseDir, final String fileMatching) {
+
+ PrivilegedAction<List<String>> action = new PrivilegedAction<List<String>>() {
+ @Override
+ public List<String> run() {
+ return listFilesInternal(baseDir, fileMatching) ;
+ }
+
+ };
+ return Subject.doAs(getLoginSubject(),action) ;
+ }
+
+ public static final void main(String[] args) {
+
+ if (args.length < 2) {
+ System.err.println("USAGE: java " + HadoopFS.class.getName() + " repositoryName basedirectory [filenameToMatch]") ;
+ System.exit(1) ;
+ }
+
+ String repositoryName = args[0] ;
+ String baseDir = args[1] ;
+ String fileNameToMatch = (args.length == 2 ? null : args[2]) ;
+
+ HadoopFS fs = new HadoopFS(repositoryName) ;
+ List<String> fsList = fs.listFiles(baseDir, fileNameToMatch) ;
+ if (fsList != null && fsList.size() > 0) {
+ for(String s : fsList) {
+ System.out.println(s) ;
+ }
+ }
+ else {
+ System.err.println("Unable to get file listing for [" + baseDir + (baseDir.endsWith("/") ? "" : "/") + fileNameToMatch + "] in repository [" + repositoryName + "]") ;
+ }
+ }
+
+ public static HashMap<String, Object> testConnection(String dataSource,
+ HashMap<String, String> connectionProperties) {
+
+ HashMap<String, Object> responseData = new HashMap<String, Object>();
+ boolean connectivityStatus = false;
+ HadoopFS connectionObj = new HadoopFS(dataSource, connectionProperties);
+ if (connectionObj != null) {
+ List<String> testResult = connectionObj.listFiles("/", null);
+ if (testResult != null && testResult.size() != 0) {
+ connectivityStatus = true;
+ }
+ }
+ if (connectivityStatus) {
+ String successMsg = "TestConnection Successful";
+ generateResponseDataMap(connectivityStatus, successMsg, successMsg,
+ null, null, responseData);
+ } else {
+ String failureMsg = "Unable to retrieve any files using given parameters, "
+ + "You can still save the repository and start creating policies, "
+ + "but you would not be able to use autocomplete for resource names. "
+ + "Check xa_portal.log for more info.";
+ generateResponseDataMap(connectivityStatus, failureMsg, failureMsg,
+ null, null, responseData);
+ }
+ return responseData;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/org/apache/ranger/hadoop/client/HadoopFSTester.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/org/apache/ranger/hadoop/client/HadoopFSTester.java b/lookup-client/src/main/java/org/apache/ranger/hadoop/client/HadoopFSTester.java
new file mode 100644
index 0000000..8199971
--- /dev/null
+++ b/lookup-client/src/main/java/org/apache/ranger/hadoop/client/HadoopFSTester.java
@@ -0,0 +1,61 @@
+/*
+ * 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.hadoop.client;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Properties;
+
+public class HadoopFSTester {
+
+ public static void main(String[] args) throws Throwable {
+ if (args.length < 3) {
+ System.err.println("USAGE: java " + HadoopFS.class.getName() + " repositoryName propertyFile basedirectory [filenameToMatch]") ;
+ System.exit(1) ;
+ }
+
+ String repositoryName = args[0] ;
+ String propFile = args[1] ;
+ String baseDir = args[2] ;
+ String fileNameToMatch = (args.length == 3 ? null : args[3]) ;
+
+ Properties conf = new Properties() ;
+ conf.load(HadoopFSTester.class.getClassLoader().getResourceAsStream(propFile));
+
+ HashMap<String,String> prop = new HashMap<String,String>() ;
+ for(Object key : conf.keySet()) {
+ Object val = conf.get(key) ;
+ prop.put((String)key, (String)val) ;
+ }
+
+ HadoopFS fs = new HadoopFS(repositoryName, prop) ;
+ List<String> fsList = fs.listFiles(baseDir, fileNameToMatch) ;
+ if (fsList != null && fsList.size() > 0) {
+ for(String s : fsList) {
+ System.out.println(s) ;
+ }
+ }
+ else {
+ System.err.println("Unable to get file listing for [" + baseDir + (baseDir.endsWith("/") ? "" : "/") + fileNameToMatch + "] in repository [" + repositoryName + "]") ;
+ }
+
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/org/apache/ranger/hadoop/client/config/BaseClient.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/org/apache/ranger/hadoop/client/config/BaseClient.java b/lookup-client/src/main/java/org/apache/ranger/hadoop/client/config/BaseClient.java
new file mode 100644
index 0000000..e7775d8
--- /dev/null
+++ b/lookup-client/src/main/java/org/apache/ranger/hadoop/client/config/BaseClient.java
@@ -0,0 +1,163 @@
+/*
+ * 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.hadoop.client.config;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+import javax.security.auth.Subject;
+
+import org.apache.commons.lang.StringUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.security.SecureClientLogin;
+import org.apache.ranger.hadoop.client.HadoopFS;
+import org.apache.ranger.hadoop.client.exceptions.HadoopException;
+
+public abstract class BaseClient {
+ private static final Log LOG = LogFactory.getLog(HadoopFS.class) ;
+
+ private String dataSource ;
+ private Subject loginSubject ;
+ private HadoopConfigHolder configHolder;
+
+ protected HashMap<String,String> connectionProperties ;
+
+ public BaseClient(String dataSource) {
+ this.dataSource = dataSource ;
+ init() ;
+ login() ;
+ }
+
+ public BaseClient(String dataSource, HashMap<String,String> connectionProperties) {
+ this.dataSource = dataSource ;
+ this.connectionProperties = connectionProperties ;
+ init() ;
+ login() ;
+ }
+
+
+ private void init() {
+ if (connectionProperties == null) {
+ configHolder = HadoopConfigHolder.getInstance(dataSource) ;
+ }
+ else {
+ configHolder = HadoopConfigHolder.getInstance(dataSource,connectionProperties) ;
+ }
+ }
+
+
+ protected void login() {
+ ClassLoader prevCl = Thread.currentThread().getContextClassLoader() ;
+ String errMsg = " You can still save the repository and start creating "
+ + "policies, but you would not be able to use autocomplete for "
+ + "resource names. Check xa_portal.log for more info.";
+ try {
+ Thread.currentThread().setContextClassLoader(configHolder.getClassLoader());
+ String userName = configHolder.getUserName() ;
+ if (userName == null) {
+ String msgDesc = "Unable to find login username for hadoop environment, ["
+ + dataSource + "]";
+ HadoopException hdpException = new HadoopException(msgDesc);
+ hdpException.generateResponseDataMap(false, msgDesc, msgDesc + errMsg,
+ null, null);
+
+ throw hdpException;
+ }
+ String keyTabFile = configHolder.getKeyTabFile() ;
+ if (keyTabFile != null) {
+ if ( configHolder.isKerberosAuthentication() ) {
+ LOG.info("Init Login: security enabled, using username/keytab");
+ loginSubject = SecureClientLogin.loginUserFromKeytab(userName, keyTabFile) ;
+ }
+ else {
+ LOG.info("Init Login: using username");
+ loginSubject = SecureClientLogin.login(userName) ;
+ }
+ }
+ else {
+ String password = configHolder.getPassword() ;
+ if ( configHolder.isKerberosAuthentication() ) {
+ LOG.info("Init Login: using username/password");
+ loginSubject = SecureClientLogin.loginUserWithPassword(userName, password) ;
+ }
+ else {
+ LOG.info("Init Login: security not enabled, using username");
+ loginSubject = SecureClientLogin.login(userName) ;
+ }
+ }
+ } catch (IOException ioe) {
+ String msgDesc = "Unable to login to Hadoop environment ["
+ + dataSource + "]";
+
+ HadoopException hdpException = new HadoopException(msgDesc, ioe);
+ hdpException.generateResponseDataMap(false, getMessage(ioe),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ } catch (SecurityException se) {
+ String msgDesc = "Unable to login to Hadoop environment ["
+ + dataSource + "]";
+ HadoopException hdpException = new HadoopException(msgDesc, se);
+ hdpException.generateResponseDataMap(false, getMessage(se),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ } finally {
+ Thread.currentThread().setContextClassLoader(prevCl);
+ }
+ }
+
+ public String getDataSource() {
+ return dataSource ;
+ }
+
+ protected Subject getLoginSubject() {
+ return loginSubject;
+ }
+
+ protected HadoopConfigHolder getConfigHolder() {
+ return configHolder;
+ }
+
+ public static void generateResponseDataMap(boolean connectivityStatus,
+ String message, String description, Long objectId,
+ String fieldName, HashMap<String, Object> responseData) {
+ responseData.put("connectivityStatus", connectivityStatus);
+ responseData.put("message", message);
+ responseData.put("description", description);
+ responseData.put("objectId", objectId);
+ responseData.put("fieldName", fieldName);
+ }
+
+ public static String getMessage(Throwable excp) {
+ List<String> errList = new ArrayList<String>();
+ while (excp != null) {
+ if (!errList.contains(excp.getMessage() + ". \n")) {
+ if (excp.getMessage() != null && !(excp.getMessage().equalsIgnoreCase(""))) {
+ errList.add(excp.getMessage() + ". \n");
+ }
+ }
+ excp = excp.getCause();
+ }
+ return StringUtils.join(errList, "");
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/org/apache/ranger/hadoop/client/config/HadoopClassLoader.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/org/apache/ranger/hadoop/client/config/HadoopClassLoader.java b/lookup-client/src/main/java/org/apache/ranger/hadoop/client/config/HadoopClassLoader.java
new file mode 100644
index 0000000..bb13538
--- /dev/null
+++ b/lookup-client/src/main/java/org/apache/ranger/hadoop/client/config/HadoopClassLoader.java
@@ -0,0 +1,105 @@
+/*
+ * 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.hadoop.client.config;
+
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.net.URL;
+import java.util.Properties;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.hadoop.client.exceptions.HadoopException;
+
+public class HadoopClassLoader extends ClassLoader {
+
+ private static final Log LOG = LogFactory.getLog(HadoopClassLoader.class) ;
+
+ private HadoopConfigHolder confHolder ;
+
+ public HadoopClassLoader(HadoopConfigHolder confHolder) {
+ super(Thread.currentThread().getContextClassLoader()) ;
+ this.confHolder = confHolder;
+ }
+
+
+ @Override
+ protected URL findResource(String resourceName) {
+ LOG.debug("findResource(" + resourceName + ") is called.") ;
+ URL ret = null;
+
+ if (confHolder.hasResourceExists(resourceName)) {
+ ret = buildResourceFile(resourceName) ;
+ }
+ else {
+ ret = super.findResource(resourceName);
+ }
+ LOG.debug("findResource(" + resourceName + ") is returning [" + ret + "]") ;
+ return ret ;
+ }
+
+
+ @SuppressWarnings("deprecation")
+ private URL buildResourceFile(String aResourceName) {
+ URL ret = null ;
+ String prefix = aResourceName ;
+ String suffix = ".txt" ;
+
+ Properties prop = confHolder.getProperties(aResourceName) ;
+ LOG.debug("Building XML for: " + prop.toString());
+ if (prop != null && prop.size() > 0) {
+ if (aResourceName.contains(".")) {
+ int lastDotFound = aResourceName.indexOf(".") ;
+ prefix = aResourceName.substring(0,lastDotFound) + "-" ;
+ suffix = aResourceName.substring(lastDotFound) ;
+ }
+
+ try {
+ File tempFile = File.createTempFile(prefix, suffix) ;
+ tempFile.deleteOnExit();
+ PrintWriter out = new PrintWriter(new FileWriter(tempFile)) ;
+ out.println("<?xml version=\"1.0\"?>") ;
+ out.println("<?xml-stylesheet type=\"text/xsl\" href=\"configuration.xsl\"?>") ;
+ out.println("<configuration xmlns:xi=\"http://www.w3.org/2001/XInclude\">") ;
+ for(Object keyobj : prop.keySet()) {
+ String key = (String)keyobj;
+ String val = prop.getProperty(key) ;
+ if (HadoopConfigHolder.HADOOP_RPC_PROTECTION.equals(key) && (val == null || val.trim().isEmpty())) {
+ continue;
+ }
+ out.println("<property><name>" + key.trim() + "</name><value>" + val + "</value></property>") ;
+ }
+ out.println("</configuration>") ;
+ out.close() ;
+ ret = tempFile.toURL() ;
+ } catch (IOException e) {
+ throw new HadoopException("Unable to load create hadoop configuration file [" + aResourceName + "]", e) ;
+ }
+
+ }
+
+ return ret ;
+
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/org/apache/ranger/hadoop/client/config/HadoopConfigHolder.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/org/apache/ranger/hadoop/client/config/HadoopConfigHolder.java b/lookup-client/src/main/java/org/apache/ranger/hadoop/client/config/HadoopConfigHolder.java
new file mode 100644
index 0000000..7651bb5
--- /dev/null
+++ b/lookup-client/src/main/java/org/apache/ranger/hadoop/client/config/HadoopConfigHolder.java
@@ -0,0 +1,360 @@
+/*
+ * 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.hadoop.client.config;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.Properties;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.hadoop.client.exceptions.HadoopException;
+
+public class HadoopConfigHolder {
+ private static final Log LOG = LogFactory.getLog(HadoopConfigHolder.class) ;
+ public static final String GLOBAL_LOGIN_PARAM_PROP_FILE = "hadoop-login.properties" ;
+ public static final String DEFAULT_DATASOURCE_PARAM_PROP_FILE = "datasource.properties" ;
+ public static final String RESOURCEMAP_PROP_FILE = "resourcenamemap.properties" ;
+ public static final String DEFAULT_RESOURCE_NAME = "core-site.xml" ;
+ public static final String RANGER_SECTION_NAME = "xalogin.xml" ;
+ public static final String RANGER_LOGIN_USER_NAME_PROP = "username" ;
+ public static final String RANGER_LOGIN_KEYTAB_FILE_PROP = "keytabfile" ;
+ public static final String RANGER_LOGIN_PASSWORD = "password" ;
+ public static final String HADOOP_SECURITY_AUTHENTICATION = "hadoop.security.authentication";
+ public static final String HADOOP_SECURITY_AUTHENTICATION_METHOD = "kerberos";
+ public static final String HADOOP_RPC_PROTECTION = "hadoop.rpc.protection";
+
+
+ private static boolean initialized = false ;
+ private static HashMap<String,HashMap<String,Properties>> dataSource2ResourceListMap = new HashMap<String,HashMap<String,Properties>>() ;
+ private static Properties globalLoginProp = new Properties() ;
+ private static HashMap<String,HadoopConfigHolder> dataSource2HadoopConfigHolder = new HashMap<String,HadoopConfigHolder>() ;
+ private static Properties resourcemapProperties = null ;
+
+
+ private String datasourceName ;
+ private String userName ;
+ private String keyTabFile ;
+ private String password ;
+ private boolean isKerberosAuth ;
+
+ private HadoopClassLoader classLoader ;
+ private HashMap<String,String> connectionProperties;
+
+ public static HadoopConfigHolder getInstance(String aDatasourceName) {
+ HadoopConfigHolder ret = dataSource2HadoopConfigHolder.get(aDatasourceName) ;
+ if (ret == null) {
+ synchronized(HadoopConfigHolder.class) {
+ HadoopConfigHolder temp = ret ;
+ if (temp == null) {
+ ret = new HadoopConfigHolder(aDatasourceName) ;
+ dataSource2HadoopConfigHolder.put(aDatasourceName, ret) ;
+ }
+ }
+ }
+ return ret ;
+ }
+
+ public static HadoopConfigHolder getInstance(String aDatasourceName, HashMap<String,String> connectionProperties) {
+ HadoopConfigHolder ret = dataSource2HadoopConfigHolder.get(aDatasourceName) ;
+ if (ret == null) {
+ synchronized(HadoopConfigHolder.class) {
+ HadoopConfigHolder temp = ret ;
+ if (temp == null) {
+ ret = new HadoopConfigHolder(aDatasourceName,connectionProperties) ;
+ dataSource2HadoopConfigHolder.put(aDatasourceName, ret) ;
+ }
+ }
+ }
+ else {
+ if (connectionProperties !=null && !connectionProperties.equals(ret.connectionProperties)) {
+ ret = new HadoopConfigHolder(aDatasourceName,connectionProperties) ;
+ dataSource2HadoopConfigHolder.remove(aDatasourceName) ;
+ dataSource2HadoopConfigHolder.put(aDatasourceName, ret) ;
+ }
+ }
+ return ret ;
+ }
+
+
+
+ private HadoopConfigHolder(String aDatasourceName) {
+ datasourceName = aDatasourceName;
+ if ( ! initialized ) {
+ init() ;
+ }
+ initLoginInfo();
+ initClassLoader() ;
+ }
+
+ private HadoopConfigHolder(String aDatasourceName, HashMap<String,String> connectionProperties) {
+ datasourceName = aDatasourceName;
+ this.connectionProperties = connectionProperties ;
+ initConnectionProp() ;
+ initLoginInfo();
+ initClassLoader() ;
+ }
+
+ private void initConnectionProp() {
+ for(String key : connectionProperties.keySet()) {
+
+ String resourceName = getResourceName(key) ;
+
+ if (resourceName == null) {
+ resourceName = RANGER_SECTION_NAME ;
+ }
+ String val = connectionProperties.get(key) ;
+ addConfiguration(datasourceName, resourceName, key, val );
+ }
+ }
+
+ private String getResourceName(String key) {
+
+ if (resourcemapProperties == null) {
+ initResourceMap();
+ }
+
+ if (resourcemapProperties != null) {
+ return resourcemapProperties.getProperty(key);
+ }
+ else {
+ return null;
+ }
+ }
+
+ public static void initResourceMap() {
+ if (resourcemapProperties == null) {
+ resourcemapProperties = new Properties() ;
+ InputStream in = HadoopConfigHolder.class.getClassLoader().getResourceAsStream(RESOURCEMAP_PROP_FILE) ;
+ if (in != null) {
+ try {
+ resourcemapProperties.load(in);
+ } catch (IOException e) {
+ throw new HadoopException("Unable to load resource map properties from [" + RESOURCEMAP_PROP_FILE + "]", e);
+ }
+ }
+ else {
+ throw new HadoopException("Unable to locate resource map properties from [" + RESOURCEMAP_PROP_FILE + "] in the class path.");
+ }
+ }
+ }
+
+
+
+ private static synchronized void init() {
+
+ if (initialized) {
+ return ;
+ }
+
+ try {
+ InputStream in = HadoopConfigHolder.class.getClassLoader().getResourceAsStream(DEFAULT_DATASOURCE_PARAM_PROP_FILE) ;
+ if (in != null) {
+ Properties prop = new Properties() ;
+ try {
+ prop.load(in) ;
+ } catch (IOException e) {
+ throw new HadoopException("Unable to get configuration information for Hadoop environments", e);
+ }
+ finally {
+ try {
+ in.close();
+ } catch (IOException e) {
+ // Ignored exception when the stream is closed.
+ }
+ }
+
+ if (prop.size() == 0)
+ return ;
+
+ for(Object keyobj : prop.keySet()) {
+ String key = (String)keyobj;
+ String val = prop.getProperty(key) ;
+
+ int dotLocatedAt = key.indexOf(".") ;
+
+ if (dotLocatedAt == -1) {
+ continue ;
+ }
+
+ String dataSource = key.substring(0,dotLocatedAt) ;
+
+ String propKey = key.substring(dotLocatedAt+1) ;
+ int resourceFoundAt = propKey.indexOf(".") ;
+ if (resourceFoundAt > -1) {
+ String resourceName = propKey.substring(0, resourceFoundAt) + ".xml" ;
+ propKey = propKey.substring(resourceFoundAt+1) ;
+ addConfiguration(dataSource, resourceName, propKey, val) ;
+ }
+
+ }
+ }
+
+ in = HadoopConfigHolder.class.getClassLoader().getResourceAsStream(GLOBAL_LOGIN_PARAM_PROP_FILE) ;
+ if (in != null) {
+ Properties tempLoginProp = new Properties() ;
+ try {
+ tempLoginProp.load(in) ;
+ } catch (IOException e) {
+ throw new HadoopException("Unable to get login configuration information for Hadoop environments from file: [" + GLOBAL_LOGIN_PARAM_PROP_FILE + "]", e);
+ }
+ finally {
+ try {
+ in.close();
+ } catch (IOException e) {
+ // Ignored exception when the stream is closed.
+ }
+ }
+ globalLoginProp = tempLoginProp ;
+ }
+ }
+ finally {
+ initialized = true ;
+ }
+ }
+
+
+ private void initLoginInfo() {
+ Properties prop = this.getRangerSection() ;
+ if (prop != null) {
+ userName = prop.getProperty(RANGER_LOGIN_USER_NAME_PROP) ;
+ keyTabFile = prop.getProperty(RANGER_LOGIN_KEYTAB_FILE_PROP) ;
+ password = prop.getProperty(RANGER_LOGIN_PASSWORD) ;
+
+ if ( getHadoopSecurityAuthentication() != null) {
+ isKerberosAuth = ( getHadoopSecurityAuthentication().equalsIgnoreCase(HADOOP_SECURITY_AUTHENTICATION_METHOD));
+ }
+ else {
+ isKerberosAuth = (userName != null) && (userName.indexOf("@") > -1) ;
+ }
+
+ }
+ }
+
+ private void initClassLoader() {
+ classLoader = new HadoopClassLoader(this) ;
+ }
+
+
+ public Properties getRangerSection() {
+ Properties prop = this.getProperties(RANGER_SECTION_NAME) ;
+ if (prop == null) {
+ prop = globalLoginProp ;
+ }
+ return prop ;
+ }
+
+
+
+ private static void addConfiguration(String dataSource, String resourceName, String propertyName, String value) {
+
+ if (dataSource == null || dataSource.isEmpty()) {
+ return ;
+ }
+
+ if (propertyName == null || propertyName.isEmpty()) {
+ return ;
+ }
+
+ if (resourceName == null) {
+ resourceName = DEFAULT_RESOURCE_NAME ;
+ }
+
+
+ HashMap<String,Properties> resourceName2PropertiesMap = dataSource2ResourceListMap.get(dataSource) ;
+
+ if (resourceName2PropertiesMap == null) {
+ resourceName2PropertiesMap = new HashMap<String,Properties>() ;
+ dataSource2ResourceListMap.put(dataSource, resourceName2PropertiesMap) ;
+ }
+
+ Properties prop = resourceName2PropertiesMap.get(resourceName) ;
+ if (prop == null) {
+ prop = new Properties() ;
+ resourceName2PropertiesMap.put(resourceName, prop) ;
+ }
+ if (value == null) {
+ prop.remove(propertyName) ;
+ }
+ else {
+ prop.put(propertyName, value) ;
+ }
+ }
+
+
+ public String getDatasourceName() {
+ return datasourceName ;
+ }
+
+ public boolean hasResourceExists(String aResourceName) {
+ HashMap<String,Properties> resourceName2PropertiesMap = dataSource2ResourceListMap.get(datasourceName) ;
+ return (resourceName2PropertiesMap != null && resourceName2PropertiesMap.containsKey(aResourceName)) ;
+ }
+
+ public Properties getProperties(String aResourceName) {
+ Properties ret = null ;
+ HashMap<String,Properties> resourceName2PropertiesMap = dataSource2ResourceListMap.get(datasourceName) ;
+ if (resourceName2PropertiesMap != null) {
+ ret = resourceName2PropertiesMap.get(aResourceName) ;
+ }
+ return ret ;
+ }
+
+ public String getHadoopSecurityAuthentication() {
+ Properties repoParam = null ;
+ String ret = null;
+
+ HashMap<String,Properties> resourceName2PropertiesMap = dataSource2ResourceListMap.get(this.getDatasourceName()) ;
+
+ if ( resourceName2PropertiesMap != null) {
+ repoParam=resourceName2PropertiesMap.get(DEFAULT_RESOURCE_NAME);
+ }
+
+ if ( repoParam != null ) {
+ ret = (String)repoParam.get(HADOOP_SECURITY_AUTHENTICATION);
+ }
+ return ret;
+ }
+
+ public String getUserName() {
+ return userName;
+ }
+
+ public String getKeyTabFile() {
+ return keyTabFile;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public HadoopClassLoader getClassLoader() {
+ return classLoader;
+ }
+
+ public boolean isKerberosAuthentication() {
+ return isKerberosAuth;
+ }
+
+
+
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/org/apache/ranger/hadoop/client/exceptions/HadoopException.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/org/apache/ranger/hadoop/client/exceptions/HadoopException.java b/lookup-client/src/main/java/org/apache/ranger/hadoop/client/exceptions/HadoopException.java
new file mode 100644
index 0000000..5614343
--- /dev/null
+++ b/lookup-client/src/main/java/org/apache/ranger/hadoop/client/exceptions/HadoopException.java
@@ -0,0 +1,60 @@
+/*
+ * 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.hadoop.client.exceptions;
+
+import java.util.HashMap;
+
+public class HadoopException extends RuntimeException {
+
+ private static final long serialVersionUID = 8872734935128535649L;
+
+ public HashMap<String, Object> responseData;
+
+ public HadoopException() {
+ super();
+ // TODO Auto-generated constructor stub
+ }
+
+ public HadoopException(String message, Throwable cause) {
+ super(message, cause);
+ // TODO Auto-generated constructor stub
+ }
+
+ public HadoopException(String message) {
+ super(message);
+ // TODO Auto-generated constructor stub
+ }
+
+ public HadoopException(Throwable cause) {
+ super(cause);
+ // TODO Auto-generated constructor stub
+ }
+
+ public void generateResponseDataMap(boolean connectivityStatus,
+ String message, String description, Long objectId, String fieldName) {
+ responseData = new HashMap<String, Object>();
+ responseData.put("connectivityStatus", connectivityStatus);
+ responseData.put("message", message);
+ responseData.put("description", description);
+ responseData.put("objectId", objectId);
+ responseData.put("fieldName", fieldName);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/org/apache/ranger/hbase/client/HBaseClient.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/org/apache/ranger/hbase/client/HBaseClient.java b/lookup-client/src/main/java/org/apache/ranger/hbase/client/HBaseClient.java
new file mode 100644
index 0000000..1df5a0b
--- /dev/null
+++ b/lookup-client/src/main/java/org/apache/ranger/hbase/client/HBaseClient.java
@@ -0,0 +1,403 @@
+/*
+ * 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.hbase.client;
+
+import java.io.IOException;
+import java.security.PrivilegedAction;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map.Entry;
+
+import javax.security.auth.Subject;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.HBaseConfiguration;
+import org.apache.hadoop.hbase.HColumnDescriptor;
+import org.apache.hadoop.hbase.HTableDescriptor;
+import org.apache.hadoop.hbase.MasterNotRunningException;
+import org.apache.hadoop.hbase.ZooKeeperConnectionException;
+import org.apache.hadoop.hbase.client.HBaseAdmin;
+import org.apache.ranger.hadoop.client.config.BaseClient;
+import org.apache.ranger.hadoop.client.exceptions.HadoopException;
+
+import com.google.protobuf.ServiceException;
+
+public class HBaseClient extends BaseClient {
+
+ private static final Log LOG = LogFactory.getLog(HBaseClient.class) ;
+
+ private Subject subj = null ;
+
+ public HBaseClient(String dataSource) {
+ super(dataSource) ;
+ }
+
+ public HBaseClient(String dataSource,HashMap<String,String> connectionProp) {
+ super(dataSource, addDefaultHBaseProp(connectionProp)) ;
+ }
+
+ //TODO: temporary solution - to be added to the UI for HBase
+ private static HashMap<String,String> addDefaultHBaseProp(HashMap<String,String> connectionProp) {
+ if (connectionProp != null) {
+ String param = "zookeeper.znode.parent" ;
+ String unsecuredPath = "/hbase-unsecure" ;
+ String authParam = "hadoop.security.authorization" ;
+
+ String ret = connectionProp.get(param) ;
+ LOG.info("HBase connection has [" + param + "] with value [" + ret + "]");
+ if (ret == null) {
+ ret = connectionProp.get(authParam) ;
+ LOG.info("HBase connection has [" + authParam + "] with value [" + ret + "]");
+ if (ret != null && ret.trim().equalsIgnoreCase("false")) {
+ LOG.info("HBase connection is resetting [" + param + "] with value [" + unsecuredPath + "]");
+ connectionProp.put(param, unsecuredPath) ;
+ }
+ }
+ }
+ return connectionProp;
+ }
+
+ public static HashMap<String, Object> testConnection(String dataSource,
+ HashMap<String, String> connectionProperties) {
+
+ HashMap<String, Object> responseData = new HashMap<String, Object>();
+ final String errMsg = " You can still save the repository and start creating "
+ + "policies, but you would not be able to use autocomplete for "
+ + "resource names. Check xa_portal.log for more info.";
+ boolean connectivityStatus = false;
+
+ HBaseClient connectionObj = new HBaseClient(dataSource,
+ connectionProperties);
+ if (connectionObj != null) {
+ connectivityStatus = connectionObj.getHBaseStatus();
+ }
+
+ if (connectivityStatus) {
+ String successMsg = "TestConnection Successful";
+ generateResponseDataMap(connectivityStatus, successMsg, successMsg,
+ null, null, responseData);
+ } else {
+ String failureMsg = "Unable to retrieve any databases using given parameters.";
+ generateResponseDataMap(connectivityStatus, failureMsg, failureMsg
+ + errMsg, null, null, responseData);
+ }
+ return responseData;
+ }
+
+ public boolean getHBaseStatus() {
+ boolean hbaseStatus = false;
+ subj = getLoginSubject();
+ final String errMsg = " You can still save the repository and start creating "
+ + "policies, but you would not be able to use autocomplete for "
+ + "resource names. Check xa_portal.log for more info.";
+ if (subj != null) {
+ ClassLoader prevCl = Thread.currentThread().getContextClassLoader() ;
+ try {
+ Thread.currentThread().setContextClassLoader(getConfigHolder().getClassLoader());
+
+ hbaseStatus = Subject.doAs(subj, new PrivilegedAction<Boolean>() {
+ @Override
+ public Boolean run() {
+ Boolean hbaseStatus1 = false;
+ try {
+ LOG.info("getHBaseStatus: creating default Hbase configuration");
+ Configuration conf = HBaseConfiguration.create() ;
+ LOG.info("getHBaseStatus: setting config values from client");
+ setClientConfigValues(conf);
+ LOG.info("getHBaseStatus: checking HbaseAvailability with the new config");
+ HBaseAdmin.checkHBaseAvailable(conf);
+ LOG.info("getHBaseStatus: no exception: HbaseAvailability true");
+ hbaseStatus1 = true;
+ } catch (ZooKeeperConnectionException zce) {
+ String msgDesc = "getHBaseStatus: Unable to connect to `ZooKeeper` "
+ + "using given config parameters.";
+ HadoopException hdpException = new HadoopException(msgDesc, zce);
+ hdpException.generateResponseDataMap(false, getMessage(zce),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+
+ } catch (MasterNotRunningException mnre) {
+ String msgDesc = "getHBaseStatus: Looks like `Master` is not running, "
+ + "so couldn't check that running HBase is available or not, "
+ + "Please try again later.";
+ HadoopException hdpException = new HadoopException(
+ msgDesc, mnre);
+ hdpException.generateResponseDataMap(false,
+ getMessage(mnre), msgDesc + errMsg,
+ null, null);
+ throw hdpException;
+
+ } catch (ServiceException se) {
+ String msgDesc = "getHBaseStatus: Unable to check availability of "
+ + "Hbase environment [" + getConfigHolder().getDatasourceName() + "].";
+ HadoopException hdpException = new HadoopException(msgDesc, se);
+ hdpException.generateResponseDataMap(false, getMessage(se),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+
+ } catch(IOException io) {
+ String msgDesc = "getHBaseStatus: Unable to check availability of"
+ + " Hbase environment [" + getConfigHolder().getDatasourceName() + "].";
+ HadoopException hdpException = new HadoopException(msgDesc, io);
+ hdpException.generateResponseDataMap(false, getMessage(io),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+
+ } catch (Throwable e) {
+ String msgDesc = "getHBaseStatus: Unable to check availability of"
+ + " Hbase environment [" + getConfigHolder().getDatasourceName() + "].";
+ LOG.error(msgDesc);
+ hbaseStatus1 = false;
+ HadoopException hdpException = new HadoopException(msgDesc, e);
+ hdpException.generateResponseDataMap(false, getMessage(e),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ }
+ return hbaseStatus1;
+ }
+ }) ;
+ } catch (SecurityException se) {
+ String msgDesc = "getHBaseStatus: Unable to connect to HBase Server instance, "
+ + "current thread might not be able set the context ClassLoader.";
+ HadoopException hdpException = new HadoopException(msgDesc, se);
+ hdpException.generateResponseDataMap(false, getMessage(se),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ } finally {
+ Thread.currentThread().setContextClassLoader(prevCl);
+ }
+ } else {
+ LOG.error("getHBaseStatus: secure login not done, subject is null");
+ }
+
+ return hbaseStatus;
+ }
+
+ private void setClientConfigValues(Configuration conf) {
+ if (this.connectionProperties == null) return;
+ Iterator<Entry<String, String>> i = this.connectionProperties.entrySet().iterator();
+ while (i.hasNext()) {
+ Entry<String, String> e = i.next();
+ String v = conf.get(e.getKey());
+ if (v != null && !v.equalsIgnoreCase(e.getValue())) {
+ conf.set(e.getKey(), e.getValue());
+ }
+ }
+ }
+
+ public List<String> getTableList(final String tableNameMatching) {
+ List<String> ret = null ;
+ final String errMsg = " You can still save the repository and start creating "
+ + "policies, but you would not be able to use autocomplete for "
+ + "resource names. Check xa_portal.log for more info.";
+
+ subj = getLoginSubject();
+
+ if (subj != null) {
+ ClassLoader prevCl = Thread.currentThread().getContextClassLoader() ;
+ try {
+ Thread.currentThread().setContextClassLoader(getConfigHolder().getClassLoader());
+
+ ret = Subject.doAs(subj, new PrivilegedAction<List<String>>() {
+
+ @Override
+ public List<String> run() {
+
+ List<String> tableList = new ArrayList<String>() ;
+ HBaseAdmin admin = null ;
+ try {
+
+ Configuration conf = HBaseConfiguration.create() ;
+ admin = new HBaseAdmin(conf) ;
+ for (HTableDescriptor htd : admin.listTables(tableNameMatching)) {
+ tableList.add(htd.getNameAsString()) ;
+ }
+ } catch (ZooKeeperConnectionException zce) {
+ String msgDesc = "getTableList: Unable to connect to `ZooKeeper` "
+ + "using given config parameters.";
+ HadoopException hdpException = new HadoopException(msgDesc, zce);
+ hdpException.generateResponseDataMap(false, getMessage(zce),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+
+ } catch (MasterNotRunningException mnre) {
+ String msgDesc = "getTableList: Looks like `Master` is not running, "
+ + "so couldn't check that running HBase is available or not, "
+ + "Please try again later.";
+ HadoopException hdpException = new HadoopException(
+ msgDesc, mnre);
+ hdpException.generateResponseDataMap(false,
+ getMessage(mnre), msgDesc + errMsg,
+ null, null);
+ throw hdpException;
+
+ } catch(IOException io) {
+ String msgDesc = "Unable to get HBase table List for [repository:"
+ + getConfigHolder().getDatasourceName() + ",table-match:"
+ + tableNameMatching + "].";
+ HadoopException hdpException = new HadoopException(msgDesc, io);
+ hdpException.generateResponseDataMap(false, getMessage(io),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ } catch (Throwable e) {
+ String msgDesc = "Unable to get HBase table List for [repository:"
+ + getConfigHolder().getDatasourceName() + ",table-match:"
+ + tableNameMatching + "].";
+ LOG.error(msgDesc);
+ HadoopException hdpException = new HadoopException(msgDesc, e);
+ hdpException.generateResponseDataMap(false, getMessage(e),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ }
+ finally {
+ if (admin != null) {
+ try {
+ admin.close() ;
+ } catch (IOException e) {
+ LOG.error("Unable to close HBase connection [" + getConfigHolder().getDatasourceName() + "]", e);
+ }
+ }
+ }
+ return tableList ;
+ }
+
+ }) ;
+ }
+ finally {
+ Thread.currentThread().setContextClassLoader(prevCl);
+ }
+ }
+ return ret ;
+ }
+
+
+ public List<String> getColumnFamilyList(final String tableName, final String columnFamilyMatching) {
+ List<String> ret = null ;
+ final String errMsg = " You can still save the repository and start creating "
+ + "policies, but you would not be able to use autocomplete for "
+ + "resource names. Check xa_portal.log for more info.";
+
+ subj = getLoginSubject();
+ if (subj != null) {
+ ClassLoader prevCl = Thread.currentThread().getContextClassLoader() ;
+ try {
+ Thread.currentThread().setContextClassLoader(getConfigHolder().getClassLoader());
+
+ ret = Subject.doAs(subj, new PrivilegedAction<List<String>>() {
+
+ @Override
+ public List<String> run() {
+
+ List<String> colfList = new ArrayList<String>() ;
+ HBaseAdmin admin = null ;
+ try {
+ Configuration conf = HBaseConfiguration.create();
+ admin = new HBaseAdmin(conf) ;
+ HTableDescriptor htd = admin.getTableDescriptor(tableName.getBytes()) ;
+ if (htd != null) {
+ for (HColumnDescriptor hcd : htd.getColumnFamilies()) {
+ String colf = hcd.getNameAsString() ;
+ if (colf.matches(columnFamilyMatching)) {
+ if (!colfList.contains(colf)) {
+ colfList.add(colf) ;
+ }
+ }
+ }
+ }
+ } catch (ZooKeeperConnectionException zce) {
+ String msgDesc = "getColumnFamilyList: Unable to connect to `ZooKeeper` "
+ + "using given config parameters.";
+ HadoopException hdpException = new HadoopException(msgDesc, zce);
+ hdpException.generateResponseDataMap(false, getMessage(zce),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+
+ } catch (MasterNotRunningException mnre) {
+ String msgDesc = "getColumnFamilyList: Looks like `Master` is not running, "
+ + "so couldn't check that running HBase is available or not, "
+ + "Please try again later.";
+ HadoopException hdpException = new HadoopException(
+ msgDesc, mnre);
+ hdpException.generateResponseDataMap(false,
+ getMessage(mnre), msgDesc + errMsg,
+ null, null);
+ throw hdpException;
+
+ } catch(IOException io) {
+ String msgDesc = "getColumnFamilyList: Unable to get HBase ColumnFamilyList for "
+ + "[repository:" +getConfigHolder().getDatasourceName() + ",table:" + tableName
+ + ", table-match:" + columnFamilyMatching + "], "
+ + "current thread might not be able set the context ClassLoader.";
+ HadoopException hdpException = new HadoopException(msgDesc, io);
+ hdpException.generateResponseDataMap(false, getMessage(io),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ } catch (SecurityException se) {
+ String msgDesc = "getColumnFamilyList: Unable to get HBase ColumnFamilyList for "
+ + "[repository:" +getConfigHolder().getDatasourceName() + ",table:" + tableName
+ + ", table-match:" + columnFamilyMatching + "], "
+ + "current thread might not be able set the context ClassLoader.";
+ HadoopException hdpException = new HadoopException(msgDesc, se);
+ hdpException.generateResponseDataMap(false, getMessage(se),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+
+ } catch (Throwable e) {
+ String msgDesc = "getColumnFamilyList: Unable to get HBase ColumnFamilyList for "
+ + "[repository:" +getConfigHolder().getDatasourceName() + ",table:" + tableName
+ + ", table-match:" + columnFamilyMatching + "], "
+ + "current thread might not be able set the context ClassLoader.";
+ LOG.error(msgDesc);
+ HadoopException hdpException = new HadoopException(msgDesc, e);
+ hdpException.generateResponseDataMap(false, getMessage(e),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ }
+ finally {
+ if (admin != null) {
+ try {
+ admin.close() ;
+ } catch (IOException e) {
+ LOG.error("Unable to close HBase connection [" + getConfigHolder().getDatasourceName() + "]", e);
+ }
+ }
+ }
+ return colfList ;
+ }
+
+ }) ;
+ } catch (SecurityException se) {
+ String msgDesc = "getColumnFamilyList: Unable to connect to HBase Server instance, "
+ + "current thread might not be able set the context ClassLoader.";
+ HadoopException hdpException = new HadoopException(msgDesc, se);
+ hdpException.generateResponseDataMap(false, getMessage(se),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ } finally {
+ Thread.currentThread().setContextClassLoader(prevCl);
+ }
+ }
+ return ret ;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/org/apache/ranger/hbase/client/HBaseClientTester.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/org/apache/ranger/hbase/client/HBaseClientTester.java b/lookup-client/src/main/java/org/apache/ranger/hbase/client/HBaseClientTester.java
new file mode 100644
index 0000000..dc177e6
--- /dev/null
+++ b/lookup-client/src/main/java/org/apache/ranger/hbase/client/HBaseClientTester.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.hbase.client;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Properties;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class HBaseClientTester {
+
+ private static final Log LOG = LogFactory.getLog(HBaseClientTester.class) ;
+
+ public static void main(String[] args) throws Throwable {
+
+ HBaseClient hc = null;
+
+ if (args.length <= 2) {
+ System.err.println("USAGE: java " + HBaseClientTester.class.getName() + " dataSourceName propertyFile <tableName> <columnFamilyName>");
+ System.exit(1);
+ }
+
+ LOG.info("Starting ...");
+
+ Properties conf = new Properties();
+
+ conf.load(HBaseClientTester.class.getClassLoader().getResourceAsStream(args[1]));
+
+ HashMap<String, String> prop = new HashMap<String, String>();
+ for (Object key : conf.keySet()) {
+ Object val = conf.get(key);
+ prop.put((String) key, (String) val);
+ }
+
+ hc = new HBaseClient(args[0], prop);
+
+ if (args.length == 3) {
+ List<String> dbList = hc.getTableList(args[2]);
+ if (dbList.size() == 0) {
+ System.out.println("No tables found with db filter [" + args[2] + "]");
+ } else {
+ for (String str : dbList) {
+ System.out.println("table: " + str);
+ }
+ }
+ } else if (args.length == 4) {
+ List<String> tableList = hc.getColumnFamilyList(args[2], args[3]);
+ if (tableList.size() == 0) {
+ System.out.println("No column families found under table [" + args[2] + "] with columnfamily filter [" + args[3] + "]");
+ } else {
+ for (String str : tableList) {
+ System.out.println("ColumnFamily: " + str);
+ }
+ }
+ }
+
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/org/apache/ranger/hive/client/HiveClient.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/org/apache/ranger/hive/client/HiveClient.java b/lookup-client/src/main/java/org/apache/ranger/hive/client/HiveClient.java
new file mode 100644
index 0000000..f8f50f8
--- /dev/null
+++ b/lookup-client/src/main/java/org/apache/ranger/hive/client/HiveClient.java
@@ -0,0 +1,510 @@
+/*
+ * 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.hive.client;
+
+import java.io.Closeable;
+import java.security.PrivilegedAction;
+import java.sql.Connection;
+import java.sql.Driver;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.SQLTimeoutException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Properties;
+
+import javax.security.auth.Subject;
+
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.hadoop.client.config.BaseClient;
+import org.apache.ranger.hadoop.client.exceptions.HadoopException;
+
+public class HiveClient extends BaseClient implements Closeable {
+
+ private static final Log LOG = LogFactory.getLog(HiveClient.class) ;
+
+ Connection con = null ;
+ boolean isKerberosAuth=false;
+
+
+ public HiveClient(String dataSource) {
+ super(dataSource) ;
+ initHive() ;
+ }
+
+ public HiveClient(String dataSource,HashMap<String,String> connectionProp) {
+ super(dataSource,connectionProp) ;
+ initHive() ;
+ }
+
+ public void initHive() {
+ isKerberosAuth = getConfigHolder().isKerberosAuthentication();
+ if (isKerberosAuth) {
+ LOG.info("Secured Mode: JDBC Connection done with preAuthenticated Subject");
+ Subject.doAs(getLoginSubject(), new PrivilegedAction<Object>() {
+ public Object run() {
+ initConnection();
+ return null;
+ }
+ }) ;
+ }
+ else {
+ LOG.info("Since Password is NOT provided, Trying to use UnSecure client with username and password");
+ final String userName = getConfigHolder().getUserName() ;
+ final String password = getConfigHolder().getPassword() ;
+ Subject.doAs(getLoginSubject(), new PrivilegedAction<Object>() {
+ public Object run() {
+ initConnection(userName,password);
+ return null;
+ }
+ }) ;
+ }
+ }
+
+ public List<String> getDatabaseList(String databaseMatching){
+ final String dbMatching=databaseMatching;
+ List<String> dblist = Subject.doAs(getLoginSubject(), new PrivilegedAction<List<String>>() {
+ public List<String> run() {
+ return getDBList(dbMatching);
+ }
+ }) ;
+ return dblist;
+ }
+
+ private List<String> getDBList(String databaseMatching) {
+ List<String> ret = new ArrayList<String>() ;
+ String errMsg = " You can still save the repository and start creating "
+ + "policies, but you would not be able to use autocomplete for "
+ + "resource names. Check xa_portal.log for more info.";
+ if (con != null) {
+ Statement stat = null ;
+ ResultSet rs = null ;
+ String sql = "show databases" ;
+ if (databaseMatching != null && ! databaseMatching.isEmpty()) {
+ sql = sql + " like \"" + databaseMatching + "\"" ;
+ }
+ try {
+ stat = con.createStatement() ;
+ rs = stat.executeQuery(sql) ;
+ while (rs.next()) {
+ ret.add(rs.getString(1)) ;
+ }
+ } catch (SQLTimeoutException sqlt) {
+ String msgDesc = "Time Out, Unable to execute SQL [" + sql
+ + "].";
+ HadoopException hdpException = new HadoopException(msgDesc,
+ sqlt);
+ hdpException.generateResponseDataMap(false, getMessage(sqlt),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ } catch (SQLException sqle) {
+ String msgDesc = "Unable to execute SQL [" + sql + "].";
+ HadoopException hdpException = new HadoopException(msgDesc,
+ sqle);
+ hdpException.generateResponseDataMap(false, getMessage(sqle),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ } finally {
+ close(rs) ;
+ close(stat) ;
+ }
+
+ }
+ return ret ;
+ }
+
+ public List<String> getTableList(String database, String tableNameMatching){
+ final String db=database;
+ final String tblNameMatching=tableNameMatching;
+ List<String> tableList = Subject.doAs(getLoginSubject(), new PrivilegedAction<List<String>>() {
+ public List<String> run() {
+ return getTblList(db,tblNameMatching);
+ }
+ }) ;
+ return tableList;
+ }
+
+ public List<String> getTblList(String database, String tableNameMatching) {
+ List<String> ret = new ArrayList<String>() ;
+ String errMsg = " You can still save the repository and start creating "
+ + "policies, but you would not be able to use autocomplete for "
+ + "resource names. Check xa_portal.log for more info.";
+ if (con != null) {
+ Statement stat = null ;
+ ResultSet rs = null ;
+
+ String sql = null ;
+
+ try {
+ sql = "use " + database;
+
+ try {
+ stat = con.createStatement() ;
+ stat.execute(sql) ;
+ }
+ finally {
+ close(stat) ;
+ }
+
+ sql = "show tables " ;
+ if (tableNameMatching != null && ! tableNameMatching.isEmpty()) {
+ sql = sql + " like \"" + tableNameMatching + "\"" ;
+ }
+ stat = con.createStatement() ;
+ rs = stat.executeQuery(sql) ;
+ while (rs.next()) {
+ ret.add(rs.getString(1)) ;
+ }
+ } catch (SQLTimeoutException sqlt) {
+ String msgDesc = "Time Out, Unable to execute SQL [" + sql
+ + "].";
+ HadoopException hdpException = new HadoopException(msgDesc,
+ sqlt);
+ hdpException.generateResponseDataMap(false, getMessage(sqlt),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ } catch (SQLException sqle) {
+ String msgDesc = "Unable to execute SQL [" + sql + "].";
+ HadoopException hdpException = new HadoopException(msgDesc,
+ sqle);
+ hdpException.generateResponseDataMap(false, getMessage(sqle),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ } finally {
+ close(rs) ;
+ close(stat) ;
+ }
+
+ }
+ return ret ;
+ }
+
+ public List<String> getViewList(String database, String viewNameMatching) {
+ List<String> ret = null ;
+ return ret ;
+ }
+
+ public List<String> getUDFList(String database, String udfMatching) {
+ List<String> ret = null ;
+ return ret ;
+ }
+
+ public List<String> getColumnList(String database, String tableName, String columnNameMatching) {
+ final String db=database;
+ final String tblName=tableName;
+ final String clmNameMatching=columnNameMatching;
+ List<String> columnList = Subject.doAs(getLoginSubject(), new PrivilegedAction<List<String>>() {
+ public List<String> run() {
+ return getClmList(db,tblName,clmNameMatching);
+ }
+ }) ;
+ return columnList;
+ }
+
+ public List<String> getClmList(String database, String tableName, String columnNameMatching) {
+ List<String> ret = new ArrayList<String>() ;
+ String errMsg = " You can still save the repository and start creating "
+ + "policies, but you would not be able to use autocomplete for "
+ + "resource names. Check xa_portal.log for more info.";
+ if (con != null) {
+
+ String columnNameMatchingRegEx = null ;
+
+ if (columnNameMatching != null && ! columnNameMatching.isEmpty()) {
+ columnNameMatchingRegEx = columnNameMatching ;
+ }
+
+ Statement stat = null ;
+ ResultSet rs = null ;
+
+ String sql = null ;
+
+ try {
+ sql = "use " + database;
+
+ try {
+ stat = con.createStatement() ;
+ stat.execute(sql) ;
+ }
+ finally {
+ close(stat) ;
+ }
+
+ sql = "describe " + tableName ;
+ stat = con.createStatement() ;
+ rs = stat.executeQuery(sql) ;
+ while (rs.next()) {
+ String columnName = rs.getString(1) ;
+ if (columnNameMatchingRegEx == null) {
+ ret.add(columnName) ;
+ }
+ else if (FilenameUtils.wildcardMatch(columnName,columnNameMatchingRegEx)) {
+ ret.add(columnName) ;
+ }
+ }
+ } catch (SQLTimeoutException sqlt) {
+ String msgDesc = "Time Out, Unable to execute SQL [" + sql
+ + "].";
+ HadoopException hdpException = new HadoopException(msgDesc,
+ sqlt);
+ hdpException.generateResponseDataMap(false, getMessage(sqlt),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ } catch (SQLException sqle) {
+ String msgDesc = "Unable to execute SQL [" + sql + "].";
+ HadoopException hdpException = new HadoopException(msgDesc,
+ sqle);
+ hdpException.generateResponseDataMap(false, getMessage(sqle),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ } finally {
+ close(rs) ;
+ close(stat) ;
+ }
+
+ }
+ return ret ;
+ }
+
+
+ public void close() {
+ Subject.doAs(getLoginSubject(), new PrivilegedAction<Void>(){
+ public Void run() {
+ close(con) ;
+ return null;
+ }
+ });
+ }
+
+ private void close(Statement aStat) {
+ try {
+ if (aStat != null) {
+ aStat.close();
+ }
+ } catch (SQLException e) {
+ LOG.error("Unable to close SQL statement", e);
+ }
+ }
+
+ private void close(ResultSet aResultSet) {
+ try {
+ if (aResultSet != null) {
+ aResultSet.close();
+ }
+ } catch (SQLException e) {
+ LOG.error("Unable to close ResultSet", e);
+ }
+ }
+
+ private void close(Connection aCon) {
+ try {
+ if (aCon != null) {
+ aCon.close();
+ }
+ } catch (SQLException e) {
+ LOG.error("Unable to close SQL Connection", e);
+ }
+ }
+
+ private void initConnection() {
+ initConnection(null,null) ;
+ }
+
+
+ private void initConnection(String userName, String password) {
+
+ Properties prop = getConfigHolder().getRangerSection() ;
+ String driverClassName = prop.getProperty("jdbc.driverClassName") ;
+ String url = prop.getProperty("jdbc.url") ;
+ String errMsg = " You can still save the repository and start creating "
+ + "policies, but you would not be able to use autocomplete for "
+ + "resource names. Check xa_portal.log for more info.";
+
+ if (driverClassName != null) {
+ try {
+ Driver driver = (Driver)Class.forName(driverClassName).newInstance() ;
+ DriverManager.registerDriver(driver);
+ } catch (SQLException e) {
+ String msgDesc = "initConnection: Caught SQLException while registering "
+ + "Hive driver, so Unable to connect to Hive Thrift Server instance.";
+ HadoopException hdpException = new HadoopException(msgDesc, e);
+ hdpException.generateResponseDataMap(false, getMessage(e),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ } catch (IllegalAccessException ilae) {
+ String msgDesc = "initConnection: Class or its nullary constructor might not accessible."
+ + "So unable to initiate connection to hive thrift server instance.";
+ HadoopException hdpException = new HadoopException(msgDesc, ilae);
+ hdpException.generateResponseDataMap(false, getMessage(ilae),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ } catch (InstantiationException ie) {
+ String msgDesc = "initConnection: Class may not have its nullary constructor or "
+ + "may be the instantiation fails for some other reason."
+ + "So unable to initiate connection to hive thrift server instance.";
+ HadoopException hdpException = new HadoopException(msgDesc, ie);
+ hdpException.generateResponseDataMap(false, getMessage(ie),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+
+ } catch (ExceptionInInitializerError eie) {
+ String msgDesc = "initConnection: Got ExceptionInInitializerError, "
+ + "The initialization provoked by this method fails."
+ + "So unable to initiate connection to hive thrift server instance.";
+ HadoopException hdpException = new HadoopException(msgDesc, eie);
+ hdpException.generateResponseDataMap(false, getMessage(eie),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ } catch (SecurityException se) {
+ String msgDesc = "initConnection: unable to initiate connection to hive thrift server instance,"
+ + " The caller's class loader is not the same as or an ancestor "
+ + "of the class loader for the current class and invocation of "
+ + "s.checkPackageAccess() denies access to the package of this class.";
+ HadoopException hdpException = new HadoopException(msgDesc, se);
+ hdpException.generateResponseDataMap(false, getMessage(se),
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ } catch (Throwable t) {
+ String msgDesc = "initConnection: Unable to connect to Hive Thrift Server instance, "
+ + "please provide valid value of field : {jdbc.driverClassName}.";
+ HadoopException hdpException = new HadoopException(msgDesc, t);
+ hdpException.generateResponseDataMap(false, getMessage(t),
+ msgDesc + errMsg, null, "jdbc.driverClassName");
+ throw hdpException;
+ }
+ }
+
+ try {
+
+ if (userName == null && password == null) {
+ con = DriverManager.getConnection(url) ;
+ }
+ else {
+ con = DriverManager.getConnection(url, userName, password) ;
+ }
+
+ } catch (SQLException e) {
+ String msgDesc = "Unable to connect to Hive Thrift Server instance.";
+ HadoopException hdpException = new HadoopException(msgDesc, e);
+ hdpException.generateResponseDataMap(false, getMessage(e), msgDesc
+ + errMsg, null, null);
+ throw hdpException;
+ } catch (SecurityException se) {
+ String msgDesc = "Unable to connect to Hive Thrift Server instance.";
+ HadoopException hdpException = new HadoopException(msgDesc, se);
+ hdpException.generateResponseDataMap(false, getMessage(se), msgDesc
+ + errMsg, null, null);
+ throw hdpException;
+ }
+ }
+
+
+ public static void main(String[] args) {
+
+ HiveClient hc = null ;
+
+ if (args.length == 0) {
+ System.err.println("USAGE: java " + HiveClient.class.getName() + " dataSourceName <databaseName> <tableName> <columnName>") ;
+ System.exit(1) ;
+ }
+
+ try {
+ hc = new HiveClient(args[0]) ;
+
+ if (args.length == 2) {
+ List<String> dbList = hc.getDatabaseList(args[1]) ;
+ if (dbList.size() == 0) {
+ System.out.println("No database found with db filter [" + args[1] + "]") ;
+ }
+ else {
+ for (String str : dbList ) {
+ System.out.println("database: " + str ) ;
+ }
+ }
+ }
+ else if (args.length == 3) {
+ List<String> tableList = hc.getTableList(args[1], args[2]) ;
+ if (tableList.size() == 0) {
+ System.out.println("No tables found under database[" + args[1] + "] with table filter [" + args[2] + "]") ;
+ }
+ else {
+ for(String str : tableList) {
+ System.out.println("Table: " + str) ;
+ }
+ }
+ }
+ else if (args.length == 4) {
+ List<String> columnList = hc.getColumnList(args[1], args[2], args[3]) ;
+ if (columnList.size() == 0) {
+ System.out.println("No columns found for db:" + args[1] + ", table: [" + args[2] + "], with column filter [" + args[3] + "]") ;
+ }
+ else {
+ for (String str : columnList ) {
+ System.out.println("Column: " + str) ;
+ }
+ }
+ }
+
+ }
+ finally {
+ if (hc != null) {
+ hc.close();
+ }
+ }
+ }
+
+ public static HashMap<String, Object> testConnection(String dataSource,
+ HashMap<String, String> connectionProperties) {
+
+ HashMap<String, Object> responseData = new HashMap<String, Object>();
+ boolean connectivityStatus = false;
+ String errMsg = " You can still save the repository and start creating "
+ + "policies, but you would not be able to use autocomplete for "
+ + "resource names. Check xa_portal.log for more info.";
+
+ HiveClient connectionObj = new HiveClient(dataSource,
+ connectionProperties);
+ if (connectionObj != null) {
+
+ List<String> testResult = connectionObj.getDatabaseList("*");
+ if (testResult != null && testResult.size() != 0) {
+ connectivityStatus = true;
+ }
+ }
+ if (connectivityStatus) {
+ String successMsg = "TestConnection Successful";
+ generateResponseDataMap(connectivityStatus, successMsg, successMsg,
+ null, null, responseData);
+ } else {
+ String failureMsg = "Unable to retrieve any databases using given parameters.";
+ generateResponseDataMap(connectivityStatus, failureMsg, failureMsg + errMsg,
+ null, null, responseData);
+ }
+
+ connectionObj.close();
+ return responseData;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/org/apache/ranger/hive/client/HiveClientTester.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/org/apache/ranger/hive/client/HiveClientTester.java b/lookup-client/src/main/java/org/apache/ranger/hive/client/HiveClientTester.java
new file mode 100644
index 0000000..0128622
--- /dev/null
+++ b/lookup-client/src/main/java/org/apache/ranger/hive/client/HiveClientTester.java
@@ -0,0 +1,97 @@
+/*
+ * 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.hive.client;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Properties;
+
+public class HiveClientTester {
+
+ public static void main(String[] args) throws Throwable {
+
+ HiveClient hc = null ;
+
+ if (args.length <= 2) {
+ System.err.println("USAGE: java " + HiveClientTester.class.getName() + " dataSourceName propertyFile <databaseName> <tableName> <columnName>") ;
+ System.exit(1) ;
+ }
+
+
+ try {
+
+ Properties conf = new Properties() ;
+ conf.load(HiveClientTester.class.getClassLoader().getResourceAsStream(args[1]));
+
+ HashMap<String,String> prop = new HashMap<String,String>() ;
+ for(Object key : conf.keySet()) {
+ Object val = conf.get(key) ;
+ prop.put((String)key, (String)val) ;
+ }
+
+
+ hc = new HiveClient(args[0], prop) ;
+
+
+ if (args.length == 3) {
+ List<String> dbList = hc.getDatabaseList(args[2]) ;
+ if (dbList.size() == 0) {
+ System.out.println("No database found with db filter [" + args[2] + "]") ;
+ }
+ else {
+ for (String str : dbList ) {
+ System.out.println("database: " + str ) ;
+ }
+ }
+ }
+ else if (args.length == 4) {
+ List<String> tableList = hc.getTableList(args[2], args[3]) ;
+ if (tableList.size() == 0) {
+ System.out.println("No tables found under database[" + args[2] + "] with table filter [" + args[3] + "]") ;
+ }
+ else {
+ for(String str : tableList) {
+ System.out.println("Table: " + str) ;
+ }
+ }
+ }
+ else if (args.length == 5) {
+ List<String> columnList = hc.getColumnList(args[2], args[3], args[4]) ;
+ if (columnList.size() == 0) {
+ System.out.println("No columns found for db:" + args[2] + ", table: [" + args[3] + "], with column filter [" + args[4] + "]") ;
+ }
+ else {
+ for (String str : columnList ) {
+ System.out.println("Column: " + str) ;
+ }
+ }
+ }
+
+ }
+ finally {
+ if (hc != null) {
+ hc.close();
+ }
+ }
+
+ }
+
+
+}
[26/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/biz/AssetMgrBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/biz/AssetMgrBase.java b/security-admin/src/main/java/com/xasecure/biz/AssetMgrBase.java
deleted file mode 100644
index a5953be..0000000
--- a/security-admin/src/main/java/com/xasecure/biz/AssetMgrBase.java
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * 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 com.xasecure.biz;
-
-import com.xasecure.common.*;
-import com.xasecure.service.*;
-import com.xasecure.view.*;
-import org.springframework.beans.factory.annotation.Autowired;
-public class AssetMgrBase {
-
- @Autowired
- RESTErrorUtil restErrorUtil;
-
- @Autowired
- XAssetService xAssetService;
-
- @Autowired
- XResourceService xResourceService;
-
- @Autowired
- XCredentialStoreService xCredentialStoreService;
-
- @Autowired
- XPolicyExportAuditService xPolicyExportAuditService;
- public VXAsset getXAsset(Long id){
- return (VXAsset)xAssetService.readResource(id);
- }
-
- public VXAsset createXAsset(VXAsset vXAsset){
- vXAsset = (VXAsset)xAssetService.createResource(vXAsset);
- return vXAsset;
- }
-
- public VXAsset updateXAsset(VXAsset vXAsset) {
- vXAsset = (VXAsset)xAssetService.updateResource(vXAsset);
- return vXAsset;
- }
-
- public void deleteXAsset(Long id, boolean force) {
- if (force) {
- xAssetService.deleteResource(id);
- } else {
- throw restErrorUtil.createRESTException(
- "serverMsg.modelMgrBaseDeleteModel",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
- }
-
- public VXAssetList searchXAssets(SearchCriteria searchCriteria) {
- return xAssetService.searchXAssets(searchCriteria);
- }
-
- public VXLong getXAssetSearchCount(SearchCriteria searchCriteria) {
- return xAssetService.getSearchCount(searchCriteria,
- xAssetService.searchFields);
- }
-
- public VXResource getXResource(Long id){
- return (VXResource)xResourceService.readResource(id);
- }
-
- public VXResource createXResource(VXResource vXResource){
- vXResource = (VXResource)xResourceService.createResource(vXResource);
- return vXResource;
- }
-
- public VXResource updateXResource(VXResource vXResource) {
- vXResource = (VXResource)xResourceService.updateResource(vXResource);
- return vXResource;
- }
-
- public void deleteXResource(Long id, boolean force) {
- if (force) {
- xResourceService.deleteResource(id);
- } else {
- throw restErrorUtil.createRESTException(
- "serverMsg.modelMgrBaseDeleteModel",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
- }
-
- public VXResourceList searchXResources(SearchCriteria searchCriteria) {
- return xResourceService.searchXResources(searchCriteria);
- }
-
- public VXLong getXResourceSearchCount(SearchCriteria searchCriteria) {
- return xResourceService.getSearchCount(searchCriteria,
- xResourceService.searchFields);
- }
-
- public VXCredentialStore getXCredentialStore(Long id){
- return (VXCredentialStore)xCredentialStoreService.readResource(id);
- }
-
- public VXCredentialStore createXCredentialStore(VXCredentialStore vXCredentialStore){
- vXCredentialStore = (VXCredentialStore)xCredentialStoreService.createResource(vXCredentialStore);
- return vXCredentialStore;
- }
-
- public VXCredentialStore updateXCredentialStore(VXCredentialStore vXCredentialStore) {
- vXCredentialStore = (VXCredentialStore)xCredentialStoreService.updateResource(vXCredentialStore);
- return vXCredentialStore;
- }
-
- public void deleteXCredentialStore(Long id, boolean force) {
- if (force) {
- xCredentialStoreService.deleteResource(id);
- } else {
- throw restErrorUtil.createRESTException(
- "serverMsg.modelMgrBaseDeleteModel",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
- }
-
- public VXCredentialStoreList searchXCredentialStores(SearchCriteria searchCriteria) {
- return xCredentialStoreService.searchXCredentialStores(searchCriteria);
- }
-
- public VXLong getXCredentialStoreSearchCount(SearchCriteria searchCriteria) {
- return xCredentialStoreService.getSearchCount(searchCriteria,
- xCredentialStoreService.searchFields);
- }
-
- public VXPolicyExportAudit getXPolicyExportAudit(Long id){
- return (VXPolicyExportAudit)xPolicyExportAuditService.readResource(id);
- }
-
- public VXPolicyExportAudit createXPolicyExportAudit(VXPolicyExportAudit vXPolicyExportAudit){
- vXPolicyExportAudit = (VXPolicyExportAudit)xPolicyExportAuditService.createResource(vXPolicyExportAudit);
- return vXPolicyExportAudit;
- }
-
- public VXPolicyExportAudit updateXPolicyExportAudit(VXPolicyExportAudit vXPolicyExportAudit) {
- vXPolicyExportAudit = (VXPolicyExportAudit)xPolicyExportAuditService.updateResource(vXPolicyExportAudit);
- return vXPolicyExportAudit;
- }
-
- public void deleteXPolicyExportAudit(Long id, boolean force) {
- if (force) {
- xPolicyExportAuditService.deleteResource(id);
- } else {
- throw restErrorUtil.createRESTException(
- "serverMsg.modelMgrBaseDeleteModel",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
- }
-
- public VXPolicyExportAuditList searchXPolicyExportAudits(SearchCriteria searchCriteria) {
- return xPolicyExportAuditService.searchXPolicyExportAudits(searchCriteria);
- }
-
- public VXLong getXPolicyExportAuditSearchCount(SearchCriteria searchCriteria) {
- return xPolicyExportAuditService.getSearchCount(searchCriteria,
- xPolicyExportAuditService.searchFields);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/biz/BaseMgr.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/biz/BaseMgr.java b/security-admin/src/main/java/com/xasecure/biz/BaseMgr.java
deleted file mode 100644
index 53bb733..0000000
--- a/security-admin/src/main/java/com/xasecure/biz/BaseMgr.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * 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 com.xasecure.biz;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import com.xasecure.common.XAConstants;
-import com.xasecure.common.MessageEnums;
-import com.xasecure.common.RESTErrorUtil;
-import com.xasecure.common.db.BaseDao;
-import com.xasecure.db.XADaoManager;
-import com.xasecure.entity.XXDBBase;
-
-@Component
-public abstract class BaseMgr {
- static final Logger logger = Logger.getLogger(BaseMgr.class);
-
- @Autowired
- XADaoManager daoManager;
-
- @Autowired
- RESTErrorUtil restErrorUtil;
-
- public XADaoManager getDaoManager() {
- return daoManager;
- }
-
- public void deleteEntity(BaseDao<? extends XXDBBase> baseDao, Long id,
- String entityName) {
- XXDBBase entity = baseDao.getById(id);
- if (entity != null) {
- try {
- baseDao.remove(id);
- } catch (Exception e) {
- logger.error("Error deleting " + entityName + ". Id=" + id, e);
- throw restErrorUtil.createRESTException("This " + entityName
- + " can't be deleted",
- MessageEnums.OPER_NOT_ALLOWED_FOR_STATE, id, null, ""
- + id + ", error=" + e.getMessage());
- }
- } else {
- // Return without error
- logger.info("Delete ignored for non-existent " + entityName
- + " id=" + id);
- }
- }
-
- /**
- * @param objectClassType
- */
- protected void validateClassType(int objectClassType) {
- // objectClassType
- restErrorUtil.validateMinMax(objectClassType, 1,
- XAConstants.ClassTypes_MAX, "Invalid classType", null,
- "objectClassType");
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/biz/HadoopFSMgr.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/biz/HadoopFSMgr.java b/security-admin/src/main/java/com/xasecure/biz/HadoopFSMgr.java
deleted file mode 100644
index e77a4f1..0000000
--- a/security-admin/src/main/java/com/xasecure/biz/HadoopFSMgr.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * 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 com.xasecure.biz;
-
-import org.apache.log4j.Logger;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Component;
-
-import com.xasecure.hadoop.client.HadoopFS;
-
-/**
- *
- *
- */
-
-@Component
-@Scope("singleton")
-public class HadoopFSMgr {
-
- private HadoopFS fs;
- private String dataSource;
- private static Logger logger = Logger.getLogger(HadoopFSMgr.class);
-
- public HadoopFSMgr() {
- init();
- }
-
- public HadoopFSMgr(String dataSource) {
- this.dataSource = dataSource;
- init();
- }
-
- private void init() {
- try {
-// if (dataSource != null) {
-// fs = new HadoopFS(dataSource);
-// } else {
-// fs = new HadoopFS("hadoopdev");
-// }
- } catch (Exception e) {
- logger.error("Error connecting hive client", e);
- }
- }
-
- protected HadoopFS getInstance(String dataSourceName) {
- if (dataSourceName == null) {
- logger.info("Hadoop client name not provided.");
- return fs;
- } else {
- if (fs.getDataSource() != null) {
- if (fs.getDataSource().equalsIgnoreCase(dataSourceName)) {
- return fs;
- } else {
- fs = new HadoopFS(dataSourceName);
- return fs;
- }
- } else {
- fs = new HadoopFS(dataSourceName);
- return fs;
- }
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/biz/HiveFSMgr.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/biz/HiveFSMgr.java b/security-admin/src/main/java/com/xasecure/biz/HiveFSMgr.java
deleted file mode 100644
index e0cbcf1..0000000
--- a/security-admin/src/main/java/com/xasecure/biz/HiveFSMgr.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * 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 com.xasecure.biz;
-
-import org.apache.log4j.Logger;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Component;
-import com.xasecure.hive.client.HiveClient;
-
-/**
- *
- */
-
-// @Component
-// @Scope("singleton")
-
-public class HiveFSMgr {
-
- private HiveClient fs;
- private String dataSource;
- private static Logger logger = Logger.getLogger(HiveFSMgr.class);
-
- public HiveFSMgr() {
- init();
- }
-
- public HiveFSMgr(String dataSource) {
- this.dataSource = dataSource;
- init();
- }
-
- private void init() {
- try {
- if (dataSource != null) {
- fs = new HiveClient(dataSource);
- } else {
- fs = new HiveClient("dev-hive");
- }
- } catch (Exception e) {
- logger.error("Error connecting hive client", e);
- }
- }
-
- protected HiveClient getInstance(String dataSourceName) {
- if (dataSourceName == null) {
- logger.info("Hive client name not provided.");
- return fs;
- } else {
- if (fs.getDataSource() != null) {
- if (fs.getDataSource().equalsIgnoreCase(dataSourceName)) {
- return fs;
- } else {
- fs = new HiveClient(dataSourceName);
- return fs;
- }
- } else {
- fs = new HiveClient(dataSourceName);
- return fs;
- }
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/biz/SessionMgr.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/biz/SessionMgr.java b/security-admin/src/main/java/com/xasecure/biz/SessionMgr.java
deleted file mode 100644
index ee6e29b..0000000
--- a/security-admin/src/main/java/com/xasecure/biz/SessionMgr.java
+++ /dev/null
@@ -1,342 +0,0 @@
-/*
- * 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 com.xasecure.biz;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-
-import com.xasecure.common.XACommonEnums;
-import com.xasecure.common.XAConstants;
-import com.xasecure.common.DateUtil;
-import com.xasecure.common.HTTPUtil;
-import com.xasecure.common.MessageEnums;
-import com.xasecure.common.RESTErrorUtil;
-import com.xasecure.common.SearchCriteria;
-import com.xasecure.common.StringUtil;
-import com.xasecure.common.UserSessionBase;
-import com.xasecure.db.XADaoManager;
-import com.xasecure.entity.XXAuthSession;
-import com.xasecure.entity.XXPortalUser;
-import com.xasecure.entity.XXPortalUserRole;
-import com.xasecure.service.AuthSessionService;
-import com.xasecure.util.RestUtil;
-import com.xasecure.view.VXAuthSession;
-import com.xasecure.view.VXAuthSessionList;
-import com.xasecure.view.VXLong;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.context.SecurityContextHolder;
-import org.springframework.security.web.authentication.WebAuthenticationDetails;
-import org.springframework.stereotype.Component;
-import org.springframework.transaction.annotation.Propagation;
-import org.springframework.transaction.annotation.Transactional;
-
-import com.xasecure.security.context.XAContextHolder;
-import com.xasecure.security.context.XASecurityContext;
-
-@Component
-@Transactional
-public class SessionMgr {
-
- static final Logger logger = Logger.getLogger(SessionMgr.class);
-
- @Autowired
- RESTErrorUtil restErrorUtil;
-
- @Autowired
- XADaoManager daoManager;
-
- @Autowired
- AuthSessionService authSessionService;
-
- @Autowired
- HTTPUtil httpUtil;
-
- @Autowired
- StringUtil stringUtil;
-
- public SessionMgr() {
- logger.debug("SessionManager created");
- }
-
- public UserSessionBase processSuccessLogin(int authType, String userAgent) {
- return processSuccessLogin(authType, userAgent, null);
- }
-
- public UserSessionBase processSuccessLogin(int authType, String userAgent,
- HttpServletRequest httpRequest) {
- boolean newSessionCreation = true;
- UserSessionBase userSession = null;
-
- XASecurityContext context = XAContextHolder.getSecurityContext();
- if (context != null) {
- userSession = context.getUserSession();
- }
-
- Authentication authentication = SecurityContextHolder.getContext()
- .getAuthentication();
- WebAuthenticationDetails details = (WebAuthenticationDetails) authentication
- .getDetails();
-
- String currentLoginId = authentication.getName();
- if (userSession != null) {
- if (validateUserSession(userSession, currentLoginId)) {
- newSessionCreation = false;
- }
- }
-
- if (newSessionCreation) {
- // Need to build the UserSession
- XXPortalUser gjUser = daoManager.getXXPortalUser().findByLoginId(currentLoginId);
- if (gjUser == null) {
- logger.error(
- "Error getting user for loginId=" + currentLoginId,
- new Exception());
- return null;
- }
-
- XXAuthSession gjAuthSession = new XXAuthSession();
- gjAuthSession.setLoginId(currentLoginId);
- gjAuthSession.setUserId(gjUser.getId());
- gjAuthSession.setAuthTime(DateUtil.getUTCDate());
- gjAuthSession.setAuthStatus(XXAuthSession.AUTH_STATUS_SUCCESS);
- gjAuthSession.setAuthType(authType);
- if (details != null) {
- gjAuthSession.setExtSessionId(details.getSessionId());
- gjAuthSession.setRequestIP(details.getRemoteAddress());
- }
-
- if (userAgent != null) {
- gjAuthSession.setRequestUserAgent(userAgent);
- }
- gjAuthSession.setDeviceType(httpUtil.getDeviceType(userAgent));
- gjAuthSession = storeAuthSession(gjAuthSession);
-
- userSession = new UserSessionBase();
- userSession.setXXPortalUser(gjUser);
- userSession.setXXAuthSession(gjAuthSession);
- resetUserSessionForProfiles(userSession);
-
- if (details != null) {
- logger.info("Login Success: loginId=" + currentLoginId
- + ", sessionId=" + gjAuthSession.getId()
- + ", sessionId=" + details.getSessionId()
- + ", requestId=" + details.getRemoteAddress());
- } else {
- logger.info("Login Success: loginId=" + currentLoginId
- + ", sessionId=" + gjAuthSession.getId()
- + ", details is null");
- }
-
- }
-
- return userSession;
- }
-
- public void resetUserSessionForProfiles(UserSessionBase userSession) {
- if (userSession == null) {
- // Nothing to reset
- return;
- }
-
- // Let's get the Current User Again
- String currentLoginId = userSession.getLoginId();
-
- XXPortalUser gjUser = daoManager.getXXPortalUser().findByLoginId(currentLoginId);
- userSession.setXXPortalUser(gjUser);
-
- setUserRoles(userSession);
-
- }
-
- private void setUserRoles(UserSessionBase userSession) {
-
- List<String> strRoleList = new ArrayList<String>();
- List<XXPortalUserRole> roleList = daoManager.getXXPortalUserRole().findByUserId(
- userSession.getUserId());
- for (XXPortalUserRole gjUserRole : roleList) {
- String userRole = gjUserRole.getUserRole();
-
- strRoleList.add(userRole);
- if (userRole.equals(XAConstants.ROLE_SYS_ADMIN)) {
- userSession.setUserAdmin(true);
- }
- }
- userSession.setUserRoleList(strRoleList);
- }
-
- public XXAuthSession processFailureLogin(int authStatus, int authType,
- String loginId, String remoteAddr, String sessionId) {
- XXAuthSession gjAuthSession = new XXAuthSession();
- gjAuthSession.setLoginId(loginId);
- gjAuthSession.setUserId(null);
- gjAuthSession.setAuthTime(DateUtil.getUTCDate());
- gjAuthSession.setAuthStatus(authStatus);
- gjAuthSession.setAuthType(authType);
- gjAuthSession.setDeviceType(XACommonEnums.DEVICE_UNKNOWN);
- gjAuthSession.setExtSessionId(sessionId);
- gjAuthSession.setRequestIP(remoteAddr);
- gjAuthSession.setRequestUserAgent(null);
-
- gjAuthSession = storeAuthSession(gjAuthSession);
- return gjAuthSession;
- }
-
- protected boolean validateUserSession(UserSessionBase userSession,
- String currentLoginId) {
- if (currentLoginId
- .equalsIgnoreCase(userSession.getXXPortalUser().getLoginId())) {
- return true;
- } else {
- logger.info(
- "loginId doesn't match loginId from HTTPSession. Will create new session. loginId="
- + currentLoginId + ", userSession=" + userSession,
- new Exception());
- return false;
- }
- }
-
- @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
- protected XXAuthSession storeAuthSession(XXAuthSession gjAuthSession) {
- // daoManager.getEntityManager().getTransaction().begin();
- XXAuthSession dbMAuthSession = daoManager.getXXAuthSession().create(
- gjAuthSession);
- // daoManager.getEntityManager().getTransaction().commit();
- return dbMAuthSession;
- }
-
- // non-WEB processing
- public UserSessionBase processStandaloneSuccessLogin(int authType,
- String ipAddress) {
- Authentication authentication = SecurityContextHolder.getContext()
- .getAuthentication();
-
- String currentLoginId = authentication.getName();
-
- // Need to build the UserSession
- XXPortalUser gjUser = daoManager.getXXPortalUser().findByLoginId(currentLoginId);
- if (gjUser == null) {
- logger.error("Error getting user for loginId=" + currentLoginId,
- new Exception());
- return null;
- }
-
- XXAuthSession gjAuthSession = new XXAuthSession();
- gjAuthSession.setLoginId(currentLoginId);
- gjAuthSession.setUserId(gjUser.getId());
- gjAuthSession.setAuthTime(DateUtil.getUTCDate());
- gjAuthSession.setAuthStatus(XXAuthSession.AUTH_STATUS_SUCCESS);
- gjAuthSession.setAuthType(authType);
- gjAuthSession.setDeviceType(XACommonEnums.DEVICE_UNKNOWN);
- gjAuthSession.setExtSessionId(null);
- gjAuthSession.setRequestIP(ipAddress);
- gjAuthSession.setRequestUserAgent(null);
-
- gjAuthSession = storeAuthSession(gjAuthSession);
-
- UserSessionBase userSession = new UserSessionBase();
- userSession.setXXPortalUser(gjUser);
- userSession.setXXAuthSession(gjAuthSession);
-
- // create context with user-session and set in thread-local
- XASecurityContext context = new XASecurityContext();
- context.setUserSession(userSession);
- XAContextHolder.setSecurityContext(context);
-
- resetUserSessionForProfiles(userSession);
-
- return userSession;
- }
-
- /**
- * @param searchCriteria
- * @return
- */
- public VXAuthSessionList searchAuthSessions(SearchCriteria searchCriteria) {
-
- if (searchCriteria != null && searchCriteria.getParamList() != null
- && searchCriteria.getParamList().size() > 0) {
-
- int clientTimeOffsetInMinute=RestUtil.getClientTimeOffset();
- java.util.Date temp = null;
- DateUtil dateUtil = new DateUtil();
- if (searchCriteria.getParamList().containsKey("startDate")) {
- temp = (java.util.Date) searchCriteria.getParamList().get(
- "startDate");
- temp = dateUtil.getDateFromGivenDate(temp, 0, 0, 0, 0);
- temp = dateUtil.addTimeOffset(temp, clientTimeOffsetInMinute);
- searchCriteria.getParamList().put("startDate", temp);
- }
- if (searchCriteria.getParamList().containsKey("endDate")) {
- temp = (java.util.Date) searchCriteria.getParamList().get(
- "endDate");
- temp = dateUtil.getDateFromGivenDate(temp, 0, 23, 59, 59);
- temp = dateUtil.addTimeOffset(temp, clientTimeOffsetInMinute);
- searchCriteria.getParamList().put("endDate", temp);
- }
- }
-
- return authSessionService.search(searchCriteria);
- }
-
- public VXLong countAuthSessions(SearchCriteria searchCriteria) {
- return authSessionService.getSearchCount(searchCriteria,
- AuthSessionService.AUTH_SESSION_SEARCH_FLDS);
- }
-
- public VXAuthSession getAuthSession(Long id) {
- return authSessionService.readResource(id);
- }
-
- public VXAuthSession getAuthSessionBySessionId(String authSessionId) {
- if(stringUtil.isEmpty(authSessionId)){
- throw restErrorUtil.createRESTException("Please provide the auth session id.",
- MessageEnums.INVALID_INPUT_DATA);
- }
-
- XXAuthSession xXAuthSession = daoManager.getXXAuthSession()
- .getAuthSessionBySessionId(authSessionId);
-
- if(xXAuthSession==null){
- throw restErrorUtil.createRESTException("Please provide a valid "
- + "session id.", MessageEnums.INVALID_INPUT_DATA);
- }
-
- VXAuthSession vXAuthSession = authSessionService.populateViewBean(xXAuthSession);
- return vXAuthSession;
- }
-
- public boolean isValidXAUser(String loginId) {
- XXPortalUser pUser = daoManager.getXXPortalUser().findByLoginId(loginId);
- if (pUser == null) {
- logger.error("Error getting user for loginId=" + loginId);
- return false;
- } else {
- logger.info(loginId+" is a valid user");
- return true;
- }
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/biz/UserMgr.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/biz/UserMgr.java b/security-admin/src/main/java/com/xasecure/biz/UserMgr.java
deleted file mode 100644
index 58b1c8c..0000000
--- a/security-admin/src/main/java/com/xasecure/biz/UserMgr.java
+++ /dev/null
@@ -1,1150 +0,0 @@
-/*
- * 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 com.xasecure.biz;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-
-import javax.persistence.Query;
-
-import com.xasecure.common.AppConstants;
-import com.xasecure.common.XACommonEnums;
-import com.xasecure.common.XAConstants;
-import com.xasecure.common.ContextUtil;
-import com.xasecure.common.GUIDUtil;
-import com.xasecure.common.MessageEnums;
-import com.xasecure.common.RESTErrorUtil;
-import com.xasecure.common.SearchCriteria;
-import com.xasecure.common.SearchUtil;
-import com.xasecure.common.StringUtil;
-import com.xasecure.common.UserSessionBase;
-import com.xasecure.common.DateUtil;
-import com.xasecure.common.XAConfigUtil;
-import com.xasecure.db.XADaoManager;
-import com.xasecure.entity.XXPortalUser;
-import com.xasecure.entity.XXPortalUserRole;
-import com.xasecure.entity.XXTrxLog;
-import com.xasecure.service.XPortalUserService;
-import com.xasecure.view.VXPasswordChange;
-import com.xasecure.view.VXResponse;
-import com.xasecure.view.VXString;
-import com.xasecure.view.VXPortalUser;
-import com.xasecure.view.VXPortalUserList;
-
-import org.apache.log4j.Logger;
-import org.apache.velocity.Template;
-import org.apache.velocity.app.VelocityEngine;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
-import org.springframework.stereotype.Component;
-import org.springframework.transaction.annotation.Propagation;
-import org.springframework.transaction.annotation.Transactional;
-
-@Component
-public class UserMgr {
-
- static final Logger logger = Logger.getLogger(UserMgr.class);
- private static final Md5PasswordEncoder md5Encoder = new Md5PasswordEncoder();
-
- @Autowired
- XADaoManager daoManager;
-
- @Autowired
- RESTErrorUtil restErrorUtil;
-
- @Autowired
- StringUtil stringUtil;
-
- @Autowired
- SearchUtil searchUtil;
-
- @Autowired
- XABizUtil msBizUtil;
-
- @Autowired
- SessionMgr sessionMgr;
-
- @Autowired
- VelocityEngine velocityEngine;
- Template t;
-
- @Autowired
- DateUtil dateUtil;
-
- @Autowired
- XAConfigUtil configUtil;
-
- @Autowired
- XPortalUserService xPortalUserService;
-
- String publicRoles[] = new String[] { XAConstants.ROLE_USER,
- XAConstants.ROLE_OTHER };
-
- private static final List<String> DEFAULT_ROLE_LIST = new ArrayList<String>(
- 1);
-
- private static final List<String> VALID_ROLE_LIST = new ArrayList<String>(2);
-
- static {
- DEFAULT_ROLE_LIST.add(XAConstants.ROLE_USER);
- VALID_ROLE_LIST.add(XAConstants.ROLE_SYS_ADMIN);
- VALID_ROLE_LIST.add(XAConstants.ROLE_USER);
- }
-
- public UserMgr() {
- if (logger.isDebugEnabled()) {
- logger.debug("UserMgr()");
- }
- }
-
- public XXPortalUser createUser(VXPortalUser userProfile, int userStatus,
- Collection<String> userRoleList) {
- XXPortalUser user = mapVXPortalUserToXXPortalUser(userProfile);
- user = createUser(user, userStatus, userRoleList);
-
- return user;
- }
-
- public XXPortalUser createUser(XXPortalUser user, int userStatus,
- Collection<String> userRoleList) {
- user.setStatus(userStatus);
- String saltEncodedpasswd = encrypt(user.getLoginId(),
- user.getPassword());
- user.setPassword(saltEncodedpasswd);
- user = daoManager.getXXPortalUser().create(user);
-
- // Create the UserRole for this user
- List<XXPortalUserRole> gjUserRoleList = new ArrayList<XXPortalUserRole>();
- if (userRoleList != null) {
- for (String userRole : userRoleList) {
- XXPortalUserRole gjUserRole = addUserRole(user.getId(), userRole);
- if (gjUserRole != null) {
- gjUserRoleList.add(gjUserRole);
- }
- }
- }
-
- return user;
- }
-
- public XXPortalUser createUser(VXPortalUser userProfile, int userStatus) {
- ArrayList<String> roleList = new ArrayList<String>();
- Collection<String> reqRoleList = userProfile.getUserRoleList();
- if (reqRoleList != null && reqRoleList.size()>0) {
- for (String role : reqRoleList) {
- roleList.add(role);
- }
- }else{
- roleList.add(XAConstants.ROLE_USER);
- }
-
- return createUser(userProfile, userStatus, roleList);
- }
-
- /**
- * @param userProfile
- * @return
- */
- public XXPortalUser updateUser(VXPortalUser userProfile) {
- XXPortalUser gjUser = daoManager.getXXPortalUser().getById(
- userProfile.getId());
-
- if (gjUser == null) {
- logger.error("updateUser(). User not found. userProfile="
- + userProfile);
- return null;
- }
-
- checkAccess(gjUser);
-
- boolean updateUser = false;
- // Selectively update fields
-
- // status
- if (userProfile.getStatus() != gjUser.getStatus()) {
- updateUser = true;
- }
-
- // Allowing email address update even when its set to empty.
- // emailAddress
- String emailAddress = userProfile.getEmailAddress();
- if (stringUtil.isEmpty(emailAddress)) {
- String randomString = GUIDUtil.genGUI();
- userProfile.setEmailAddress(randomString);
- updateUser = true;
- } else {
- if (stringUtil.validateEmail(emailAddress)) {
- XXPortalUser checkUser = daoManager.getXXPortalUser()
- .findByEmailAddress(emailAddress);
- if (checkUser != null) {
- String loginId = userProfile.getLoginId();
- if (loginId == null) {
- throw restErrorUtil.createRESTException(
- "Invalid user, please provide valid "
- + "username.",
- MessageEnums.INVALID_INPUT_DATA);
- } else if (!loginId.equals(checkUser.getLoginId())) {
- throw restErrorUtil
- .createRESTException(
- "The email address "
- + "you've provided already exists in system.",
- MessageEnums.INVALID_INPUT_DATA);
- } else {
- userProfile.setEmailAddress(emailAddress);
- updateUser = true;
- }
- } else {
- userProfile.setEmailAddress(emailAddress);
- updateUser = true;
- }
- } else {
- throw restErrorUtil.createRESTException(
- "Please provide valid email address.",
- MessageEnums.INVALID_INPUT_DATA);
- }
- }
-
- // loginId
- // if (!stringUtil.isEmpty(userProfile.getLoginId())
- // && !userProfile.getLoginId().equals(gjUser.getLoginId())) {
- // gjUser.setLoginId(userProfile.getLoginId());
- // updateUser = true;
- // }
-
- // firstName
- if (!stringUtil.isEmpty(userProfile.getFirstName())
- && !userProfile.getFirstName().equals(gjUser.getFirstName())) {
- userProfile.setFirstName(stringUtil.toCamelCaseAllWords(userProfile
- .getFirstName()));
- updateUser = true;
- }
-
- // lastName allowed to be empty
- if (userProfile.getLastName() != null
- && !userProfile.getLastName().equals(gjUser.getLastName())) {
- userProfile.setLastName(stringUtil.toCamelCaseAllWords(userProfile
- .getLastName()));
- updateUser = true;
- }
-
- // publicScreenName
- if (!stringUtil.isEmpty(userProfile.getPublicScreenName())
- && !userProfile.getPublicScreenName().equals(
- gjUser.getPublicScreenName())) {
- userProfile.setPublicScreenName(userProfile.getFirstName() + " "
- + userProfile.getLastName());
- updateUser = true;
- }
-
- // notes
- /*if (!stringUtil.isEmpty(userProfile.getNotes())
- && !userProfile.getNotes().equalsIgnoreCase(gjUser.getNotes())) {
- updateUser = true;
- }*/
-
- // userRoleList
- updateRoles(userProfile.getId(), userProfile.getUserRoleList());
-
- if (updateUser) {
-
- List<XXTrxLog> trxLogList = xPortalUserService.getTransactionLog(
- userProfile, gjUser, "update");
-
- userProfile.setPassword(gjUser.getPassword());
- userProfile = xPortalUserService.updateResource(userProfile);
- sessionMgr.resetUserSessionForProfiles(ContextUtil
- .getCurrentUserSession());
-
- msBizUtil.createTrxLog(trxLogList);
- }
-
- return gjUser;
- }
-
- private boolean updateRoles(Long userId, Collection<String> rolesList) {
- boolean rolesUpdated = false;
- if (rolesList == null || rolesList.size() == 0) {
- return false;
- }
-
- // Let's first delete old roles
- List<XXPortalUserRole> gjUserRoles = daoManager.getXXPortalUserRole().findByUserId(
- userId);
-
- for (XXPortalUserRole gjUserRole : gjUserRoles) {
- boolean found = false;
- for (String userRole : rolesList) {
- if (gjUserRole.getUserRole().equalsIgnoreCase(userRole)) {
- found = true;
- break;
- }
- }
- if (!found) {
- if (deleteUserRole(userId, gjUserRole)) {
- rolesUpdated = true;
- }
- }
- }
-
- // Let's add new roles
- for (String userRole : rolesList) {
- boolean found = false;
- for (XXPortalUserRole gjUserRole : gjUserRoles) {
- if (gjUserRole.getUserRole().equalsIgnoreCase(userRole)) {
- found = true;
- break;
- }
- }
- if (!found) {
- if (addUserRole(userId, userRole) != null) {
- rolesUpdated = true;
- }
- }
- }
- return rolesUpdated;
- }
-
- /**
- * @param userId
- * @param vStrings
- */
- public void setUserRoles(Long userId, List<VXString> vStringRolesList) {
- List<String> stringRolesList = new ArrayList<String>();
- for (VXString vXString : vStringRolesList) {
- stringRolesList.add(vXString.getValue());
- }
- updateRoles(userId, stringRolesList);
- }
-
- /**
- * @param pwdChange
- * @return
- */
- public VXResponse changePassword(VXPasswordChange pwdChange) {
- // First let's get the XXPortalUser for the current logged in user
- String currentUserLoginId = ContextUtil.getCurrentUserLoginId();
- XXPortalUser gjUserCurrent = daoManager.getXXPortalUser()
- .findByLoginId(currentUserLoginId);
-
- String encryptedOldPwd = encrypt(gjUserCurrent.getLoginId(),
- pwdChange.getOldPassword());
-
- VXResponse ret = new VXResponse();
-
- if (!stringUtil.equals(encryptedOldPwd, gjUserCurrent.getPassword())) {
- logger.info("changePassword(). Invalid old password. userId="
- + pwdChange.getId());
-
- throw restErrorUtil.createRESTException(
- "serverMsg.userMgrPassword",
- MessageEnums.OPER_NO_PERMISSION, null, null,
- "" + pwdChange.getId());
- }
-
- // Get the user for whom we want to change the password
- XXPortalUser gjUser = daoManager.getXXPortalUser().getById(
- pwdChange.getId());
- if (gjUser == null) {
- logger.warn("SECURITY:changePassword(). User not found. userId="
- + pwdChange.getId());
- throw restErrorUtil.createRESTException(
- "serverMsg.userMgrInvalidUser",
- MessageEnums.DATA_NOT_FOUND, null, null,
- "" + pwdChange.getId());
- }
-
- if (!stringUtil
- .validatePassword(
- pwdChange.getUpdPassword(),
- new String[] { gjUser.getFirstName(),
- gjUser.getLastName(), gjUser.getLoginId(),
- gjUserCurrent.getFirstName(),
- gjUserCurrent.getLastName(),
- gjUserCurrent.getLoginId() })) {
- logger.warn("SECURITY:changePassword(). Invalid new password. userId="
- + pwdChange.getId());
-
- throw restErrorUtil.createRESTException(
- "serverMsg.userMgrNewPassword",
- MessageEnums.INVALID_PASSWORD, null, null,
- "" + pwdChange.getId());
- }
-
- String encryptedNewPwd = encrypt(gjUser.getLoginId(),
- pwdChange.getUpdPassword());
-
- String currentPassword = gjUser.getPassword();
-
- if (!encryptedNewPwd.equals(currentPassword)) {
-
- List<XXTrxLog> trxLogList = new ArrayList<XXTrxLog>();
- XXTrxLog xTrxLog = new XXTrxLog();
-
- xTrxLog.setAttributeName("Password");
- xTrxLog.setPreviousValue(currentPassword);
- xTrxLog.setNewValue(encryptedNewPwd);
- xTrxLog.setAction("password change");
- xTrxLog.setObjectClassType(AppConstants.CLASS_TYPE_PASSWORD_CHANGE);
- xTrxLog.setObjectId(pwdChange.getId());
- xTrxLog.setObjectName(pwdChange.getLoginId());
- trxLogList.add(xTrxLog);
-
- msBizUtil.createTrxLog(trxLogList);
-
- gjUser.setPassword(encryptedNewPwd);
- gjUser = daoManager.getXXPortalUser().update(gjUser);
-
- ret.setMsgDesc("Password successfully updated");
- ret.setStatusCode(VXResponse.STATUS_SUCCESS);
- } else {
- ret.setMsgDesc("Password update failed");
- ret.setStatusCode(VXResponse.STATUS_ERROR);
- throw restErrorUtil.createRESTException(
- "serverMsg.userMgrOldPassword",
- MessageEnums.INVALID_INPUT_DATA, gjUser.getId(),
- "password", gjUser.toString());
- }
- return ret;
- }
-
- /**
- * @param gjUser
- * @param changeEmail
- * @return
- */
- public VXPortalUser changeEmailAddress(XXPortalUser gjUser,
- VXPasswordChange changeEmail) {
-
- if (gjUser.getEmailAddress() != null) {
- throw restErrorUtil.createRESTException(
- "serverMsg.userMgrEmailChange",
- MessageEnums.OPER_NO_PERMISSION, null, null, ""
- + changeEmail);
- }
-
- String encryptedOldPwd = encrypt(gjUser.getLoginId(),
- changeEmail.getOldPassword());
-
- if (!stringUtil.validateEmail(changeEmail.getEmailAddress())) {
- logger.info("Invalid email address." + changeEmail);
- throw restErrorUtil.createRESTException(
- "serverMsg.userMgrInvalidEmail",
- MessageEnums.INVALID_INPUT_DATA, changeEmail.getId(),
- "emailAddress", changeEmail.toString());
-
- }
-
- if (!stringUtil.equals(encryptedOldPwd, gjUser.getPassword())) {
- logger.info("changeEmailAddress(). Invalid password. changeEmail="
- + changeEmail);
-
- throw restErrorUtil.createRESTException(
- "serverMsg.userMgrWrongPassword",
- MessageEnums.OPER_NO_PERMISSION, null, null, ""
- + changeEmail);
- }
-
- // Normalize email. Make it lower case
- gjUser.setEmailAddress(stringUtil.normalizeEmail(changeEmail
- .getEmailAddress()));
-
- // loginId
- gjUser.setLoginId(gjUser.getEmailAddress());
-
- String saltEncodedpasswd = encrypt(gjUser.getLoginId(),
- changeEmail.getOldPassword());
-
- gjUser.setPassword(saltEncodedpasswd);
-
- daoManager.getXXPortalUser().update(gjUser);
- return mapXXPortalUserVXPortalUser(gjUser);
- }
-
- /**
- * @param userId
- */
- public VXPortalUser deactivateUser(XXPortalUser gjUser) {
- if (gjUser != null
- && gjUser.getStatus() != XAConstants.ACT_STATUS_DEACTIVATED) {
- logger.info("Marking user " + gjUser.getLoginId() + " as deleted");
- gjUser.setStatus(XAConstants.ACT_STATUS_DEACTIVATED);
- gjUser = daoManager.getXXPortalUser().update(gjUser);
- return mapXXPortalUserVXPortalUser(gjUser);
- }
- return null;
- }
-
- public VXPortalUser getUserProfile(Long id) {
- XXPortalUser user = daoManager.getXXPortalUser().getById(id);
- if (user != null) {
- checkAccessForRead(user);
- return mapXXPortalUserVXPortalUser(user);
- } else {
- if (logger.isDebugEnabled()) {
- logger.debug("User not found. userId=" + id);
- }
- return null;
- }
- }
-
- public VXPortalUser getUserProfileByLoginId() {
- String loginId = ContextUtil.getCurrentUserLoginId();
- return getUserProfileByLoginId(loginId);
- }
-
- public VXPortalUser getUserProfileByLoginId(String loginId) {
- XXPortalUser user = daoManager.getXXPortalUser().findByLoginId(loginId);
- if (user != null) {
- return mapXXPortalUserVXPortalUser(user);
- } else {
- if (logger.isDebugEnabled()) {
- logger.debug("User not found. loginId=" + loginId);
- }
- return null;
- }
- }
-
- public XXPortalUser mapVXPortalUserToXXPortalUser(VXPortalUser userProfile) {
- XXPortalUser gjUser = new XXPortalUser();
- gjUser.setEmailAddress(userProfile.getEmailAddress());
- gjUser.setFirstName(userProfile.getFirstName());
- gjUser.setLastName(userProfile.getLastName());
- gjUser.setLoginId(userProfile.getLoginId());
- gjUser.setPassword(userProfile.getPassword());
- gjUser.setUserSource(userProfile.getUserSource());
- gjUser.setPublicScreenName(userProfile.getPublicScreenName());
- return gjUser;
- }
-
- /**
- * @param user
- * @return
- */
- public VXPortalUser mapXXPortalUserToVXPortalUser(XXPortalUser user,
- Collection<String> userRoleList) {
- if (user == null) {
- return null;
- }
- UserSessionBase sess = ContextUtil.getCurrentUserSession();
- if (sess == null) {
- return null;
- }
-
- VXPortalUser userProfile = new VXPortalUser();
- gjUserToUserProfile(user, userProfile);
- if (sess.isUserAdmin() || sess.getXXPortalUser().getId().equals(user.getId())) {
- if (userRoleList == null) {
- userRoleList = new ArrayList<String>();
- List<XXPortalUserRole> gjUserRoleList = daoManager.getXXPortalUserRole()
- .findByParentId(user.getId());
-
- for (XXPortalUserRole userRole : gjUserRoleList) {
- userRoleList.add(userRole.getUserRole());
- }
- }
-
- userProfile.setUserRoleList(userRoleList);
- }
- userProfile.setUserSource(user.getUserSource());
- return userProfile;
- }
-
- private void gjUserToUserProfile(XXPortalUser user, VXPortalUser userProfile) {
- UserSessionBase sess = ContextUtil.getCurrentUserSession();
- if (sess == null) {
- return;
- }
-
- // Is accessed by peer from the same account
- boolean isPeer = false;
- boolean isAccountAdmin = false;
-
- // Admin
- if (sess.isUserAdmin() || sess.getXXPortalUser().getId().equals(user.getId())) {
- userProfile.setLoginId(user.getLoginId());
- userProfile.setStatus(user.getStatus());
- userProfile.setUserRoleList(new ArrayList<String>());
- String emailAddress = user.getEmailAddress();
-
- if (emailAddress != null && stringUtil.validateEmail(emailAddress)) {
- userProfile.setEmailAddress(user.getEmailAddress());
- }
-
- if (sess != null) {
- userProfile.setUserSource(sess.getAuthProvider());
- }
-
- List<XXPortalUserRole> gjUserRoleList = daoManager.getXXPortalUserRole()
- .findByParentId(user.getId());
-
- for (XXPortalUserRole gjUserRole : gjUserRoleList) {
- userProfile.getUserRoleList().add(gjUserRole.getUserRole());
- }
- }
-
- if (sess.isUserAdmin() || sess.getXXPortalUser().getId().equals(user.getId())
- || isPeer) {
- userProfile.setId(user.getId());
- userProfile.setFirstName(user.getFirstName());
- userProfile.setLastName(user.getLastName());
- userProfile.setPublicScreenName(user.getPublicScreenName());
- if (isAccountAdmin) {
- userProfile.setEmailAddress(user.getEmailAddress());
- }
- }
-
- }
-
- /**
- * Translates XXPortalUser to VUserProfile. This method should be called in the
- * same transaction in which the XXPortalUser was retrieved from the database
- *
- * @param user
- * @return
- */
- public VXPortalUser mapXXPortalUserVXPortalUser(XXPortalUser user) {
- return mapXXPortalUserToVXPortalUser(user, null);
- }
-
- /**
- * @param emailId
- * @return
- */
- public XXPortalUser findByEmailAddress(String emailId) {
- return daoManager.getXXPortalUser().findByEmailAddress(emailId);
- }
-
- public XXPortalUser findByLoginId(String loginId) {
- return daoManager.getXXPortalUser().findByLoginId(loginId);
- }
-
- @Transactional(readOnly = true, propagation = Propagation.REQUIRED)
- public Collection<String> getRolesForUser(XXPortalUser user) {
- Collection<String> roleList = new ArrayList<String>();
-
- Collection<XXPortalUserRole> roleCollection = daoManager.getXXPortalUserRole()
- .findByUserId(user.getId());
- for (XXPortalUserRole role : roleCollection) {
- roleList.add(role.getUserRole());
- }
- return roleList;
- }
-
- /**
- * @param searchCriteria
- * @return
- */
- public VXPortalUserList searchUsers(SearchCriteria searchCriteria) {
-
- VXPortalUserList returnList = new VXPortalUserList();
- ArrayList<VXPortalUser> objectList = new ArrayList<VXPortalUser>();
- String queryStr = "SELECT u FROM XXPortalUser u ";
- String countQueryStr = "SELECT COUNT(u) FROM XXPortalUser u ";
-
- // Get total count first
- Query query = createUserSearchQuery(countQueryStr, null, searchCriteria);
- Long count = (Long) query.getSingleResult();
- if (count == null || count.longValue() == 0) {
- return returnList;
- }
-
- // Get actual data
-
- // Add sort by
- String sortBy = searchCriteria.getSortBy();
- String querySortBy = "u.loginId";
- if (!stringUtil.isEmpty(sortBy)) {
- sortBy = sortBy.trim();
- if (sortBy.equalsIgnoreCase("userId")) {
- querySortBy = "u.id";
- } else if (sortBy.equalsIgnoreCase("loginId")) {
- querySortBy = "ua.loginId";
- } else if (sortBy.equalsIgnoreCase("emailAddress")) {
- querySortBy = "u.emailAddress";
- } else if (sortBy.equalsIgnoreCase("firstName")) {
- querySortBy = "u.firstName";
- } else if (sortBy.equalsIgnoreCase("lastName")) {
- querySortBy = "u.lastName";
- } else {
- sortBy = "loginId";
- logger.error("Invalid sortBy provided. sortBy=" + sortBy);
- }
- } else {
- sortBy = "loginId";
- }
-
- // Default sort field
- String sortClause = " order by " + querySortBy + " ";
-
- // 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);
- }
- }
- sortClause += querySortType;
-
- query = createUserSearchQuery(queryStr, sortClause, searchCriteria);
-
- // Set start index
- query.setFirstResult(searchCriteria.getStartIndex());
-
- searchUtil.updateQueryPageSize(query, searchCriteria);
-
- @SuppressWarnings("rawtypes")
- List resultList = query.getResultList();
- // Iterate over the result list and create the return list
- for (Object object : resultList) {
- XXPortalUser gjUser = (XXPortalUser) object;
- VXPortalUser userProfile = new VXPortalUser();
- gjUserToUserProfile(gjUser, userProfile);
- objectList.add(userProfile);
- }
-
- returnList.setPageSize(query.getMaxResults());
- returnList.setSortBy(sortBy);
- returnList.setSortType(querySortType);
- returnList.setStartIndex(query.getFirstResult());
- returnList.setTotalCount(count.longValue());
- returnList.setVXPortalUsers(objectList);
- return returnList;
- }
-
- /**
- * @param queryStr
- * @param sortClause
- * @param searchCriteria
- * @return
- */
- private Query createUserSearchQuery(String queryStr, String sortClause,
- SearchCriteria searchCriteria) {
- HashMap<String, Object> paramList = searchCriteria.getParamList();
-
- String whereClause = "WHERE 1 = 1 ";
-
- // roles
- @SuppressWarnings("unchecked")
- List<String> roleList = (List<String>) paramList.get("roleList");
- if (roleList != null && roleList.size() > 0) {
- whereClause = ", XXPortalUserRole ur WHERE u.id = ur.userId";
- if (roleList.size() == 1) {
- // For only one role, let's do an equal to
- whereClause += " and ur.userRole = :role";
- } else {
- whereClause += " and ur.userRole in (:roleList)";
- }
- }
-
- // userId
- Long userId = (Long) paramList.get("userId");
- if (userId != null) {
- whereClause += " and u.id = :userId ";
- }
-
- // loginId
- String loginId = (String) paramList.get("loginId");
- if (loginId != null) {
- whereClause += " and LOWER(u.loginId) = :loginId ";
- }
-
- // emailAddress
- String emailAddress = (String) paramList.get("emailAddress");
- if (emailAddress != null) {
- whereClause += " and LOWER(u.emailAddress) = :emailAddress ";
- }
-
- // firstName
- String firstName = (String) paramList.get("firstName");
- if (firstName != null) {
- whereClause += " and LOWER(u.firstName) = :firstName ";
- }
-
- // lastName
- String lastName = (String) paramList.get("lastName");
- if (lastName != null) {
- whereClause += " and LOWER(u.lastName) = :lastName ";
- }
-
- // status
- Integer status = null;
- @SuppressWarnings("unchecked")
- List<Integer> statusList = (List<Integer>) paramList.get("statusList");
- if (statusList != null && statusList.size() == 1) {
- // use == condition
- whereClause += " and u.status = :status";
- status = statusList.get(0);
- } else if (statusList != null && statusList.size() > 1) {
- // use in operator
- whereClause += " and u.status in (:statusList) ";
- }
-
- // publicScreenName
- String publicScreenName = (String) paramList.get("publicScreenName");
- if (publicScreenName != null) {
- whereClause += " and LOWER(u.publicScreenName) = :publicScreenName ";
- }
-
- // familyScreenName
- String familyScreenName = (String) paramList.get("familyScreenName");
- if (familyScreenName != null) {
- whereClause += " and LOWER(u.familyScreenName) = :familyScreenName ";
- }
-
- if (sortClause != null) {
- whereClause += sortClause;
- }
-
- Query query = daoManager.getEntityManager().createQuery(
- queryStr + whereClause);
-
- if (roleList != null && roleList.size() > 0) {
- if (roleList.size() == 1) {
- query.setParameter("role", roleList.get(0));
- } else {
- query.setParameter("roleList", roleList);
- }
- }
-
- if (status != null) {
- query.setParameter("status", status);
- }
- if (statusList != null && statusList.size() > 1) {
- query.setParameter("statusList", statusList);
- }
- if (emailAddress != null) {
- query.setParameter("emailAddress", emailAddress.toLowerCase());
- }
-
- // userId
- if (userId != null) {
- query.setParameter("userId", userId);
- }
- // firstName
- if (firstName != null) {
- query.setParameter("firstName", firstName.toLowerCase());
- }
- // lastName
- if (lastName != null) {
- query.setParameter("lastName", lastName.toLowerCase());
- }
-
- // loginId
- if (loginId != null) {
- query.setParameter("loginId", loginId.toLowerCase());
- }
-
- // publicScreenName
- if (publicScreenName != null) {
- query.setParameter("publicScreenName",
- publicScreenName.toLowerCase());
- }
-
- // familyScreenName
- if (familyScreenName != null) {
- query.setParameter("familyScreenName",
- familyScreenName.toLowerCase());
- }
-
- return query;
- }
-
- public boolean deleteUserRole(Long userId, String userRole) {
- List<XXPortalUserRole> roleList = daoManager.getXXPortalUserRole().findByUserId(
- userId);
- for (XXPortalUserRole gjUserRole : roleList) {
- if (gjUserRole.getUserRole().equalsIgnoreCase(userRole)) {
- return deleteUserRole(userId, gjUserRole);
- }
- }
- return false;
- }
-
- public boolean deleteUserRole(Long userId, XXPortalUserRole gjUserRole) {
- /*if (XAConstants.ROLE_USER.equals(gjUserRole.getUserRole())) {
- return false;
- }*/
- boolean publicRole = false;
- for (int i = 0; i < publicRoles.length; i++) {
- if (publicRoles[i].equalsIgnoreCase(gjUserRole.getUserRole())) {
- publicRole = true;
- break;
- }
- }
- if (!publicRole) {
- UserSessionBase sess = ContextUtil.getCurrentUserSession();
- if (sess == null || !sess.isUserAdmin()) {
- return false;
- }
- }
-
- daoManager.getXXPortalUserRole().remove(gjUserRole.getId());
- return true;
- }
-
- public XXPortalUserRole addUserRole(Long userId, String userRole) {
- List<XXPortalUserRole> roleList = daoManager.getXXPortalUserRole().findByUserId(
- userId);
- boolean publicRole = false;
- for (int i = 0; i < publicRoles.length; i++) {
- if (publicRoles[i].equalsIgnoreCase(userRole)) {
- publicRole = true;
- break;
- }
- }
- if (!publicRole) {
- UserSessionBase sess = ContextUtil.getCurrentUserSession();
- if (sess == null) {
- return null;
- }
- // Admin
- if (!sess.isUserAdmin()) {
- logger.error(
- "SECURITY WARNING: User trying to add non public role. userId="
- + userId + ", role=" + userRole + ", session="
- + sess.toString(), new Throwable());
- return null;
- }
- }
-
- for (XXPortalUserRole gjUserRole : roleList) {
- if (userRole.equalsIgnoreCase(gjUserRole.getUserRole())) {
- return gjUserRole;
- }
- }
- XXPortalUserRole userRoleObj = new XXPortalUserRole();
- userRoleObj.setUserRole(userRole.toUpperCase());
- userRoleObj.setUserId(userId);
- userRoleObj.setStatus(XAConstants.STATUS_ENABLED);
- daoManager.getXXPortalUserRole().create(userRoleObj);
-
- // If role is not OTHER, then remove OTHER
- if (!XAConstants.ROLE_OTHER.equalsIgnoreCase(userRole)) {
- deleteUserRole(userId, XAConstants.ROLE_OTHER);
- }
-
- sessionMgr.resetUserSessionForProfiles(ContextUtil
- .getCurrentUserSession());
- return null;
- }
-
- public void checkAccess(Long userId) {
- XXPortalUser gjUser = daoManager.getXXPortalUser().getById(userId);
- if (gjUser == null) {
- throw restErrorUtil
- .create403RESTException("serverMsg.userMgrWrongUser"
- + userId);
- }
-
- checkAccess(gjUser);
- }
-
- /**
- * @param gjUser
- * @return
- */
- public void checkAccess(XXPortalUser gjUser) {
- if (gjUser == null) {
- throw restErrorUtil
- .create403RESTException("serverMsg.userMgrWrongUser");
- }
- UserSessionBase sess = ContextUtil.getCurrentUserSession();
- if (sess != null) {
-
- // Admin
- if (sess != null && sess.isUserAdmin()) {
- return;
- }
-
- // Self
- if (sess.getXXPortalUser().getId().equals(gjUser.getId())) {
- return;
- }
-
- }
- throw restErrorUtil.create403RESTException("User "
- + " access denied. loggedInUser="
- + (sess != null ? sess.getXXPortalUser().getId() : "Not Logged In")
- + ", accessing user=" + gjUser.getId());
-
- }
-
- public void checkAccessForRead(XXPortalUser gjUser) {
- if (gjUser == null) {
- throw restErrorUtil
- .create403RESTException("serverMsg.userMgrWrongUser");
- }
- UserSessionBase sess = ContextUtil.getCurrentUserSession();
- if (sess != null) {
-
- // Admin
- if (sess != null && sess.isUserAdmin()) {
- return;
- }
-
- // Self
- if (sess.getXXPortalUser().getId().equals(gjUser.getId())) {
- return;
- }
-
- }
- throw restErrorUtil.create403RESTException("User "
- + " access denied. loggedInUser="
- + (sess != null ? sess.getXXPortalUser().getId() : "Not Logged In")
- + ", accessing user=" + gjUser.getId());
-
- }
-
- public String encrypt(String loginId, String password) {
- String saltEncodedpasswd = md5Encoder.encodePassword(password, loginId);
- return saltEncodedpasswd;
- }
-
- public VXPortalUser createUser(VXPortalUser userProfile) {
- XXPortalUser xXPortalUser = this
- .createUser(userProfile, XACommonEnums.STATUS_ENABLED);
- return mapXXPortalUserVXPortalUser(xXPortalUser);
- }
-
- public VXPortalUser createDefaultAccountUser(VXPortalUser userProfile) {
- if(userProfile.getPassword()==null||userProfile.getPassword().trim().isEmpty()){
- userProfile.setUserSource(XACommonEnums.USER_EXTERNAL);
- }
- // access control
- UserSessionBase session = ContextUtil.getCurrentUserSession();
- if (session != null) {
- if (!session.isUserAdmin()) {
- throw restErrorUtil.create403RESTException("User "
- + "creation denied. LoggedInUser="
- + (session != null ? session.getXXPortalUser().getId()
- : "Not Logged In")
- + " ,isn't permitted to perform the action.");
-
- }
- }
-
- XXPortalUser xXPortalUser = null;
- String loginId = userProfile.getLoginId();
- String emailAddress = userProfile.getEmailAddress();
-
- if (loginId != null && !loginId.isEmpty()) {
- xXPortalUser = this.findByLoginId(loginId);
- if (xXPortalUser == null) {
- if (emailAddress != null && !emailAddress.isEmpty()) {
- xXPortalUser = this.findByEmailAddress(emailAddress);
- if (xXPortalUser == null) {
- xXPortalUser = this.createUser(userProfile,
- XACommonEnums.STATUS_ENABLED);
- } else {
- throw restErrorUtil
- .createRESTException(
- "The email address "
- + emailAddress
- + " you've provided already exists. Please try again with different "
- + "email address.",
- MessageEnums.OPER_NOT_ALLOWED_FOR_STATE);
- }
- } else {
- String randomEmail = GUIDUtil.genGUI();
- userProfile.setEmailAddress(randomEmail);
- xXPortalUser = this.createUser(userProfile,
- XACommonEnums.STATUS_ENABLED);
- }
- } else {
- /*throw restErrorUtil
- .createRESTException(
- "The login id "
- + loginId
- + " you've provided already exists. Please try again with different "
- + "login id.",
- MessageEnums.OPER_NOT_ALLOWED_FOR_STATE);*/
- }
- }
-
- return mapXXPortalUserToVXPortalUserForDefaultAccount(xXPortalUser);
- }
-
- private VXPortalUser mapXXPortalUserToVXPortalUserForDefaultAccount(XXPortalUser user) {
-
- VXPortalUser userProfile = new VXPortalUser();
-
- userProfile.setLoginId(user.getLoginId());
- userProfile.setEmailAddress(user.getEmailAddress());
- userProfile.setStatus(user.getStatus());
- userProfile.setUserRoleList(new ArrayList<String>());
- userProfile.setId(user.getId());
- userProfile.setFirstName(user.getFirstName());
- userProfile.setLastName(user.getLastName());
- userProfile.setPublicScreenName(user.getPublicScreenName());
- userProfile.setEmailAddress(user.getEmailAddress());
-
- List<XXPortalUserRole> gjUserRoleList = daoManager.getXXPortalUserRole()
- .findByParentId(user.getId());
-
- for (XXPortalUserRole gjUserRole : gjUserRoleList) {
- userProfile.getUserRoleList().add(gjUserRole.getUserRole());
- }
-
- return userProfile;
- }
-
- public boolean isUserInRole(Long userId, String role) {
- XXPortalUserRole xXPortalUserRole = daoManager.getXXPortalUserRole().findByRoleUserId(
- userId, role);
- if (xXPortalUserRole != null) {
- String userRole = xXPortalUserRole.getUserRole();
- if (userRole.equalsIgnoreCase(role)) {
- return true;
- }
- }
- return false;
- }
-
- public XXPortalUser updateUserWithPass(VXPortalUser userProfile) {
- String updatedPassword = userProfile.getPassword();
- XXPortalUser xXPortalUser = this.updateUser(userProfile);
-
- if (updatedPassword != null && !updatedPassword.isEmpty()) {
- if (!stringUtil.validatePassword(updatedPassword,
- new String[] { xXPortalUser.getFirstName(), xXPortalUser.getLastName(),
- xXPortalUser.getLoginId() })) {
- logger.warn("SECURITY:changePassword(). Invalid new password. userId="
- + xXPortalUser.getId());
-
- throw restErrorUtil.createRESTException(
- "serverMsg.userMgrNewPassword",
- MessageEnums.INVALID_PASSWORD, null, null,
- "" + xXPortalUser.getId());
- }
-
- String encryptedNewPwd = encrypt(xXPortalUser.getLoginId(),
- updatedPassword);
- xXPortalUser.setPassword(encryptedNewPwd);
- xXPortalUser = daoManager.getXXPortalUser().update(xXPortalUser);
- }
- return xXPortalUser;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/biz/UserMgrBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/biz/UserMgrBase.java b/security-admin/src/main/java/com/xasecure/biz/UserMgrBase.java
deleted file mode 100644
index efdf4bc..0000000
--- a/security-admin/src/main/java/com/xasecure/biz/UserMgrBase.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * 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 com.xasecure.biz;
-
-import com.xasecure.common.*;
-import com.xasecure.service.*;
-import com.xasecure.view.*;
-import org.springframework.beans.factory.annotation.Autowired;
-public class UserMgrBase {
-
- @Autowired
- RESTErrorUtil restErrorUtil;
-
- @Autowired
- XPortalUserService xPortalUserService;
- public VXPortalUser getXPortalUser(Long id){
- return (VXPortalUser)xPortalUserService.readResource(id);
- }
-
- public VXPortalUser createXPortalUser(VXPortalUser vXPortalUser){
- vXPortalUser = (VXPortalUser)xPortalUserService.createResource(vXPortalUser);
- return vXPortalUser;
- }
-
- public VXPortalUser updateXPortalUser(VXPortalUser vXPortalUser) {
- vXPortalUser = (VXPortalUser)xPortalUserService.updateResource(vXPortalUser);
- return vXPortalUser;
- }
-
- public void deleteXPortalUser(Long id, boolean force) {
- if (force) {
- xPortalUserService.deleteResource(id);
- } else {
- throw restErrorUtil.createRESTException(
- "serverMsg.modelMgrBaseDeleteModel",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
- }
-
- public VXPortalUserList searchXPortalUsers(SearchCriteria searchCriteria) {
- return xPortalUserService.searchXPortalUsers(searchCriteria);
- }
-
- public VXLong getXPortalUserSearchCount(SearchCriteria searchCriteria) {
- return xPortalUserService.getSearchCount(searchCriteria,
- xPortalUserService.searchFields);
- }
-
-}
[07/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/biz/XABizUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/XABizUtil.java b/security-admin/src/main/java/org/apache/ranger/biz/XABizUtil.java
new file mode 100644
index 0000000..0177682
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/biz/XABizUtil.java
@@ -0,0 +1,1313 @@
+/*
+ * 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.biz;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.common.AppConstants;
+import org.apache.ranger.common.ContextUtil;
+import org.apache.ranger.common.GUIDUtil;
+import org.apache.ranger.common.PropertiesUtil;
+import org.apache.ranger.common.RESTErrorUtil;
+import org.apache.ranger.common.StringUtil;
+import org.apache.ranger.common.UserSessionBase;
+import org.apache.ranger.common.XACommonEnums;
+import org.apache.ranger.common.XAConstants;
+import org.apache.ranger.common.db.BaseDao;
+import org.apache.ranger.db.XADaoManager;
+import org.apache.ranger.entity.XXAsset;
+import org.apache.ranger.entity.XXDBBase;
+import org.apache.ranger.entity.XXGroup;
+import org.apache.ranger.entity.XXPermMap;
+import org.apache.ranger.entity.XXPortalUser;
+import org.apache.ranger.entity.XXResource;
+import org.apache.ranger.entity.XXTrxLog;
+import org.apache.ranger.entity.XXUser;
+import org.apache.ranger.service.AbstractBaseResourceService;
+import org.apache.ranger.view.VXDataObject;
+import org.apache.ranger.view.VXPortalUser;
+import org.apache.ranger.view.VXResource;
+import org.apache.ranger.view.VXResponse;
+import org.apache.ranger.view.VXString;
+import org.apache.ranger.view.VXStringList;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.util.Random;
+
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.io.IOCase;
+
+@Component
+public class XABizUtil {
+ static final Logger logger = Logger.getLogger(XABizUtil.class);
+
+ @Autowired
+ RESTErrorUtil restErrorUtil;
+
+ @Autowired
+ XADaoManager daoManager;
+
+ @Autowired
+ StringUtil stringUtil;
+
+ @Autowired
+ UserMgr userMgr;
+
+ Set<Class<?>> groupEditableClasses;
+ private Class<?>[] groupEditableClassesList = {};
+
+ Map<String, Integer> classTypeMappings = new HashMap<String, Integer>();
+ private int maxFirstNameLength;
+ int maxDisplayNameLength = 150;
+ boolean defaultAutoApprove = true;
+ boolean showBlockedContent = true;
+ public final String EMPTY_CONTENT_DISPLAY_NAME = "...";
+ boolean enableResourceAccessControl;
+ private Random random;
+ private static final String PATH_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrst0123456789-_.";
+ private static char[] PATH_CHAR_SET = PATH_CHARS.toCharArray();
+ private static int PATH_CHAR_SET_LEN = PATH_CHAR_SET.length;
+
+ static String fileSeparator = PropertiesUtil.getProperty(
+ "xa.file.separator", "/");
+
+ public XABizUtil() {
+ maxFirstNameLength = Integer.parseInt(PropertiesUtil.getProperty(
+ "xa.user.firstname.maxlength", "16"));
+ maxDisplayNameLength = PropertiesUtil.getIntProperty(
+ "xa.bookmark.name.maxlen", maxDisplayNameLength);
+ showBlockedContent = PropertiesUtil.getBooleanProperty(
+ "xa.content.show_blocked", showBlockedContent);
+ defaultAutoApprove = PropertiesUtil.getBooleanProperty(
+ "xa.mod.default", defaultAutoApprove);
+
+ groupEditableClasses = new HashSet<Class<?>>(
+ Arrays.asList(groupEditableClassesList));
+ enableResourceAccessControl = PropertiesUtil.getBooleanProperty(
+ "xa.resource.accessControl.enabled", true);
+ random = new Random();
+ }
+
+ public <T extends XXDBBase> List<? extends XXDBBase> getParentObjects(T object) {
+ List<XXDBBase> parentObjectList = null;
+ // if (checkParentAcess.contains(object.getMyClassType())) {
+ // parentObjectList = new ArrayList<MBase>();
+ // }
+ return parentObjectList;
+ }
+
+ public int getClassType(Class<?> klass) {
+ String className = klass.getName();
+ // See if this mapping is already in the database
+ Integer classType = classTypeMappings.get(className);
+ if (classType == null) {
+ // Instantiate the class and call the getClassType method
+ if (XXDBBase.class.isAssignableFrom(klass)) {
+ try {
+ XXDBBase gjObj = (XXDBBase) klass.newInstance();
+ classType = gjObj.getMyClassType();
+ classTypeMappings.put(className, classType);
+ } catch (Throwable ex) {
+ logger.error("Error instantiating object for class "
+ + className, ex);
+ }
+ }
+ }
+ if (classType == null) {
+ return XACommonEnums.CLASS_TYPE_NONE;
+ } else {
+ return classType;
+ }
+ }
+
+ // Access control methods
+ public void checkSystemAdminAccess() {
+ UserSessionBase currentUserSession = ContextUtil
+ .getCurrentUserSession();
+ if (currentUserSession != null && currentUserSession.isUserAdmin()) {
+ return;
+ }
+ throw restErrorUtil
+ .create403RESTException("Only System Administrators can add accounts");
+ }
+
+ /**
+ * @param contentType
+ * @return
+ */
+ public int getMimeTypeInt(String contentType) {
+ if (contentType.equalsIgnoreCase("JPEG")
+ || contentType.equalsIgnoreCase("JPG")
+ || contentType.endsWith("jpg") || contentType.endsWith("jpeg")) {
+ return XAConstants.MIME_JPEG;
+ }
+ if (contentType.equalsIgnoreCase("PNG") || contentType.endsWith("png")) {
+ return XAConstants.MIME_PNG;
+ }
+ return XAConstants.MIME_UNKNOWN;
+ }
+
+ /**
+ * @param mimeType
+ * @return
+ */
+ public String getMimeType(int mimeType) {
+ switch (mimeType) {
+ case XAConstants.MIME_JPEG:
+ return "jpg";
+ case XAConstants.MIME_PNG:
+ return "png";
+ }
+ return "";
+ }
+
+ /**
+ * @param contentType
+ * @return
+ */
+ public String getImageExtension(String contentType) {
+ if (contentType.toLowerCase().endsWith("jpg")
+ || contentType.toLowerCase().endsWith("jpeg")) {
+ return "jpg";
+ } else if (contentType.toLowerCase().endsWith("png")) {
+ return "png";
+ }
+ return "";
+ }
+
+ /**
+ * @param file
+ * @return
+ */
+ public String getFileNameWithoutExtension(File file) {
+ if (file != null) {
+ String fileName = file.getName();
+ if (fileName.indexOf(".") > 0) {
+ return fileName.substring(0, fileName.indexOf("."));
+ }
+ return fileName;
+
+ }
+ return null;
+ }
+
+ public String getDisplayNameForClassName(XXDBBase obj) {
+ String classTypeDisplayName = XAConstants.getLabelFor_ClassTypes(obj
+ .getMyClassType());
+ if (classTypeDisplayName == null) {
+ logger.error(
+ "Error get name for class type. obj=" + obj.toString(),
+ new Throwable());
+ }
+ return classTypeDisplayName;
+ }
+
+ public String getDisplayName(XXDBBase obj) {
+ if (obj != null) {
+ return handleGetDisplayName(obj.getMyDisplayValue());
+ } else {
+ return handleGetDisplayName(null);
+ }
+ }
+
+ /**
+ * @param displayValue
+ * @return
+ */
+ private String handleGetDisplayName(String displayValue) {
+ if (displayValue == null || displayValue.trim().isEmpty()) {
+ return EMPTY_CONTENT_DISPLAY_NAME;
+ }
+
+ if (displayValue.length() > maxDisplayNameLength) {
+ displayValue = displayValue.substring(0, maxDisplayNameLength - 3)
+ .concat("...");
+ }
+ return displayValue;
+ }
+
+ /**
+ * @param userProfile
+ * @return
+ */
+ public String generatePublicName(VXPortalUser userProfile, XXPortalUser gjUser) {
+ return generatePublicName(userProfile.getFirstName(),
+ userProfile.getLastName());
+ }
+
+ public String generatePublicName(String firstName, String lastName) {
+ String publicName = null;
+ String fName = firstName;
+ if (firstName.length() > maxFirstNameLength) {
+ fName = firstName.substring(0, maxFirstNameLength - (1 + 3))
+ + "...";
+ }
+ if (lastName != null && lastName.length() > 0) {
+ publicName = fName + " " + lastName.substring(0, 1) + ".";
+ }
+ return publicName;
+ }
+
+ public void updateCloneReferences(XXDBBase obj) {
+ if (obj == null) {
+ return;
+ }
+ }
+
+ public Long getForUserId(XXDBBase resource) {
+ return null;
+ }
+
+ public XXDBBase getMObject(int objClassType, Long objId) {
+ XXDBBase obj = null;
+
+ if (objId != null) {
+ BaseDao<?> dao = daoManager.getDaoForClassType(objClassType);
+
+ if (dao != null) {
+ obj = (XXDBBase) dao.getById(objId);
+ }
+ }
+
+ return obj;
+ }
+
+ public XXDBBase getMObject(VXDataObject vXDataObject) {
+ if (vXDataObject != null) {
+ return getMObject(vXDataObject.getMyClassType(), vXDataObject.getId());
+ }
+ return null;
+ }
+
+ public VXDataObject getVObject(int objClassType, Long objId) {
+ if (objId == null) {
+ return null;
+ }
+ if (objClassType == XAConstants.CLASS_TYPE_USER_PROFILE) {
+ return userMgr.mapXXPortalUserVXPortalUser(daoManager.getXXPortalUser().getById(
+ objId));
+ }
+ try {
+ AbstractBaseResourceService<?, ?> myService = AbstractBaseResourceService
+ .getService(objClassType);
+ if (myService != null) {
+ return myService.readResource(objId);
+ }
+ } catch (Throwable t) {
+ logger.error("Error reading resource. objectClassType="
+ + objClassType + ", objectId=" + objId, t);
+ }
+ return null;
+ }
+
+ public void deleteReferencedObjects(XXDBBase obj) {
+
+ if (obj == null) {
+ return;
+ }
+ if (obj.getMyClassType() == XAConstants.CLASS_TYPE_NONE) {
+ return;
+ }
+
+ }
+
+ /**
+ * @param obj
+ */
+ void deleteObjects(List<XXDBBase> objs) {
+
+ }
+
+ void deleteObject(XXDBBase obj) {
+ AbstractBaseResourceService<?, ?> myService = AbstractBaseResourceService
+ .getService(obj.getMyClassType());
+ if (myService != null) {
+ myService.deleteResource(obj.getId());
+ } else {
+ logger.error("Service not found for obj=" + obj, new Throwable());
+ }
+ }
+
+ public <T extends XXDBBase> Class<? extends XXDBBase> getContextObject(
+ int objectClassType, Long objectId) {
+ return null;
+ }
+
+ public VXStringList mapStringListToVStringList(List<String> stringList) {
+ if (stringList == null) {
+ return null;
+ }
+
+ List<VXString> vStringList = new ArrayList<VXString>();
+ for (String str : stringList) {
+ VXString vXString = new VXString();
+ vXString.setValue(str);
+ vStringList.add(vXString);
+ }
+
+ return new VXStringList(vStringList);
+ }
+
+ /**
+ * return response object if users is having permission on given resource
+ *
+ * @param vXResource
+ * @param permission
+ * @return
+ */
+ public VXResponse hasPermission(VXResource vXResource, int permission) {
+
+ VXResponse vXResponse = new VXResponse();
+ if (!enableResourceAccessControl) {
+ logger.debug("Resource Access Control is disabled !!!");
+ return vXResponse;
+ }
+
+ if (vXResource == null) {
+ vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
+ vXResponse.setMsgDesc("Please provide valid policy.");
+ return vXResponse;
+ }
+
+ String resourceNames = vXResource.getName();
+ if (stringUtil.isEmpty(resourceNames)) {
+ vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
+ vXResponse.setMsgDesc("Please provide valid policy.");
+ return vXResponse;
+ }
+
+ if (isAdmin()) {
+ return vXResponse;
+ }
+
+ Long xUserId = getXUserId();
+ Long assetId = vXResource.getAssetId();
+ List<XXResource> xResourceList = daoManager.getXXResource()
+ .findByAssetIdAndResourceStatus(assetId,
+ AppConstants.STATUS_ENABLED);
+
+ XXAsset xAsset = daoManager.getXXAsset().getById(assetId);
+ int assetType = xAsset.getAssetType();
+
+ vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
+ vXResponse.setMsgDesc("Permission Denied !");
+
+ if (assetType == AppConstants.ASSET_HIVE) {
+ String[] requestResNameList = resourceNames.split(",");
+ if (stringUtil.isEmpty(vXResource.getUdfs())) {
+ int reqTableType = vXResource.getTableType();
+ int reqColumnType = vXResource.getColumnType();
+ for (String resourceName : requestResNameList) {
+ boolean matchFound = matchHivePolicy(resourceName,
+ xResourceList, xUserId, permission, reqTableType,
+ reqColumnType, false);
+ if (!matchFound) {
+ vXResponse.setMsgDesc("You're not permitted to perform "
+ + "the action for resource path : "
+ + resourceName);
+ vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
+ return vXResponse;
+ }
+ }
+ } else {
+ for (String resourceName : requestResNameList) {
+ boolean matchFound = matchHivePolicy(resourceName,
+ xResourceList, xUserId, permission);
+ if (!matchFound) {
+ vXResponse.setMsgDesc("You're not permitted to perform "
+ + "the action for resource path : "
+ + resourceName);
+ vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
+ return vXResponse;
+ }
+ }
+ }
+ vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
+ return vXResponse;
+ } else if (assetType == AppConstants.ASSET_HBASE) {
+ String[] requestResNameList = resourceNames.split(",");
+ for (String resourceName : requestResNameList) {
+ boolean matchFound = matchHbasePolicy(resourceName,
+ xResourceList, vXResponse, xUserId, permission);
+ if (!matchFound) {
+ vXResponse.setMsgDesc("You're not permitted to perform "
+ + "the action for resource path : " + resourceName);
+ vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
+ return vXResponse;
+ }
+ }
+ vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
+ return vXResponse;
+ } else if (assetType == AppConstants.ASSET_HDFS) {
+ String[] requestResNameList = resourceNames.split(",");
+ for (String resourceName : requestResNameList) {
+ boolean matchFound = matchHdfsPolicy(resourceName,
+ xResourceList, xUserId, permission);
+ if (!matchFound) {
+ vXResponse.setMsgDesc("You're not permitted to perform "
+ + "the action for resource path : " + resourceName);
+ vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
+ return vXResponse;
+ }
+ }
+ vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
+ return vXResponse;
+ } else if (assetType == AppConstants.ASSET_KNOX) {
+ String[] requestResNameList = resourceNames.split(",");
+ for (String resourceName : requestResNameList) {
+ boolean matchFound = matchKnoxPolicy(resourceName,
+ xResourceList, vXResponse, xUserId, permission);
+ if (!matchFound) {
+ vXResponse.setMsgDesc("You're not permitted to perform "
+ + "the action for resource path : " + resourceName);
+ vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
+ return vXResponse;
+ }
+ }
+ vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
+ return vXResponse;
+ } else if (assetType == AppConstants.ASSET_STORM) {
+ String[] requestResNameList = resourceNames.split(",");
+ for (String resourceName : requestResNameList) {
+ boolean matchFound = matchStormPolicy(resourceName,
+ xResourceList, vXResponse, xUserId, permission);
+ if (!matchFound) {
+ vXResponse.setMsgDesc("You're not permitted to perform "
+ + "the action for resource path : " + resourceName);
+ vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
+ return vXResponse;
+ }
+ }
+ vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
+ return vXResponse;
+ }
+ return vXResponse;
+ }
+
+ /**
+ * return true id current logged in session is owned by admin
+ *
+ * @return
+ */
+ public boolean isAdmin() {
+ UserSessionBase currentUserSession = ContextUtil
+ .getCurrentUserSession();
+ if (currentUserSession == null) {
+ logger.debug("Unable to find session.");
+ return false;
+ }
+
+ if (currentUserSession.isUserAdmin()) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * returns current user's userID from active user sessions
+ *
+ * @return
+ */
+ public Long getXUserId() {
+
+ UserSessionBase currentUserSession = ContextUtil
+ .getCurrentUserSession();
+ if (currentUserSession == null) {
+ logger.debug("Unable to find session.");
+ return null;
+ }
+
+ XXPortalUser user = daoManager.getXXPortalUser().getById(
+ currentUserSession.getUserId());
+ if (user == null) {
+ logger.debug("XXPortalUser not found with logged in user id : "
+ + currentUserSession.getUserId());
+ return null;
+ }
+
+ XXUser xUser = daoManager.getXXUser().findByUserName(user.getLoginId());
+ if (xUser == null) {
+ logger.debug("XXPortalUser not found for user id :" + user.getId()
+ + " with name " + user.getFirstName());
+ return null;
+ }
+
+ return xUser.getId();
+ }
+
+ /**
+ * returns true if user is having required permission on given Hdfs resource
+ *
+ * @param resourceName
+ * @param xResourceList
+ * @param xUserId
+ * @param permission
+ * @return
+ */
+ private boolean matchHdfsPolicy(String resourceName,
+ List<XXResource> xResourceList, Long xUserId, int permission) {
+ boolean matchFound = false;
+ resourceName = replaceMetaChars(resourceName);
+
+ for (XXResource xResource : xResourceList) {
+ if (xResource.getResourceStatus() != AppConstants.STATUS_ENABLED) {
+ continue;
+ }
+ Long resourceId = xResource.getId();
+ matchFound = checkUsrPermForPolicy(xUserId, permission, resourceId);
+ if (matchFound) {
+ matchFound = false;
+ String resource = xResource.getName();
+ String[] dbResourceNameList = resource.split(",");
+ for (String dbResourceName : dbResourceNameList) {
+ if (comparePathsForExactMatch(resourceName, dbResourceName)) {
+ matchFound = true;
+ } else {
+ if (xResource.getIsRecursive() == AppConstants.BOOL_TRUE) {
+ matchFound = isRecursiveWildCardMatch(resourceName,
+ dbResourceName);
+ } else {
+ matchFound = nonRecursiveWildCardMatch(
+ resourceName, dbResourceName);
+ }
+ }
+ if (matchFound) {
+ break;
+ }
+ }
+ if (matchFound) {
+ break;
+ }
+ }
+ }
+ return matchFound;
+ }
+
+ /**
+ * returns true if user is having required permission on given Hbase
+ * resource
+ *
+ * @param resourceName
+ * @param xResourceList
+ * @param vXResponse
+ * @param xUserId
+ * @param permission
+ * @return
+ */
+ public boolean matchHbasePolicy(String resourceName,
+ List<XXResource> xResourceList, VXResponse vXResponse, Long xUserId,
+ int permission) {
+ if(stringUtil.isEmpty(resourceName) || xResourceList==null || xUserId==null){
+ return false;
+ }
+
+ String[] splittedResources = stringUtil.split(resourceName, fileSeparator);
+ if (splittedResources.length < 1 || splittedResources.length > 3) {
+ logger.debug("Invalid resourceName name : " + resourceName);
+ return false;
+ }
+
+ String tblName = splittedResources.length > 0 ? splittedResources[0] : StringUtil.WILDCARD_ASTERISK;
+ String colFamName = splittedResources.length > 1 ? splittedResources[1] : StringUtil.WILDCARD_ASTERISK;
+ String colName = splittedResources.length > 2 ? splittedResources[2] : StringUtil.WILDCARD_ASTERISK;
+
+ boolean policyMatched = false;
+ // check all resources whether Hbase policy is enabled in any resource
+ // of provided resource list
+ for (XXResource xResource : xResourceList) {
+ if (xResource.getResourceStatus() != AppConstants.STATUS_ENABLED) {
+ continue;
+ }
+ Long resourceId = xResource.getId();
+ boolean hasPermission = checkUsrPermForPolicy(xUserId, permission, resourceId);
+ // if permission is enabled then load Tables,column family and
+ // columns list from resource
+ if (! hasPermission) {
+ continue;
+ }
+
+ // 1. does the policy match the table?
+ String[] xTables = stringUtil.isEmpty(xResource.getTables()) ? null : stringUtil.split(xResource.getTables(), ",");
+
+ boolean matchFound = (xTables == null || xTables.length == 0) ? true : matchPath(tblName, xTables);
+
+ if(matchFound) {
+ // 2. does the policy match the column?
+ String[] xColumnFamilies = stringUtil.isEmpty(xResource.getColumnFamilies()) ? null : stringUtil.split(xResource.getColumnFamilies(), ",");
+
+ matchFound = (xColumnFamilies == null || xColumnFamilies.length == 0) ? true : matchPath(colFamName, xColumnFamilies);
+
+ if(matchFound) {
+ // 3. does the policy match the columnFamily?
+ String[] xColumns = stringUtil.isEmpty(xResource.getColumns()) ? null : stringUtil.split(xResource.getColumns(), ",");
+
+ matchFound = (xColumns == null || xColumns.length == 0) ? true : matchPath(colName, xColumns);
+ }
+ }
+
+ if (matchFound) {
+ policyMatched = true;
+ break;
+ }
+ }
+ return policyMatched;
+ }
+
+ public boolean matchHivePolicy(String resourceName,
+ List<XXResource> xResourceList, Long xUserId, int permission) {
+ return matchHivePolicy(resourceName, xResourceList, xUserId,
+ permission, 0, 0, true);
+ }
+
+ /**
+ * returns true if user is having required permission on given Hive resource
+ *
+ * @param resourceName
+ * @param xResourceList
+ * @param xUserId
+ * @param permission
+ * @param reqTableType
+ * @param reqColumnType
+ * @param isUdfPolicy
+ * @return
+ */
+ public boolean matchHivePolicy(String resourceName,
+ List<XXResource> xResourceList, Long xUserId, int permission,
+ int reqTableType, int reqColumnType, boolean isUdfPolicy) {
+
+ if(stringUtil.isEmpty(resourceName) || xResourceList==null || xUserId==null){
+ return false;
+ }
+
+ String[] splittedResources = stringUtil.split(resourceName, fileSeparator);// get list of resources
+ if (splittedResources.length < 1 || splittedResources.length > 3) {
+ logger.debug("Invalid resource name : " + resourceName);
+ return false;
+ }
+
+ String dbName = splittedResources.length > 0 ? splittedResources[0] : StringUtil.WILDCARD_ASTERISK;
+ String tblName = splittedResources.length > 1 ? splittedResources[1] : StringUtil.WILDCARD_ASTERISK;
+ String colName = splittedResources.length > 2 ? splittedResources[2] : StringUtil.WILDCARD_ASTERISK;
+
+ boolean policyMatched = false;
+ for (XXResource xResource : xResourceList) {
+ if (xResource.getResourceStatus() != AppConstants.STATUS_ENABLED) {
+ continue;
+ }
+
+ Long resourceId = xResource.getId();
+ boolean hasPermission = checkUsrPermForPolicy(xUserId, permission, resourceId);
+
+ if (! hasPermission) {
+ continue;
+ }
+
+ // 1. does the policy match the database?
+ String[] xDatabases = stringUtil.isEmpty(xResource.getDatabases()) ? null : stringUtil.split(xResource.getDatabases(), ",");
+
+ boolean matchFound = (xDatabases == null || xDatabases.length == 0) ? true : matchPath(dbName, xDatabases);
+
+ if (! matchFound) {
+ continue;
+ }
+
+ // Type(either UDFs policy or non-UDFs policy) of current policy
+ // should be of same as type of policy being iterated
+ if (!stringUtil.isEmpty(xResource.getUdfs()) && !isUdfPolicy) {
+ continue;
+ }
+
+ if (isUdfPolicy) {
+ // 2. does the policy match the UDF?
+ String[] xUdfs = stringUtil.isEmpty(xResource.getUdfs()) ? null : stringUtil.split(xResource.getUdfs(), ",");
+
+ if(! matchPath(tblName, xUdfs)) {
+ continue;
+ } else {
+ policyMatched = true;
+ break;
+ }
+ } else {
+ // 2. does the policy match the table?
+ String[] xTables = stringUtil.isEmpty(xResource.getTables()) ? null : stringUtil.split(xResource.getTables(), ",");
+
+ matchFound = (xTables == null || xTables.length == 0) ? true : matchPath(tblName, xTables);
+
+ if(xResource.getTableType() == AppConstants.POLICY_EXCLUSION) {
+ matchFound = !matchFound;
+ }
+
+ if (!matchFound) {
+ continue;
+ }
+
+ // 3. does current policy match the column?
+ String[] xColumns = stringUtil.isEmpty(xResource.getColumns()) ? null : stringUtil.split(xResource.getColumns(), ",");
+
+ matchFound = (xColumns == null || xColumns.length == 0) ? true : matchPath(colName, xColumns);
+
+ if(xResource.getColumnType() == AppConstants.POLICY_EXCLUSION) {
+ matchFound = !matchFound;
+ }
+
+ if (!matchFound) {
+ continue;
+ } else {
+ policyMatched = true;
+ break;
+ }
+ }
+ }
+ return policyMatched;
+ }
+ /**
+ * returns true if user is having required permission on given Hbase
+ * resource
+ *
+ * @param resourceName
+ * @param xResourceList
+ * @param vXResponse
+ * @param xUserId
+ * @param permission
+ * @return
+ */
+ private boolean matchKnoxPolicy(String resourceName,
+ List<XXResource> xResourceList, VXResponse vXResponse, Long xUserId,
+ int permission) {
+
+ String[] splittedResources = stringUtil.split(resourceName,
+ fileSeparator);
+ int numberOfResources = splittedResources.length;
+ if (numberOfResources < 1 || numberOfResources > 3) {
+ logger.debug("Invalid policy name : " + resourceName);
+ return false;
+ }
+
+ boolean policyMatched = false;
+ // check all resources whether Knox policy is enabled in any resource
+ // of provided resource list
+ for (XXResource xResource : xResourceList) {
+ if (xResource.getResourceStatus() != AppConstants.STATUS_ENABLED) {
+ continue;
+ }
+ Long resourceId = xResource.getId();
+ boolean hasPermission = checkUsrPermForPolicy(xUserId, permission,
+ resourceId);
+ // if permission is enabled then load Topologies,services list from resource
+ if (hasPermission) {
+ String[] xTopologies = (xResource.getTopologies() == null || xResource
+ .getTopologies().equalsIgnoreCase("")) ? null : stringUtil
+ .split(xResource.getTopologies(), ",");
+ String[] xServices = (xResource.getServices() == null || xResource
+ .getServices().equalsIgnoreCase("")) ? null
+ : stringUtil.split(xResource.getServices(), ",");
+
+ boolean matchFound = false;
+
+ for (int index = 0; index < numberOfResources; index++) {
+ matchFound = false;
+ // check whether given table resource matches with any
+ // existing topology resource
+ if (index == 0) {
+ if(xTopologies!=null){
+ for (String xTopology : xTopologies) {
+ if (matchPath(splittedResources[index], xTopology)) {
+ matchFound = true;
+ continue;
+ }
+ }
+ }
+ if(!matchFound) {
+ break;
+ }
+ } // check whether given service resource matches with
+ // any existing service resource
+ else if (index == 1) {
+ if(xServices!=null){
+ for (String xService : xServices) {
+ if (matchPath(splittedResources[index],
+ xService)) {
+ matchFound = true;
+ continue;
+ }
+ }
+ }
+ if(!matchFound) {
+ break;
+ }
+ }
+ }
+ if (matchFound) {
+ policyMatched = true;
+ break;
+ }
+ }
+ }
+ return policyMatched;
+ }
+
+ /**
+ * returns true if user is having required permission on given STORM
+ * resource
+ *
+ * @param resourceName
+ * @param xResourceList
+ * @param vXResponse
+ * @param xUserId
+ * @param permission
+ * @return
+ */
+ private boolean matchStormPolicy(String resourceName,
+ List<XXResource> xResourceList, VXResponse vXResponse, Long xUserId,
+ int permission) {
+
+ String[] splittedResources = stringUtil.split(resourceName,
+ fileSeparator);
+ int numberOfResources = splittedResources.length;
+ if (numberOfResources < 1 || numberOfResources > 3) {
+ logger.debug("Invalid policy name : " + resourceName);
+ return false;
+ }
+
+ boolean policyMatched = false;
+ // check all resources whether Knox policy is enabled in any resource
+ // of provided resource list
+ for (XXResource xResource : xResourceList) {
+ if (xResource.getResourceStatus() != AppConstants.STATUS_ENABLED) {
+ continue;
+ }
+ Long resourceId = xResource.getId();
+ boolean hasPermission = checkUsrPermForPolicy(xUserId, permission,
+ resourceId);
+ // if permission is enabled then load Topologies,services list from resource
+ if (hasPermission) {
+ String[] xTopologies = (xResource.getTopologies() == null || xResource
+ .getTopologies().equalsIgnoreCase("")) ? null : stringUtil
+ .split(xResource.getTopologies(), ",");
+ /*String[] xServices = (xResource.getServices() == null || xResource
+ .getServices().equalsIgnoreCase("")) ? null
+ : stringUtil.split(xResource.getServices(), ",");*/
+
+ boolean matchFound = false;
+
+ for (int index = 0; index < numberOfResources; index++) {
+ matchFound = false;
+ // check whether given table resource matches with any
+ // existing topology resource
+ if (index == 0) {
+ if(xTopologies!=null){
+ for (String xTopology : xTopologies) {
+ if (matchPath(splittedResources[index], xTopology)) {
+ matchFound = true;
+ continue;
+ }
+ }
+ }
+ } // check whether given service resource matches with
+ // any existing service resource
+ /*else if (index == 1) {
+ if(xServices!=null){
+ for (String xService : xServices) {
+ if (matchPath(splittedResources[index],
+ xService)) {
+ matchFound = true;
+ continue;
+ }
+ }
+ }
+ }*/
+ }
+ if (matchFound) {
+ policyMatched = true;
+ break;
+ }
+ }
+ }
+ return policyMatched;
+ }
+
+ /**
+ * returns path without meta characters
+ *
+ * @param path
+ * @return
+ */
+ public String replaceMetaChars(String path) {
+ if (path == null || path.isEmpty()) {
+ return path;
+ }
+
+ if (path.contains("*")) {
+ String replacement = getRandomString(5, 60);
+ path = path.replaceAll("\\*", replacement);
+ }
+ if (path.contains("?")) {
+ String replacement = getRandomString(1, 1);
+ path = path.replaceAll("\\?", replacement);
+ }
+ return path;
+ }
+
+ /**
+ * returns random String of given length range
+ *
+ * @param minLen
+ * @param maxLen
+ * @return
+ */
+ private String getRandomString(int minLen, int maxLen) {
+ StringBuilder sb = new StringBuilder();
+ int len = getRandomInt(minLen, maxLen);
+ for (int i = 0; i < len; i++) {
+ int charIdx = random.nextInt(PATH_CHAR_SET_LEN);
+ sb.append(PATH_CHAR_SET[charIdx]);
+ }
+ return sb.toString();
+ }
+
+ /**
+ * return random integer number for given range
+ *
+ * @param min
+ * @param max
+ * @return
+ */
+ private int getRandomInt(int min, int max) {
+ if (min == max) {
+ return min;
+ } else {
+ int interval = max - min;
+ int randomNum = random.nextInt();
+ return ((Math.abs(randomNum) % interval) + min);
+ }
+ }
+
+ /**
+ * returns true if given userID is having specified permission on specified
+ * resource
+ *
+ * @param xUserId
+ * @param permission
+ * @param resourceId
+ * @return
+ */
+ private boolean checkUsrPermForPolicy(Long xUserId, int permission,
+ Long resourceId) {
+ // this snippet load user groups and permission map list from DB
+ List<XXGroup> userGroups = new ArrayList<XXGroup>();
+ List<XXPermMap> permMapList = new ArrayList<XXPermMap>();
+ userGroups = daoManager.getXXGroup().findByUserId(xUserId);
+ permMapList = daoManager.getXXPermMap().findByResourceId(resourceId);
+ Long publicGroupId = getPublicGroupId();
+ boolean matchFound = false;
+ for (XXPermMap permMap : permMapList) {
+ if (permMap.getPermType() == permission) {
+ if (permMap.getPermFor() == AppConstants.XA_PERM_FOR_GROUP) {
+ // check whether permission is enabled for public group or a group to which user belongs
+ matchFound = (publicGroupId != null && publicGroupId == permMap.getGroupId()) || isGroupInList(permMap.getGroupId(), userGroups);
+ } else if (permMap.getPermFor() == AppConstants.XA_PERM_FOR_USER) {
+ // check whether permission is enabled to user
+ matchFound = permMap.getUserId().equals(xUserId);
+ }
+ }
+ if (matchFound) {
+ break;
+ }
+ }
+ return matchFound;
+ }
+
+ public Long getPublicGroupId() {
+ XXGroup xXGroupPublic = daoManager.getXXGroup().findByGroupName(XAConstants.GROUP_PUBLIC);
+
+ return xXGroupPublic != null ? xXGroupPublic.getId() : null;
+ }
+
+ /**
+ * returns true is given group id is in given group list
+ *
+ * @param groupId
+ * @param xGroupList
+ * @return
+ */
+ public boolean isGroupInList(Long groupId, List<XXGroup> xGroupList) {
+ for (XXGroup xGroup : xGroupList) {
+ if (xGroup.getId().equals(groupId)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * returns true if given path matches in same level or sub directories with
+ * given wild card pattern
+ *
+ * @param pathToCheck
+ * @param wildcardPath
+ * @return
+ */
+ public boolean isRecursiveWildCardMatch(String pathToCheck,
+ String wildcardPath) {
+ if (pathToCheck != null) {
+ if (wildcardPath != null && wildcardPath.equals(fileSeparator)) {
+ return true;
+ }
+ StringBuilder sb = new StringBuilder();
+ for (String p : pathToCheck.split(fileSeparator)) {
+ sb.append(p);
+ boolean matchFound = FilenameUtils.wildcardMatch(sb.toString(),
+ wildcardPath);
+ if (matchFound) {
+ return true;
+ }
+ sb.append(fileSeparator);
+ }
+ sb = null;
+ }
+ return false;
+ }
+
+ /**
+ * return List<Integer>
+ *
+ * List of all possible parent return type for some specific resourceType
+ *
+ * @param resourceType
+ * , assetType
+ *
+ */
+ public List<Integer> getResorceTypeParentHirearchy(int resourceType,
+ int assetType) {
+ List<Integer> resourceTypeList = new ArrayList<Integer>();
+
+ if (assetType == AppConstants.ASSET_HDFS) {
+ resourceTypeList.add(AppConstants.RESOURCE_PATH);
+ } else if (assetType == AppConstants.ASSET_HIVE) {
+ resourceTypeList.add(AppConstants.RESOURCE_DB);
+ if (resourceType == AppConstants.RESOURCE_TABLE) {
+ resourceTypeList.add(AppConstants.RESOURCE_TABLE);
+ } else if (resourceType == AppConstants.RESOURCE_UDF) {
+ resourceTypeList.add(AppConstants.RESOURCE_UDF);
+ } else if (resourceType == AppConstants.RESOURCE_COLUMN) {
+ resourceTypeList.add(AppConstants.RESOURCE_TABLE);
+ resourceTypeList.add(AppConstants.RESOURCE_COLUMN);
+ }
+ } else if (assetType == AppConstants.ASSET_HBASE) {
+ resourceTypeList.add(AppConstants.RESOURCE_TABLE);
+ if (resourceType == AppConstants.RESOURCE_COL_FAM) {
+ resourceTypeList.add(AppConstants.RESOURCE_COL_FAM);
+ } else if (resourceType == AppConstants.RESOURCE_COLUMN) {
+ resourceTypeList.add(AppConstants.RESOURCE_COL_FAM);
+ resourceTypeList.add(AppConstants.RESOURCE_COLUMN);
+ }
+ }
+
+ return resourceTypeList;
+ }
+
+ /**
+ * return true if both path matches exactly, wild card matching is not
+ * checked
+ *
+ * @param path1
+ * @param path2
+ * @return
+ */
+ public boolean comparePathsForExactMatch(String path1, String path2) {
+ String pathSeparator = fileSeparator;
+ if (!path1.endsWith(pathSeparator)) {
+ path1 = path1.concat(pathSeparator);
+ }
+ if (!path2.endsWith(pathSeparator)) {
+ path2 = path2.concat(pathSeparator);
+ }
+ return path1.equalsIgnoreCase(path2);
+ }
+
+ /**
+ * return true if both path matches at same level path, this function does
+ * not match sub directories
+ *
+ * @param pathToCheck
+ * @param wildcardPath
+ * @return
+ */
+ public boolean nonRecursiveWildCardMatch(String pathToCheck,
+ String wildcardPath) {
+ if (pathToCheck != null && wildcardPath != null) {
+
+ List<String> pathToCheckArray = new ArrayList<String>();
+ List<String> wildcardPathArray = new ArrayList<String>();
+
+ for (String p : pathToCheck.split(fileSeparator)) {
+ pathToCheckArray.add(p);
+ }
+ for (String w : wildcardPath.split(fileSeparator)) {
+ wildcardPathArray.add(w);
+ }
+
+ if (pathToCheckArray.size() == wildcardPathArray.size()) {
+ boolean match = false;
+ for (int index = 0; index < pathToCheckArray.size(); index++) {
+ match = matchPath(pathToCheckArray.get(index),
+ wildcardPathArray.get(index));
+ if (!match)
+ return match;
+ }
+ return match;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * returns true if first and second path are same
+ *
+ * @param pathToCheckFragment
+ * @param wildCardPathFragment
+ * @return
+ */
+ private boolean matchPath(String pathToCheckFragment,
+ String wildCardPathFragment) {
+ if(pathToCheckFragment == null || wildCardPathFragment == null) {
+ return false;
+ }
+
+ if (pathToCheckFragment.contains("*")
+ || pathToCheckFragment.contains("?")) {
+ pathToCheckFragment = replaceMetaChars(pathToCheckFragment);
+
+ if (wildCardPathFragment.contains("*")
+ || wildCardPathFragment.contains("?")) {
+ return FilenameUtils.wildcardMatch(pathToCheckFragment,
+ wildCardPathFragment, IOCase.SENSITIVE);
+ } else {
+ return false;
+ }
+ } else {
+ if (wildCardPathFragment.contains("*")
+ || wildCardPathFragment.contains("?")) {
+ return FilenameUtils.wildcardMatch(pathToCheckFragment,
+ wildCardPathFragment, IOCase.SENSITIVE);
+ } else {
+ return pathToCheckFragment.trim().equals(
+ wildCardPathFragment.trim());
+ }
+ }
+ }
+
+ private boolean matchPath(String pathToCheck, String[] wildCardPaths) {
+ if (pathToCheck != null && wildCardPaths != null) {
+ for (String wildCardPath : wildCardPaths) {
+ if (matchPath(pathToCheck, wildCardPath)) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * This method returns true if first parameter value is equal to others
+ * argument value passed
+ *
+ * @param checkValue
+ * @param otherValues
+ * @return
+ */
+ public static boolean areAllEqual(int checkValue, int... otherValues) {
+ for (int value : otherValues) {
+ if (value != checkValue) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public void createTrxLog(List<XXTrxLog> trxLogList) {
+ if (trxLogList == null) {
+ return;
+ }
+
+ UserSessionBase usb = ContextUtil.getCurrentUserSession();
+ Long authSessionId = null;
+ if (usb != null) {
+ authSessionId = ContextUtil.getCurrentUserSession().getSessionId();
+ }
+ Long trxId = GUIDUtil.genLong();
+
+ for (XXTrxLog xTrxLog : trxLogList) {
+ xTrxLog.setTransactionId(trxId.toString());
+ if (authSessionId != null) {
+ xTrxLog.setSessionId("" + authSessionId);
+ }
+ xTrxLog.setSessionType("Spring Authenticated Session");
+ xTrxLog.setRequestId(trxId.toString());
+ daoManager.getXXTrxLog().create(xTrxLog);
+ }
+ }
+
+ public static int getDBFlavor() {
+
+ String dbFlavor = "";
+ boolean dbFlavorPropFound = true;
+
+ dbFlavor = PropertiesUtil.getProperty("xa.db.flavor");
+ if (dbFlavor == null || dbFlavor.trim().isEmpty()) {
+ dbFlavor = PropertiesUtil.getProperty("jdbc.dialect");
+ dbFlavorPropFound = false;
+ }
+
+ if (dbFlavor != null && !dbFlavor.trim().isEmpty()) {
+ if (dbFlavorPropFound) {
+ if ("MYSQL".equalsIgnoreCase(dbFlavor)) {
+ return AppConstants.DB_FLAVOR_MYSQL;
+ } else if ("ORACLE".equalsIgnoreCase(dbFlavor)) {
+ return AppConstants.DB_FLAVOR_ORACLE;
+ } else {
+ return AppConstants.DB_FLAVOR_UNKNOWN;
+ }
+ } else {
+ if (dbFlavor.toUpperCase().contains("MYSQL")) {
+ return AppConstants.DB_FLAVOR_MYSQL;
+ } else if (dbFlavor.toUpperCase().contains("ORACLE")) {
+ return AppConstants.DB_FLAVOR_ORACLE;
+ } else {
+ return AppConstants.DB_FLAVOR_UNKNOWN;
+ }
+ }
+ } else {
+ logger.error("Property : xa.db.flavor or jdbc.dialect, not found");
+ return AppConstants.DB_FLAVOR_UNKNOWN;
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/biz/XAuditMgr.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/XAuditMgr.java b/security-admin/src/main/java/org/apache/ranger/biz/XAuditMgr.java
new file mode 100644
index 0000000..9d69a95
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/biz/XAuditMgr.java
@@ -0,0 +1,25 @@
+/*
+ * 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.biz;
+
+public class XAuditMgr extends XAuditMgrBase {
+
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/biz/XAuditMgrBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/XAuditMgrBase.java b/security-admin/src/main/java/org/apache/ranger/biz/XAuditMgrBase.java
new file mode 100644
index 0000000..7031508
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/biz/XAuditMgrBase.java
@@ -0,0 +1,102 @@
+/*
+ * 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.biz;
+
+import org.apache.ranger.common.*;
+import org.apache.ranger.service.*;
+import org.apache.ranger.view.*;
+import org.springframework.beans.factory.annotation.Autowired;
+public class XAuditMgrBase {
+
+ @Autowired
+ RESTErrorUtil restErrorUtil;
+
+ @Autowired
+ XTrxLogService xTrxLogService;
+
+ @Autowired
+ XAccessAuditService xAccessAuditService;
+ public VXTrxLog getXTrxLog(Long id){
+ return (VXTrxLog)xTrxLogService.readResource(id);
+ }
+
+ public VXTrxLog createXTrxLog(VXTrxLog vXTrxLog){
+ vXTrxLog = (VXTrxLog)xTrxLogService.createResource(vXTrxLog);
+ return vXTrxLog;
+ }
+
+ public VXTrxLog updateXTrxLog(VXTrxLog vXTrxLog) {
+ vXTrxLog = (VXTrxLog)xTrxLogService.updateResource(vXTrxLog);
+ return vXTrxLog;
+ }
+
+ public void deleteXTrxLog(Long id, boolean force) {
+ if (force) {
+ xTrxLogService.deleteResource(id);
+ } else {
+ throw restErrorUtil.createRESTException(
+ "serverMsg.modelMgrBaseDeleteModel",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ }
+
+ public VXTrxLogList searchXTrxLogs(SearchCriteria searchCriteria) {
+ return xTrxLogService.searchXTrxLogs(searchCriteria);
+ }
+
+ public VXLong getXTrxLogSearchCount(SearchCriteria searchCriteria) {
+ return xTrxLogService.getSearchCount(searchCriteria,
+ xTrxLogService.searchFields);
+ }
+
+ public VXAccessAudit getXAccessAudit(Long id){
+ return (VXAccessAudit)xAccessAuditService.readResource(id);
+ }
+
+ public VXAccessAudit createXAccessAudit(VXAccessAudit vXAccessAudit){
+ vXAccessAudit = (VXAccessAudit)xAccessAuditService.createResource(vXAccessAudit);
+ return vXAccessAudit;
+ }
+
+ public VXAccessAudit updateXAccessAudit(VXAccessAudit vXAccessAudit) {
+ vXAccessAudit = (VXAccessAudit)xAccessAuditService.updateResource(vXAccessAudit);
+ return vXAccessAudit;
+ }
+
+ public void deleteXAccessAudit(Long id, boolean force) {
+ if (force) {
+ xAccessAuditService.deleteResource(id);
+ } else {
+ throw restErrorUtil.createRESTException(
+ "serverMsg.modelMgrBaseDeleteModel",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ }
+
+ public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) {
+ return xAccessAuditService.searchXAccessAudits(searchCriteria);
+ }
+
+ public VXLong getXAccessAuditSearchCount(SearchCriteria searchCriteria) {
+ return xAccessAuditService.getSearchCount(searchCriteria,
+ xAccessAuditService.searchFields);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/biz/XUserMgr.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/XUserMgr.java b/security-admin/src/main/java/org/apache/ranger/biz/XUserMgr.java
new file mode 100644
index 0000000..7f0fe37
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/biz/XUserMgr.java
@@ -0,0 +1,450 @@
+/*
+ * 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.biz;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.biz.UserMgr;
+import org.apache.ranger.biz.XABizUtil;
+import org.apache.ranger.common.MessageEnums;
+import org.apache.ranger.common.PropertiesUtil;
+import org.apache.ranger.common.SearchCriteria;
+import org.apache.ranger.common.XAConstants;
+import org.apache.ranger.db.XADaoManager;
+import org.apache.ranger.db.XXGroupUserDao;
+import org.apache.ranger.entity.XXGroup;
+import org.apache.ranger.entity.XXPortalUser;
+import org.apache.ranger.entity.XXTrxLog;
+import org.apache.ranger.service.XUserService;
+import org.apache.ranger.view.VXGroup;
+import org.apache.ranger.view.VXGroupList;
+import org.apache.ranger.view.VXGroupUser;
+import org.apache.ranger.view.VXGroupUserList;
+import org.apache.ranger.view.VXPortalUser;
+import org.apache.ranger.view.VXUser;
+import org.apache.ranger.view.VXUserList;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+@Component
+public class XUserMgr extends XUserMgrBase {
+
+ @Autowired
+ XUserService xUserService;
+ @Autowired
+ XABizUtil msBizUtil;
+
+ @Autowired
+ UserMgr userMgr;
+
+ @Autowired
+ XADaoManager daoManager;
+
+ @Autowired
+ XABizUtil xaBizUtil;
+
+ static final Logger logger = Logger.getLogger(XUserMgr.class);
+
+ public void deleteXGroup(Long id, boolean force) {
+ if (force) {
+ SearchCriteria searchCriteria = new SearchCriteria();
+ searchCriteria.addParam("xGroupId", id);
+ VXGroupUserList vxGroupUserList = searchXGroupUsers(searchCriteria);
+ for (VXGroupUser groupUser : vxGroupUserList.getList()) {
+ daoManager.getXXGroupUser().remove(groupUser.getId());
+ }
+ XXGroup xGroup = daoManager.getXXGroup().getById(id);
+ daoManager.getXXGroup().remove(id);
+ List<XXTrxLog> trxLogList = xGroupService.getTransactionLog(
+ xGroupService.populateViewBean(xGroup), "delete");
+ xaBizUtil.createTrxLog(trxLogList);
+ } else {
+ throw restErrorUtil.createRESTException(
+ "serverMsg.modelMgrBaseDeleteModel",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ }
+
+ public void deleteXUser(Long id, boolean force) {
+ if (force) {
+ SearchCriteria searchCriteria = new SearchCriteria();
+ searchCriteria.addParam("xUserId", id);
+ VXGroupUserList vxGroupUserList = searchXGroupUsers(searchCriteria);
+
+ XXGroupUserDao xGroupUserDao = daoManager.getXXGroupUser();
+ for (VXGroupUser groupUser : vxGroupUserList.getList()) {
+ xGroupUserDao.remove(groupUser.getId());
+ }
+ // TODO : Need to discuss, why we were not removing user from the
+ // system.
+
+ // XXUser xUser = daoManager.getXXUser().getById(id);
+ daoManager.getXXUser().remove(id);
+ //applicationCache.removeUserID(id);
+ // Not Supported So Far
+ // List<XXTrxLog> trxLogList = xUserService.getTransactionLog(
+ // xUserService.populateViewBean(xUser), "delete");
+ // xaBizUtil.createTrxLog(trxLogList);
+ } else {
+ throw restErrorUtil.createRESTException(
+ "serverMsg.modelMgrBaseDeleteModel",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ }
+
+ public VXUser getXUserByUserName(String userName) {
+ return xUserService.getXUserByUserName(userName);
+ }
+
+ public VXUser createXUser(VXUser vXUser) {
+
+ String userName = vXUser.getName();
+ if (userName == null || userName.isEmpty()) {
+ throw restErrorUtil.createRESTException("Please provide a valid "
+ + "username.", MessageEnums.INVALID_INPUT_DATA);
+ }
+
+ if (vXUser.getDescription() == null) {
+ setUserDesc(vXUser);
+ }
+
+ String actualPassword = vXUser.getPassword();
+
+ VXPortalUser vXPortalUser = new VXPortalUser();
+ vXPortalUser.setLoginId(userName);
+ vXPortalUser.setFirstName(vXUser.getFirstName());
+ vXPortalUser.setLastName(vXUser.getLastName());
+ vXPortalUser.setEmailAddress(vXUser.getEmailAddress());
+ vXPortalUser.setPublicScreenName(vXUser.getFirstName() +" "+ vXUser.getLastName());
+ vXPortalUser.setPassword(actualPassword);
+ vXPortalUser.setUserRoleList(vXUser.getUserRoleList());
+ vXPortalUser = userMgr.createDefaultAccountUser(vXPortalUser);
+
+ VXUser createdXUser = xUserService.createResource(vXUser);
+
+ createdXUser.setPassword(actualPassword);
+ List<XXTrxLog> trxLogList = xUserService.getTransactionLog(
+ createdXUser, "create");
+
+ String hiddenPassword = PropertiesUtil.getProperty(
+ "xa.password.hidden", "*****");
+ createdXUser.setPassword(hiddenPassword);
+
+ Collection<Long> groupIdList = vXUser.getGroupIdList();
+ List<VXGroupUser> vXGroupUsers = new ArrayList<VXGroupUser>();
+ if (groupIdList != null) {
+ for (Long groupId : groupIdList) {
+ VXGroupUser vXGroupUser = createXGroupUser(
+ createdXUser.getId(), groupId);
+ // trxLogList.addAll(xGroupUserService.getTransactionLog(
+ // vXGroupUser, "create"));
+ vXGroupUsers.add(vXGroupUser);
+ }
+ }
+ for (VXGroupUser vXGroupUser : vXGroupUsers) {
+ trxLogList.addAll(xGroupUserService.getTransactionLog(vXGroupUser,
+ "create"));
+ }
+ //
+ xaBizUtil.createTrxLog(trxLogList);
+
+ return createdXUser;
+ }
+
+ private VXGroupUser createXGroupUser(Long userId, Long groupId) {
+ VXGroupUser vXGroupUser = new VXGroupUser();
+ vXGroupUser.setParentGroupId(groupId);
+ vXGroupUser.setUserId(userId);
+ VXGroup vXGroup = xGroupService.readResource(groupId);
+ vXGroupUser.setName(vXGroup.getName());
+ vXGroupUser = xGroupUserService.createResource(vXGroupUser);
+
+ return vXGroupUser;
+ }
+
+ public VXUser updateXUser(VXUser vXUser) {
+ VXPortalUser oldUserProfile = userMgr.getUserProfileByLoginId(vXUser
+ .getName());
+ VXPortalUser vXPortalUser = new VXPortalUser();
+ if(oldUserProfile!=null && oldUserProfile.getId()!=null){
+ vXPortalUser.setId(oldUserProfile.getId());
+ }
+ // TODO : There is a possibility that old user may not exist.
+
+
+ vXPortalUser.setFirstName(vXUser.getFirstName());
+ vXPortalUser.setLastName(vXUser.getLastName());
+ vXPortalUser.setEmailAddress(vXUser.getEmailAddress());
+ vXPortalUser.setLoginId(vXUser.getName());
+ vXPortalUser.setStatus(vXUser.getStatus());
+ vXPortalUser.setUserRoleList(vXUser.getUserRoleList());
+ vXPortalUser.setPublicScreenName(vXUser.getFirstName() + " "
+ + vXUser.getLastName());
+ vXPortalUser.setUserSource(vXUser.getUserSource());
+ String hiddenPasswordString = PropertiesUtil.getProperty(
+ "xa.password.hidden", "*****");
+ String password = vXUser.getPassword();
+ if (password != null && password.equals(hiddenPasswordString)) {
+ vXPortalUser.setPassword(oldUserProfile.getPassword());
+ }
+ vXPortalUser.setPassword(password);
+
+ Collection<Long> groupIdList = vXUser.getGroupIdList();
+ XXPortalUser xXPortalUser = new XXPortalUser();
+ xXPortalUser=userMgr.updateUserWithPass(vXPortalUser);
+ Collection<String> roleList = new ArrayList<String>();
+ if(xXPortalUser!=null){
+ roleList=userMgr.getRolesForUser(xXPortalUser);
+ }
+ if(roleList==null || roleList.size()==0){
+ roleList.add(XAConstants.ROLE_USER);
+ }
+
+ // TODO I've to get the transaction log from here.
+ // There is nothing to log anything in XXUser so far.
+ vXUser = xUserService.updateResource(vXUser);
+ vXUser.setUserRoleList(roleList);
+ vXUser.setPassword(password);
+ List<XXTrxLog> trxLogList = xUserService.getTransactionLog(vXUser,
+ oldUserProfile, "update");
+ vXUser.setPassword(hiddenPasswordString);
+
+ Long userId = vXUser.getId();
+ List<Long> groupUsersToRemove = new ArrayList<Long>();
+
+ if (groupIdList != null) {
+ SearchCriteria searchCriteria = new SearchCriteria();
+ searchCriteria.addParam("xUserId", userId);
+ VXGroupUserList vXGroupUserList = xGroupUserService
+ .searchXGroupUsers(searchCriteria);
+ List<VXGroupUser> vXGroupUsers = vXGroupUserList.getList();
+
+ if (vXGroupUsers != null) {
+
+ // Create
+ for (Long groupId : groupIdList) {
+ boolean found = false;
+ for (VXGroupUser vXGroupUser : vXGroupUsers) {
+ if (groupId.equals(vXGroupUser.getParentGroupId())) {
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ VXGroupUser vXGroupUser = createXGroupUser(userId,
+ groupId);
+ trxLogList.addAll(xGroupUserService.getTransactionLog(
+ vXGroupUser, "create"));
+ }
+ }
+
+ // Delete
+ for (VXGroupUser vXGroupUser : vXGroupUsers) {
+ boolean found = false;
+ for (Long groupId : groupIdList) {
+ if (groupId.equals(vXGroupUser.getParentGroupId())) {
+ trxLogList.addAll(xGroupUserService
+ .getTransactionLog(vXGroupUser, "update"));
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ // TODO I've to get the transaction log from here.
+ trxLogList.addAll(xGroupUserService.getTransactionLog(
+ vXGroupUser, "delete"));
+ groupUsersToRemove.add(vXGroupUser.getId());
+ // xGroupUserService.deleteResource(vXGroupUser.getId());
+ }
+ }
+
+ } else {
+ for (Long groupId : groupIdList) {
+ VXGroupUser vXGroupUser = createXGroupUser(userId, groupId);
+ trxLogList.addAll(xGroupUserService.getTransactionLog(
+ vXGroupUser, "create"));
+ }
+ }
+ vXUser.setGroupIdList(groupIdList);
+ } else {
+ logger.debug("Group id list can't be null for user. Group user "
+ + "mapping not updated for user : " + userId);
+ }
+
+ xaBizUtil.createTrxLog(trxLogList);
+
+ for (Long groupUserId : groupUsersToRemove) {
+ xGroupUserService.deleteResource(groupUserId);
+ }
+
+ return vXUser;
+ }
+
+ public VXUser createXUserWithOutLogin(VXUser vXUser) {
+ return xUserService.createXUserWithOutLogin(vXUser);
+ }
+
+ public VXGroup createXGroup(VXGroup vXGroup) {
+ // FIXME Just a hack
+ if (vXGroup.getDescription() == null) {
+ vXGroup.setDescription(vXGroup.getName());
+ }
+
+ vXGroup = xGroupService.createResource(vXGroup);
+ List<XXTrxLog> trxLogList = xGroupService.getTransactionLog(vXGroup,
+ "create");
+ xaBizUtil.createTrxLog(trxLogList);
+ return vXGroup;
+ }
+
+ public VXGroup createXGroupWithoutLogin(VXGroup vXGroup) {
+ return xGroupService.createXGroupWithOutLogin(vXGroup);
+ }
+
+ public VXGroupUser createXGroupUser(VXGroupUser vXGroupUser) {
+ vXGroupUser = xGroupUserService
+ .createXGroupUserWithOutLogin(vXGroupUser);
+ return vXGroupUser;
+ }
+
+ public VXUser getXUser(Long id) {
+ return xUserService.readResourceWithOutLogin(id);
+
+ }
+
+ public VXGroupUser getXGroupUser(Long id) {
+ return xGroupUserService.readResourceWithOutLogin(id);
+
+ }
+
+ public VXGroup getXGroup(Long id) {
+ return xGroupService.readResourceWithOutLogin(id);
+
+ }
+
+ /**
+ * // public void createXGroupAndXUser(String groupName, String userName) {
+ *
+ * // Long groupId; // Long userId; // XXGroup xxGroup = //
+ * appDaoManager.getXXGroup().findByGroupName(groupName); // VXGroup
+ * vxGroup; // if (xxGroup == null) { // vxGroup = new VXGroup(); //
+ * vxGroup.setName(groupName); // vxGroup.setDescription(groupName); //
+ * vxGroup.setGroupType(AppConstants.XA_GROUP_USER); //
+ * vxGroup.setPriAcctId(1l); // vxGroup.setPriGrpId(1l); // vxGroup =
+ * xGroupService.createResource(vxGroup); // groupId = vxGroup.getId(); // }
+ * else { // groupId = xxGroup.getId(); // } // XXUser xxUser =
+ * appDaoManager.getXXUser().findByUserName(userName); // VXUser vxUser; //
+ * if (xxUser == null) { // vxUser = new VXUser(); //
+ * vxUser.setName(userName); // vxUser.setDescription(userName); //
+ * vxUser.setPriGrpId(1l); // vxUser.setPriAcctId(1l); // vxUser =
+ * xUserService.createResource(vxUser); // userId = vxUser.getId(); // }
+ * else { // userId = xxUser.getId(); // } // VXGroupUser vxGroupUser = new
+ * VXGroupUser(); // vxGroupUser.setParentGroupId(groupId); //
+ * vxGroupUser.setUserId(userId); // vxGroupUser.setName(groupName); //
+ * vxGroupUser.setPriAcctId(1l); // vxGroupUser.setPriGrpId(1l); //
+ * vxGroupUser = xGroupUserService.createResource(vxGroupUser);
+ *
+ * // }
+ */
+
+ public void deleteXGroupAndXUser(String groupName, String userName) {
+ VXGroup vxGroup = xGroupService.getGroupByGroupName(groupName);
+ VXUser vxUser = xUserService.getXUserByUserName(userName);
+ SearchCriteria searchCriteria = new SearchCriteria();
+ searchCriteria.addParam("xGroupId", vxGroup.getId());
+ searchCriteria.addParam("xUserId", vxUser.getId());
+ VXGroupUserList vxGroupUserList = xGroupUserService
+ .searchXGroupUsers(searchCriteria);
+ for (VXGroupUser vxGroupUser : vxGroupUserList.getList()) {
+ daoManager.getXXGroupUser().remove(vxGroupUser.getId());
+ }
+ }
+
+ public VXGroupList getXUserGroups(Long xUserId) {
+ SearchCriteria searchCriteria = new SearchCriteria();
+ searchCriteria.addParam("xUserId", xUserId);
+ VXGroupUserList vXGroupUserList = xGroupUserService
+ .searchXGroupUsers(searchCriteria);
+ VXGroupList vXGroupList = new VXGroupList();
+ List<VXGroup> vXGroups = new ArrayList<VXGroup>();
+ if (vXGroupUserList != null) {
+ List<VXGroupUser> vXGroupUsers = vXGroupUserList.getList();
+ Set<Long> groupIdList = new HashSet<Long>();
+ for (VXGroupUser vXGroupUser : vXGroupUsers) {
+ groupIdList.add(vXGroupUser.getParentGroupId());
+ }
+ for (Long groupId : groupIdList) {
+ VXGroup vXGroup = xGroupService.readResource(groupId);
+ vXGroups.add(vXGroup);
+ }
+ vXGroupList.setVXGroups(vXGroups);
+ } else {
+ logger.debug("No groups found for user id : " + xUserId);
+ }
+ return vXGroupList;
+ }
+
+ public VXUserList getXGroupUsers(Long xGroupId) {
+ SearchCriteria searchCriteria = new SearchCriteria();
+ searchCriteria.addParam("xGroupId", xGroupId);
+ VXGroupUserList vXGroupUserList = xGroupUserService
+ .searchXGroupUsers(searchCriteria);
+ VXUserList vXUserList = new VXUserList();
+
+ List<VXUser> vXUsers = new ArrayList<VXUser>();
+ if (vXGroupUserList != null) {
+ List<VXGroupUser> vXGroupUsers = vXGroupUserList.getList();
+ Set<Long> userIdList = new HashSet<Long>();
+ for (VXGroupUser vXGroupUser : vXGroupUsers) {
+ userIdList.add(vXGroupUser.getUserId());
+ }
+ for (Long userId : userIdList) {
+ VXUser vXUser = xUserService.readResource(userId);
+ vXUsers.add(vXUser);
+
+ }
+ vXUserList.setVXUsers(vXUsers);
+ } else {
+ logger.debug("No users found for group id : " + xGroupId);
+ }
+ return vXUserList;
+ }
+
+ // FIXME Hack : Unnecessary, to be removed after discussion.
+ private void setUserDesc(VXUser vXUser) {
+ vXUser.setDescription(vXUser.getName());
+ }
+
+ @Override
+ public VXGroup updateXGroup(VXGroup vXGroup) {
+ XXGroup xGroup = daoManager.getXXGroup().getById(vXGroup.getId());
+ List<XXTrxLog> trxLogList = xGroupService.getTransactionLog(vXGroup,
+ xGroup, "update");
+ xaBizUtil.createTrxLog(trxLogList);
+ vXGroup = (VXGroup) xGroupService.updateResource(vXGroup);
+ return vXGroup;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/biz/XUserMgrBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/XUserMgrBase.java b/security-admin/src/main/java/org/apache/ranger/biz/XUserMgrBase.java
new file mode 100644
index 0000000..2a413d2
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/biz/XUserMgrBase.java
@@ -0,0 +1,246 @@
+/*
+ * 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.biz;
+
+import org.apache.ranger.common.*;
+import org.apache.ranger.service.*;
+import org.apache.ranger.view.*;
+import org.springframework.beans.factory.annotation.Autowired;
+public class XUserMgrBase {
+
+ @Autowired
+ RESTErrorUtil restErrorUtil;
+
+ @Autowired
+ XGroupService xGroupService;
+
+ @Autowired
+ XUserService xUserService;
+
+ @Autowired
+ XGroupUserService xGroupUserService;
+
+ @Autowired
+ XGroupGroupService xGroupGroupService;
+
+ @Autowired
+ XPermMapService xPermMapService;
+
+ @Autowired
+ XAuditMapService xAuditMapService;
+ public VXGroup getXGroup(Long id){
+ return (VXGroup)xGroupService.readResource(id);
+ }
+
+ public VXGroup createXGroup(VXGroup vXGroup){
+ vXGroup = (VXGroup)xGroupService.createResource(vXGroup);
+ return vXGroup;
+ }
+
+ public VXGroup updateXGroup(VXGroup vXGroup) {
+ vXGroup = (VXGroup)xGroupService.updateResource(vXGroup);
+ return vXGroup;
+ }
+
+ public void deleteXGroup(Long id, boolean force) {
+ if (force) {
+ xGroupService.deleteResource(id);
+ } else {
+ throw restErrorUtil.createRESTException(
+ "serverMsg.modelMgrBaseDeleteModel",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ }
+
+ public VXGroupList searchXGroups(SearchCriteria searchCriteria) {
+ return xGroupService.searchXGroups(searchCriteria);
+ }
+
+ public VXLong getXGroupSearchCount(SearchCriteria searchCriteria) {
+ return xGroupService.getSearchCount(searchCriteria,
+ xGroupService.searchFields);
+ }
+
+ public VXUser getXUser(Long id){
+ return (VXUser)xUserService.readResource(id);
+ }
+
+ public VXUser createXUser(VXUser vXUser){
+ vXUser = (VXUser)xUserService.createResource(vXUser);
+ return vXUser;
+ }
+
+ public VXUser updateXUser(VXUser vXUser) {
+ vXUser = (VXUser)xUserService.updateResource(vXUser);
+ return vXUser;
+ }
+
+ public void deleteXUser(Long id, boolean force) {
+ if (force) {
+ xUserService.deleteResource(id);
+ } else {
+ throw restErrorUtil.createRESTException(
+ "serverMsg.modelMgrBaseDeleteModel",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ }
+
+ public VXUserList searchXUsers(SearchCriteria searchCriteria) {
+ return xUserService.searchXUsers(searchCriteria);
+ }
+
+ public VXLong getXUserSearchCount(SearchCriteria searchCriteria) {
+ return xUserService.getSearchCount(searchCriteria,
+ xUserService.searchFields);
+ }
+
+ public VXGroupUser getXGroupUser(Long id){
+ return (VXGroupUser)xGroupUserService.readResource(id);
+ }
+
+ public VXGroupUser createXGroupUser(VXGroupUser vXGroupUser){
+ vXGroupUser = (VXGroupUser)xGroupUserService.createResource(vXGroupUser);
+ return vXGroupUser;
+ }
+
+ public VXGroupUser updateXGroupUser(VXGroupUser vXGroupUser) {
+ vXGroupUser = (VXGroupUser)xGroupUserService.updateResource(vXGroupUser);
+ return vXGroupUser;
+ }
+
+ public void deleteXGroupUser(Long id, boolean force) {
+ if (force) {
+ xGroupUserService.deleteResource(id);
+ } else {
+ throw restErrorUtil.createRESTException(
+ "serverMsg.modelMgrBaseDeleteModel",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ }
+
+ public VXGroupUserList searchXGroupUsers(SearchCriteria searchCriteria) {
+ return xGroupUserService.searchXGroupUsers(searchCriteria);
+ }
+
+ public VXLong getXGroupUserSearchCount(SearchCriteria searchCriteria) {
+ return xGroupUserService.getSearchCount(searchCriteria,
+ xGroupUserService.searchFields);
+ }
+
+ public VXGroupGroup getXGroupGroup(Long id){
+ return (VXGroupGroup)xGroupGroupService.readResource(id);
+ }
+
+ public VXGroupGroup createXGroupGroup(VXGroupGroup vXGroupGroup){
+ vXGroupGroup = (VXGroupGroup)xGroupGroupService.createResource(vXGroupGroup);
+ return vXGroupGroup;
+ }
+
+ public VXGroupGroup updateXGroupGroup(VXGroupGroup vXGroupGroup) {
+ vXGroupGroup = (VXGroupGroup)xGroupGroupService.updateResource(vXGroupGroup);
+ return vXGroupGroup;
+ }
+
+ public void deleteXGroupGroup(Long id, boolean force) {
+ if (force) {
+ xGroupGroupService.deleteResource(id);
+ } else {
+ throw restErrorUtil.createRESTException(
+ "serverMsg.modelMgrBaseDeleteModel",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ }
+
+ public VXGroupGroupList searchXGroupGroups(SearchCriteria searchCriteria) {
+ return xGroupGroupService.searchXGroupGroups(searchCriteria);
+ }
+
+ public VXLong getXGroupGroupSearchCount(SearchCriteria searchCriteria) {
+ return xGroupGroupService.getSearchCount(searchCriteria,
+ xGroupGroupService.searchFields);
+ }
+
+ public VXPermMap getXPermMap(Long id){
+ return (VXPermMap)xPermMapService.readResource(id);
+ }
+
+ public VXPermMap createXPermMap(VXPermMap vXPermMap){
+ vXPermMap = (VXPermMap)xPermMapService.createResource(vXPermMap);
+ return vXPermMap;
+ }
+
+ public VXPermMap updateXPermMap(VXPermMap vXPermMap) {
+ vXPermMap = (VXPermMap)xPermMapService.updateResource(vXPermMap);
+ return vXPermMap;
+ }
+
+ public void deleteXPermMap(Long id, boolean force) {
+ if (force) {
+ xPermMapService.deleteResource(id);
+ } else {
+ throw restErrorUtil.createRESTException(
+ "serverMsg.modelMgrBaseDeleteModel",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ }
+
+ public VXPermMapList searchXPermMaps(SearchCriteria searchCriteria) {
+ return xPermMapService.searchXPermMaps(searchCriteria);
+ }
+
+ public VXLong getXPermMapSearchCount(SearchCriteria searchCriteria) {
+ return xPermMapService.getSearchCount(searchCriteria,
+ xPermMapService.searchFields);
+ }
+
+ public VXAuditMap getXAuditMap(Long id){
+ return (VXAuditMap)xAuditMapService.readResource(id);
+ }
+
+ public VXAuditMap createXAuditMap(VXAuditMap vXAuditMap){
+ vXAuditMap = (VXAuditMap)xAuditMapService.createResource(vXAuditMap);
+ return vXAuditMap;
+ }
+
+ public VXAuditMap updateXAuditMap(VXAuditMap vXAuditMap) {
+ vXAuditMap = (VXAuditMap)xAuditMapService.updateResource(vXAuditMap);
+ return vXAuditMap;
+ }
+
+ public void deleteXAuditMap(Long id, boolean force) {
+ if (force) {
+ xAuditMapService.deleteResource(id);
+ } else {
+ throw restErrorUtil.createRESTException(
+ "serverMsg.modelMgrBaseDeleteModel",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ }
+
+ public VXAuditMapList searchXAuditMaps(SearchCriteria searchCriteria) {
+ return xAuditMapService.searchXAuditMaps(searchCriteria);
+ }
+
+ public VXLong getXAuditMapSearchCount(SearchCriteria searchCriteria) {
+ return xAuditMapService.getSearchCount(searchCriteria,
+ xAuditMapService.searchFields);
+ }
+
+}
[28/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/org/apache/ranger/knox/client/KnoxClient.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/org/apache/ranger/knox/client/KnoxClient.java b/lookup-client/src/main/java/org/apache/ranger/knox/client/KnoxClient.java
new file mode 100644
index 0000000..e9b6c33
--- /dev/null
+++ b/lookup-client/src/main/java/org/apache/ranger/knox/client/KnoxClient.java
@@ -0,0 +1,387 @@
+/**
+ * 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.knox.client;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.hadoop.client.config.BaseClient;
+import org.apache.ranger.hadoop.client.exceptions.HadoopException;
+import org.codehaus.jackson.JsonNode;
+import org.codehaus.jackson.map.ObjectMapper;
+
+import com.sun.jersey.api.client.Client;
+import com.sun.jersey.api.client.ClientResponse;
+import com.sun.jersey.api.client.WebResource;
+import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
+
+public class KnoxClient {
+
+ private static final String EXPECTED_MIME_TYPE = "application/json";
+ private static final Log LOG = LogFactory.getLog(KnoxClient.class);
+
+ private String knoxUrl;
+ private String userName;
+ private String password;
+
+ /*
+ Sample curl calls to Knox to discover topologies
+ curl -ivk -u admin:admin-password https://localhost:8443/gateway/admin/api/v1/topologies
+ curl -ivk -u admin:admin-password https://localhost:8443/gateway/admin/api/v1/topologies/admin
+ */
+
+ public KnoxClient(String knoxUrl, String userName, String password) {
+ LOG.debug("Constructed KnoxClient with knoxUrl: " + knoxUrl +
+ ", userName: " + userName);
+ this.knoxUrl = knoxUrl;
+ this.userName = userName;
+ this.password = password;
+ }
+
+ public List<String> getTopologyList(String topologyNameMatching) {
+
+ // sample URI: https://hdp.example.com:8443/gateway/admin/api/v1/topologies
+ LOG.debug("Getting Knox topology list for topologyNameMatching : " +
+ topologyNameMatching);
+ List<String> topologyList = new ArrayList<String>();
+ String errMsg = " You can still save the repository and start creating "
+ + "policies, but you would not be able to use autocomplete for "
+ + "resource names. Check xa_portal.log for more info.";
+ if ( topologyNameMatching == null || topologyNameMatching.trim().isEmpty()) {
+ topologyNameMatching = "";
+ }
+ try {
+
+ Client client = null;
+ ClientResponse response = null;
+
+ try {
+ client = Client.create();;
+
+ client.addFilter(new HTTPBasicAuthFilter(userName, password));
+ WebResource webResource = client.resource(knoxUrl);
+ response = webResource.accept(EXPECTED_MIME_TYPE)
+ .get(ClientResponse.class);
+ LOG.debug("Knox topology list response: " + response);
+ if (response != null) {
+
+ if (response.getStatus() == 200) {
+ String jsonString = response.getEntity(String.class);
+ LOG.debug("Knox topology list response JSON string: "+ jsonString);
+
+ ObjectMapper objectMapper = new ObjectMapper();
+
+ JsonNode rootNode = objectMapper.readTree(jsonString);
+ JsonNode topologyNode = rootNode.findValue("topology");
+ if (topologyNode == null) {
+ return topologyList;
+ }
+ Iterator<JsonNode> elements = topologyNode.getElements();
+ while (elements.hasNext()) {
+ JsonNode element = elements.next();
+ String topologyName = element.get("name").getValueAsText();
+ LOG.debug("Found Knox topologyName: " + topologyName);
+ if (topologyName.startsWith(topologyNameMatching)) {
+ topologyList.add(topologyName);
+ }
+ }
+ } else {
+ LOG.error("Got invalid REST response from: "+ knoxUrl + ", responsStatus: " + response.getStatus());
+ }
+
+ } else {
+ String msgDesc = "Unable to get a valid response for "
+ + "isFileChanged() call for KnoxUrl : [" + knoxUrl
+ + "] - got null response.";
+ LOG.error(msgDesc);
+ HadoopException hdpException = new HadoopException(msgDesc);
+ hdpException.generateResponseDataMap(false, msgDesc,
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ }
+
+ } finally {
+ if (response != null) {
+ response.close();
+ }
+ if (client != null) {
+ client.destroy();
+ }
+ }
+ } catch (HadoopException he) {
+ throw he;
+ } catch (Throwable t) {
+ String msgDesc = "Exception on REST call to KnoxUrl : " + knoxUrl + ".";
+ HadoopException hdpException = new HadoopException(msgDesc, t);
+ LOG.error(msgDesc, t);
+
+ hdpException.generateResponseDataMap(false,
+ BaseClient.getMessage(t), msgDesc + errMsg, null, null);
+ throw hdpException;
+ } finally {
+ }
+ return topologyList;
+ }
+
+
+ public List<String> getServiceList(String topologyName, String serviceNameMatching) {
+
+ // sample URI: .../admin/api/v1/topologies/<topologyName>
+
+ List<String> serviceList = new ArrayList<String>();
+ String errMsg = " You can still save the repository and start creating "
+ + "policies, but you would not be able to use autocomplete for "
+ + "resource names. Check xa_portal.log for more info.";
+ if ( serviceNameMatching == null || serviceNameMatching.trim().isEmpty()) {
+ serviceNameMatching = "";
+ }
+ try {
+
+ Client client = null;
+ ClientResponse response = null;
+
+ try {
+ client = Client.create();;
+
+ client.addFilter(new HTTPBasicAuthFilter(userName, password));
+
+ WebResource webResource = client.resource(knoxUrl + "/" + topologyName);
+
+ response = webResource.accept(EXPECTED_MIME_TYPE)
+ .get(ClientResponse.class);
+ LOG.debug("Knox service lookup response: " + response);
+ if (response != null) {
+
+ if (response.getStatus() == 200) {
+ String jsonString = response.getEntity(String.class);
+ LOG.debug("Knox service look up response JSON string: " + jsonString);
+
+ ObjectMapper objectMapper = new ObjectMapper();
+
+ JsonNode rootNode = objectMapper.readTree(jsonString);
+ JsonNode topologyNode = rootNode.findValue("topology");
+ JsonNode servicesNode = topologyNode.get("services");
+ Iterator<JsonNode> services = servicesNode.getElements();
+ while (services.hasNext()) {
+ JsonNode service = services.next();
+ String serviceName = service.get("role").getValueAsText();
+ LOG.debug("Knox serviceName: " + serviceName);
+ if (serviceName.startsWith(serviceNameMatching)) {
+ serviceList.add(serviceName);
+ }
+ }
+ } else {
+ LOG.error("Got invalid REST response from: "+ knoxUrl + ", responsStatus: " + response.getStatus());
+ }
+
+ } else {
+ String msgDesc = "Unable to get a valid response for "
+ + "isFileChanged() call for KnoxUrl : [" + knoxUrl
+ + "] - got null response.";
+ LOG.error(msgDesc);
+ HadoopException hdpException = new HadoopException(msgDesc);
+ hdpException.generateResponseDataMap(false, msgDesc,
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ }
+
+ } finally {
+ if (response != null) {
+ response.close();
+ }
+ if (client != null) {
+ client.destroy();
+ }
+ }
+ } catch (HadoopException he) {
+ throw he;
+ } catch (Throwable t) {
+ String msgDesc = "Exception on REST call to KnoxUrl : " + knoxUrl + ".";
+ HadoopException hdpException = new HadoopException(msgDesc, t);
+ LOG.error(msgDesc, t);
+
+ hdpException.generateResponseDataMap(false,
+ BaseClient.getMessage(t), msgDesc + errMsg, null, null);
+ throw hdpException;
+
+ } finally {
+ }
+ return serviceList;
+ }
+
+ public static void main(String[] args) {
+
+ KnoxClient knoxClient = null;
+
+ if (args.length != 3) {
+ System.err.println("USAGE: java " + KnoxClient.class.getName()
+ + " knoxUrl userName password [sslConfigFileName]");
+ System.exit(1);
+ }
+
+ try {
+ knoxClient = new KnoxClient(args[0], args[1], args[2]);
+ List<String> topologyList = knoxClient.getTopologyList("");
+ if ((topologyList == null) || topologyList.isEmpty()) {
+ System.out.println("No knox topologies found");
+ } else {
+ for (String topology : topologyList) {
+ System.out.println("Found Topology: " + topology);
+ List<String> serviceList = knoxClient.getServiceList(topology, "");
+ if ((serviceList == null) || serviceList.isEmpty()) {
+ System.out.println("No services found for knox topology: " + topology);
+ } else {
+ for (String service : serviceList) {
+ System.out.println(" Found service for topology: " + service +", " + topology);
+ }
+ }
+ }
+ }
+ } finally {
+ }
+ }
+
+ public static HashMap<String, Object> testConnection(String dataSource,
+ HashMap<String, String> connectionProperties) {
+
+ List<String> strList = new ArrayList<String>();
+ String errMsg = " You can still save the repository and start creating "
+ + "policies, but you would not be able to use autocomplete for "
+ + "resource names. Check xa_portal.log for more info.";
+ boolean connectivityStatus = false;
+ HashMap<String, Object> responseData = new HashMap<String, Object>();
+
+ KnoxClient knoxClient = getKnoxClient(dataSource, connectionProperties);
+ strList = getKnoxResources(knoxClient, "", null);
+
+ if (strList != null && (strList.size() != 0)) {
+ connectivityStatus = true;
+ }
+
+ if (connectivityStatus) {
+ String successMsg = "TestConnection Successful";
+ BaseClient.generateResponseDataMap(connectivityStatus, successMsg, successMsg,
+ null, null, responseData);
+ } else {
+ String failureMsg = "Unable to retrieve any topologies/services using given parameters.";
+ BaseClient.generateResponseDataMap(connectivityStatus, failureMsg, failureMsg + errMsg,
+ null, null, responseData);
+ }
+
+ return responseData;
+ }
+
+ public static KnoxClient getKnoxClient(String dataSourceName,
+ Map<String, String> configMap) {
+ KnoxClient knoxClient = null;
+ LOG.debug("Getting knoxClient for datasource: " + dataSourceName
+ + "configMap: " + configMap);
+ String errMsg = " You can still save the repository and start creating "
+ + "policies, but you would not be able to use autocomplete for "
+ + "resource names. Check xa_portal.log for more info.";
+ if (configMap == null || configMap.isEmpty()) {
+ String msgDesc = "Could not connect as Connection ConfigMap is empty.";
+ LOG.error(msgDesc);
+ HadoopException hdpException = new HadoopException(msgDesc);
+ hdpException.generateResponseDataMap(false, msgDesc, msgDesc + errMsg, null,
+ null);
+ throw hdpException;
+ } else {
+ String knoxUrl = configMap.get("knox.url");
+ String knoxAdminUser = configMap.get("username");
+ String knoxAdminPassword = configMap.get("password");
+ knoxClient = new KnoxClient(knoxUrl, knoxAdminUser,
+ knoxAdminPassword);
+ }
+ return knoxClient;
+ }
+
+ public static List<String> getKnoxResources(final KnoxClient knoxClient,
+ String topologyName, String serviceName) {
+
+ List<String> resultList = new ArrayList<String>();
+ String errMsg = " You can still save the repository and start creating "
+ + "policies, but you would not be able to use autocomplete for "
+ + "resource names. Check xa_portal.log for more info.";
+
+ try {
+ if (knoxClient == null) {
+ // LOG.error("Unable to get knox resources: knoxClient is null");
+ // return new ArrayList<String>();
+ String msgDesc = "Unable to get knox resources: knoxClient is null.";
+ LOG.error(msgDesc);
+ HadoopException hdpException = new HadoopException(msgDesc);
+ hdpException.generateResponseDataMap(false, msgDesc, msgDesc + errMsg,
+ null, null);
+ throw hdpException;
+ }
+
+ final Callable<List<String>> callableObj;
+ if (serviceName != null) {
+ final String finalServiceNameMatching = serviceName.trim();
+ final String finalTopologyName = topologyName;
+ callableObj = new Callable<List<String>>() {
+ @Override
+ public List<String> call() {
+ return knoxClient.getServiceList(finalTopologyName,
+ finalServiceNameMatching);
+ }
+ };
+
+ } else {
+ final String finalTopologyNameMatching = (topologyName == null) ? ""
+ : topologyName.trim();
+ callableObj = new Callable<List<String>>() {
+ @Override
+ public List<String> call() {
+ return knoxClient
+ .getTopologyList(finalTopologyNameMatching);
+ }
+ };
+ }
+ resultList = timedTask(callableObj, 5, TimeUnit.SECONDS);
+
+ } catch (HadoopException he) {
+ throw he;
+ } catch (Exception e) {
+ String msgDesc = "Unable to get knox resources.";
+ LOG.error(msgDesc, e);
+ HadoopException hdpException = new HadoopException(msgDesc);
+
+ hdpException.generateResponseDataMap(false,
+ BaseClient.getMessage(e), msgDesc + errMsg, null, null);
+ throw hdpException;
+ }
+
+ return resultList;
+ }
+
+ public static <T> T timedTask(Callable<T> callableObj, long timeout,
+ TimeUnit timeUnit) throws Exception {
+ return callableObj.call();
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/org/apache/ranger/knox/client/KnoxClientTest.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/org/apache/ranger/knox/client/KnoxClientTest.java b/lookup-client/src/main/java/org/apache/ranger/knox/client/KnoxClientTest.java
new file mode 100644
index 0000000..dd6acbc
--- /dev/null
+++ b/lookup-client/src/main/java/org/apache/ranger/knox/client/KnoxClientTest.java
@@ -0,0 +1,42 @@
+/**
+ * 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.knox.client;
+
+public class KnoxClientTest {
+
+
+ /*
+ Sample curl calls to knox REST API to discover topologies
+ curl -ivk -u admin:admin-password https://localhost:8443/gateway/admin/api/v1/topologies
+ curl -ivk -u admin:admin-password https://localhost:8443/gateway/admin/api/v1/topologies/admin
+ */
+
+ public static void main(String[] args) {
+ System.out.println(System.getProperty("java.class.path"));
+ System.setProperty("javax.net.ssl.trustStore", "/tmp/cacertswithknox)");
+ String[] testArgs = {
+ "https://localhost:8443/gateway/admin/api/v1/topologies",
+ "admin",
+ "admin-password"
+ };
+ KnoxClient.main(testArgs);
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/org/apache/ranger/knox/client/RangerConstants.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/org/apache/ranger/knox/client/RangerConstants.java b/lookup-client/src/main/java/org/apache/ranger/knox/client/RangerConstants.java
new file mode 100644
index 0000000..763ce75
--- /dev/null
+++ b/lookup-client/src/main/java/org/apache/ranger/knox/client/RangerConstants.java
@@ -0,0 +1,42 @@
+/**
+ * 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.knox.client;
+
+public class RangerConstants {
+
+ // xasecure 2-way ssl configuration
+
+ public static final String RANGER_KNOX_CLIENT_KEY_FILE = "xasecure.knoxclient.ssl.keystore";
+ public static final String RANGER_KNOX_CLIENT_KEY_FILE_PASSWORD = "xasecure.knoxclien.tssl.keystore.password";
+ public static final String RANGER_KNOX_CLIENT_KEY_FILE_TYPE = "xasecure.knoxclient.ssl.keystore.type";
+
+ public static final String RANGER_KNOX_CLIENT_KEY_FILE_TYPE_DEFAULT = "jks";
+
+ public static final String RANGER_KNOX_CLIENT_TRUSTSTORE_FILE = "xasecure.knoxclient.ssl.truststore";
+ public static final String RANGER_KNOX_CLIENT_TRUSTSTORE_FILE_PASSWORD = "xasecure.knoxclient.ssl.truststore.password";
+ public static final String RANGER_KNOX_CLIENT_TRUSTSTORE_FILE_TYPE = "xasecure.knoxclient.ssl.truststore.type";
+
+ public static final String RANGER_KNOX_CLIENT_TRUSTSTORE_FILE_TYPE_DEFAULT = "jks";
+
+
+ public static final String RANGER_SSL_KEYMANAGER_ALGO_TYPE = "SunX509" ;
+ public static final String RANGER_SSL_TRUSTMANAGER_ALGO_TYPE = "SunX509" ;
+ public static final String RANGER_SSL_CONTEXT_ALGO_TYPE = "SSL" ;
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/org/apache/ranger/storm/client/StormClient.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/org/apache/ranger/storm/client/StormClient.java b/lookup-client/src/main/java/org/apache/ranger/storm/client/StormClient.java
new file mode 100644
index 0000000..db736b0
--- /dev/null
+++ b/lookup-client/src/main/java/org/apache/ranger/storm/client/StormClient.java
@@ -0,0 +1,395 @@
+/*
+ * 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.storm.client;
+
+import java.io.IOException;
+import java.security.PrivilegedAction;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.security.auth.Subject;
+import javax.security.auth.login.AppConfigurationEntry;
+import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag;
+import javax.security.auth.login.LoginContext;
+import javax.security.auth.login.LoginException;
+
+import org.apache.commons.io.FilenameUtils;
+import org.apache.hadoop.security.KrbPasswordSaverLoginModule;
+import org.apache.hadoop.security.authentication.util.KerberosUtil;
+import org.apache.log4j.Logger;
+import org.apache.ranger.hadoop.client.config.BaseClient;
+import org.apache.ranger.hadoop.client.exceptions.HadoopException;
+import org.apache.ranger.storm.client.json.model.Topology;
+import org.apache.ranger.storm.client.json.model.TopologyListResponse;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.sun.jersey.api.client.Client;
+import com.sun.jersey.api.client.ClientResponse;
+import com.sun.jersey.api.client.WebResource;
+
+public class StormClient {
+
+ public static final Logger LOG = Logger.getLogger(StormClient.class) ;
+
+ private static final String EXPECTED_MIME_TYPE = "application/json";
+
+ private static final String TOPOLOGY_LIST_API_ENDPOINT = "/api/v1/topology/summary" ;
+
+
+ String stormUIUrl;
+ String userName;
+ String password;
+
+ public StormClient(String aStormUIUrl, String aUserName, String aPassword) {
+
+ this.stormUIUrl = aStormUIUrl;
+ this.userName = aUserName ;
+ this.password = aPassword;
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Storm Client is build with url [" + aStormUIUrl + "] user: [" + aUserName + "], password: [" + "" + "]");
+ }
+
+ }
+
+ public List<String> getTopologyList(final String topologyNameMatching) {
+
+ LOG.debug("Getting Storm topology list for topologyNameMatching : " +
+ topologyNameMatching);
+ final String errMsg = " You can still save the repository and start creating "
+ + "policies, but you would not be able to use autocomplete for "
+ + "resource names. Check xa_portal.log for more info.";
+
+ List<String> ret = new ArrayList<String>();
+
+ PrivilegedAction<ArrayList<String>> topologyListGetter = new PrivilegedAction<ArrayList<String>>() {
+ @Override
+ public ArrayList<String> run() {
+
+ ArrayList<String> lret = new ArrayList<String>();
+
+ String url = stormUIUrl + TOPOLOGY_LIST_API_ENDPOINT ;
+
+ Client client = null ;
+ ClientResponse response = null ;
+
+ try {
+ client = Client.create() ;
+
+ WebResource webResource = client.resource(url);
+
+ response = webResource.accept(EXPECTED_MIME_TYPE)
+ .get(ClientResponse.class);
+
+ LOG.debug("getTopologyList():calling " + url);
+
+ if (response != null) {
+ LOG.debug("getTopologyList():response.getStatus()= " + response.getStatus());
+ if (response.getStatus() == 200) {
+ String jsonString = response.getEntity(String.class);
+ Gson gson = new GsonBuilder().setPrettyPrinting().create();
+ TopologyListResponse topologyListResponse = gson.fromJson(jsonString, TopologyListResponse.class);
+ if (topologyListResponse != null) {
+ if (topologyListResponse.getTopologyList() != null) {
+ for(Topology topology : topologyListResponse.getTopologyList()) {
+ String toplogyName = topology.getName() ;
+ LOG.debug("getTopologyList():Found topology " + toplogyName);
+ LOG.debug("getTopologyList():topology Name=[" + topology.getName() + "], topologyNameMatching=[" + topologyNameMatching + "]");
+ if (toplogyName != null) {
+ if (topologyNameMatching == null || topologyNameMatching.isEmpty() || FilenameUtils.wildcardMatch(topology.getName(), topologyNameMatching + "*")) {
+ LOG.debug("getTopologyList():Adding topology " + toplogyName);
+ lret.add(toplogyName) ;
+ }
+ }
+ }
+ }
+ }
+ } else{
+ LOG.info("getTopologyList():response.getStatus()= " + response.getStatus() + " for URL " + url + ", so returning null list");
+ String jsonString = response.getEntity(String.class);
+ LOG.info(jsonString);
+ lret = null;
+ }
+ } else {
+ String msgDesc = "Unable to get a valid response for "
+ + "expected mime type : [" + EXPECTED_MIME_TYPE
+ + "] URL : " + url + " - got null response.";
+ LOG.error(msgDesc);
+ HadoopException hdpException = new HadoopException(msgDesc);
+ hdpException.generateResponseDataMap(false, msgDesc,
+ msgDesc + errMsg, null, null);
+ throw hdpException;
+ }
+ } catch (HadoopException he) {
+ throw he;
+ } catch (Throwable t) {
+ String msgDesc = "Exception while getting Storm TopologyList."
+ + " URL : " + url;
+ HadoopException hdpException = new HadoopException(msgDesc,
+ t);
+ LOG.error(msgDesc, t);
+
+ hdpException.generateResponseDataMap(false,
+ BaseClient.getMessage(t), msgDesc + errMsg, null,
+ null);
+ throw hdpException;
+
+ } finally {
+ if (response != null) {
+ response.close();
+ }
+
+ if (client != null) {
+ client.destroy();
+ }
+
+ }
+ return lret ;
+ }
+ } ;
+
+ try {
+ ret = executeUnderKerberos(this.userName, this.password, topologyListGetter) ;
+ } catch (IOException e) {
+ LOG.error("Unable to get Topology list from [" + stormUIUrl + "]", e) ;
+ }
+
+ return ret;
+ }
+
+ public static <T> T executeUnderKerberos(String userName, String password,
+ PrivilegedAction<T> action) throws IOException {
+
+ final String errMsg = " You can still save the repository and start creating "
+ + "policies, but you would not be able to use autocomplete for "
+ + "resource names. Check xa_portal.log for more info.";
+ class MySecureClientLoginConfiguration extends
+ javax.security.auth.login.Configuration {
+
+ private String userName;
+ private String password ;
+
+ MySecureClientLoginConfiguration(String aUserName,
+ String password) {
+ this.userName = aUserName;
+ this.password = password;
+ }
+
+ @Override
+ public AppConfigurationEntry[] getAppConfigurationEntry(
+ String appName) {
+
+ Map<String, String> kerberosOptions = new HashMap<String, String>();
+ kerberosOptions.put("principal", this.userName);
+ kerberosOptions.put("debug", "true");
+ kerberosOptions.put("useKeyTab", "false");
+ kerberosOptions.put(KrbPasswordSaverLoginModule.USERNAME_PARAM, this.userName);
+ kerberosOptions.put(KrbPasswordSaverLoginModule.PASSWORD_PARAM, this.password);
+ kerberosOptions.put("doNotPrompt", "false");
+ kerberosOptions.put("useFirstPass", "true");
+ kerberosOptions.put("tryFirstPass", "false");
+ kerberosOptions.put("storeKey", "true");
+ kerberosOptions.put("refreshKrb5Config", "true");
+
+ AppConfigurationEntry KEYTAB_KERBEROS_LOGIN = null;
+ AppConfigurationEntry KERBEROS_PWD_SAVER = null;
+ try {
+ KEYTAB_KERBEROS_LOGIN = new AppConfigurationEntry(
+ KerberosUtil.getKrb5LoginModuleName(),
+ AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
+ kerberosOptions);
+ KERBEROS_PWD_SAVER = new AppConfigurationEntry(KrbPasswordSaverLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, kerberosOptions);
+
+ } catch (IllegalArgumentException e) {
+ String msgDesc = "executeUnderKerberos: Exception while getting Storm TopologyList.";
+ HadoopException hdpException = new HadoopException(msgDesc,
+ e);
+ LOG.error(msgDesc, e);
+
+ hdpException.generateResponseDataMap(false,
+ BaseClient.getMessage(e), msgDesc + errMsg, null,
+ null);
+ throw hdpException;
+ }
+
+ LOG.debug("getAppConfigurationEntry():" + kerberosOptions.get("principal"));
+
+ return new AppConfigurationEntry[] { KERBEROS_PWD_SAVER, KEYTAB_KERBEROS_LOGIN };
+ }
+
+ };
+
+ T ret = null;
+
+ Subject subject = null;
+ LoginContext loginContext = null;
+
+ try {
+ subject = new Subject();
+ LOG.debug("executeUnderKerberos():user=" + userName + ",pass=");
+ LOG.debug("executeUnderKerberos():Creating config..");
+ MySecureClientLoginConfiguration loginConf = new MySecureClientLoginConfiguration(
+ userName, password);
+ LOG.debug("executeUnderKerberos():Creating Context..");
+ loginContext = new LoginContext("hadoop-keytab-kerberos", subject,
+ null, loginConf);
+
+ LOG.debug("executeUnderKerberos():Logging in..");
+ loginContext.login();
+
+ Subject loginSubj = loginContext.getSubject();
+
+ if (loginSubj != null) {
+ ret = Subject.doAs(loginSubj, action);
+ }
+ } catch (LoginException le) {
+ String msgDesc = "executeUnderKerberos: Login failure using given"
+ + " configuration parameters, username : `" + userName + "`.";
+ HadoopException hdpException = new HadoopException(msgDesc, le);
+ LOG.error(msgDesc, le);
+
+ hdpException.generateResponseDataMap(false,
+ BaseClient.getMessage(le), msgDesc + errMsg, null, null);
+ throw hdpException;
+ } catch (SecurityException se) {
+ String msgDesc = "executeUnderKerberos: Exception while getting Storm TopologyList.";
+ HadoopException hdpException = new HadoopException(msgDesc, se);
+ LOG.error(msgDesc, se);
+
+ hdpException.generateResponseDataMap(false,
+ BaseClient.getMessage(se), msgDesc + errMsg, null, null);
+ throw hdpException;
+
+ } finally {
+ if (loginContext != null) {
+ if (subject != null) {
+ try {
+ loginContext.logout();
+ } catch (LoginException e) {
+ throw new IOException("logout failure", e);
+ }
+ }
+ }
+ }
+
+ return ret;
+ }
+
+ public static HashMap<String, Object> testConnection(String dataSource,
+ HashMap<String, String> connectionProperties) {
+
+ List<String> strList = new ArrayList<String>();
+ String errMsg = " You can still save the repository and start creating "
+ + "policies, but you would not be able to use autocomplete for "
+ + "resource names. Check xa_portal.log for more info.";
+ boolean connectivityStatus = false;
+ HashMap<String, Object> responseData = new HashMap<String, Object>();
+
+ StormClient stormClient = getStormClient(dataSource,
+ connectionProperties);
+ strList = getStormResources(stormClient, "");
+
+ if (strList != null) {
+ connectivityStatus = true;
+ }
+
+ if (connectivityStatus) {
+ String successMsg = "TestConnection Successful";
+ BaseClient.generateResponseDataMap(connectivityStatus, successMsg,
+ successMsg, null, null, responseData);
+ } else {
+ String failureMsg = "Unable to retrieve any topologies using given parameters.";
+ BaseClient.generateResponseDataMap(connectivityStatus, failureMsg,
+ failureMsg + errMsg, null, null, responseData);
+ }
+
+ return responseData;
+ }
+
+ public static StormClient getStormClient(String dataSourceName,
+ Map<String, String> configMap) {
+ StormClient stormClient = null;
+ LOG.debug("Getting StormClient for datasource: " + dataSourceName
+ + "configMap: " + configMap);
+ String errMsg = " You can still save the repository and start creating "
+ + "policies, but you would not be able to use autocomplete for "
+ + "resource names. Check xa_portal.log for more info.";
+ if (configMap == null || configMap.isEmpty()) {
+ String msgDesc = "Could not connect as Connection ConfigMap is empty.";
+ LOG.error(msgDesc);
+ HadoopException hdpException = new HadoopException(msgDesc);
+ hdpException.generateResponseDataMap(false, msgDesc, msgDesc
+ + errMsg, null, null);
+ throw hdpException;
+ } else {
+ String stormUrl = configMap.get("nimbus.url");
+ String stormAdminUser = configMap.get("username");
+ String stormAdminPassword = configMap.get("password");
+ stormClient = new StormClient(stormUrl, stormAdminUser,
+ stormAdminPassword);
+ }
+ return stormClient;
+ }
+
+ public static List<String> getStormResources(final StormClient stormClient,
+ String topologyName) {
+
+ List<String> resultList = new ArrayList<String>();
+ String errMsg = " You can still save the repository and start creating "
+ + "policies, but you would not be able to use autocomplete for "
+ + "resource names. Check xa_portal.log for more info.";
+
+ try {
+ if (stormClient == null) {
+ String msgDesc = "Unable to get Storm resources: StormClient is null.";
+ LOG.error(msgDesc);
+ HadoopException hdpException = new HadoopException(msgDesc);
+ hdpException.generateResponseDataMap(false, msgDesc, msgDesc
+ + errMsg, null, null);
+ throw hdpException;
+ }
+
+ if (topologyName != null) {
+ String finalTopologyNameMatching = (topologyName == null) ? ""
+ : topologyName.trim();
+ resultList = stormClient
+ .getTopologyList(finalTopologyNameMatching);
+ if (resultList != null) {
+ LOG.debug("Returning list of " + resultList.size() + " topologies");
+ }
+ }
+ } catch (HadoopException he) {
+ throw he;
+ } catch (Exception e) {
+ String msgDesc = "getStormResources: Unable to get Storm resources.";
+ LOG.error(msgDesc, e);
+ HadoopException hdpException = new HadoopException(msgDesc);
+
+ hdpException.generateResponseDataMap(false,
+ BaseClient.getMessage(e), msgDesc + errMsg, null, null);
+ throw hdpException;
+ }
+ return resultList;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/org/apache/ranger/storm/client/json/model/Topology.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/org/apache/ranger/storm/client/json/model/Topology.java b/lookup-client/src/main/java/org/apache/ranger/storm/client/json/model/Topology.java
new file mode 100644
index 0000000..4abf1e7
--- /dev/null
+++ b/lookup-client/src/main/java/org/apache/ranger/storm/client/json/model/Topology.java
@@ -0,0 +1,47 @@
+/*
+ * 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.storm.client.json.model;
+
+public class Topology {
+ private String id ;
+ private String name ;
+ private String status ;
+
+ public String getId() {
+ return id;
+ }
+ public void setId(String id) {
+ this.id = id;
+ }
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+ public String getStatus() {
+ return status;
+ }
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/org/apache/ranger/storm/client/json/model/TopologyListResponse.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/org/apache/ranger/storm/client/json/model/TopologyListResponse.java b/lookup-client/src/main/java/org/apache/ranger/storm/client/json/model/TopologyListResponse.java
new file mode 100644
index 0000000..14d641d
--- /dev/null
+++ b/lookup-client/src/main/java/org/apache/ranger/storm/client/json/model/TopologyListResponse.java
@@ -0,0 +1,38 @@
+/*
+ * 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.storm.client.json.model;
+
+import java.util.List;
+
+import com.google.gson.annotations.SerializedName;
+
+public class TopologyListResponse {
+ @SerializedName("topologies")
+ private List<Topology> topologyList;
+
+ public List<Topology> getTopologyList() {
+ return topologyList;
+ }
+
+ public void setTopologyList(List<Topology> topologyList) {
+ this.topologyList = topologyList;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/scripts/run-audit-test.sh
----------------------------------------------------------------------
diff --git a/lookup-client/src/scripts/run-audit-test.sh b/lookup-client/src/scripts/run-audit-test.sh
index 698459f..9dd00eb 100755
--- a/lookup-client/src/scripts/run-audit-test.sh
+++ b/lookup-client/src/scripts/run-audit-test.sh
@@ -27,4 +27,4 @@ done
export cp
-java -Xmx1024M -Xms1024M -cp "${cp}" com.xasecure.audit.test.TestEvents $*
+java -Xmx1024M -Xms1024M -cp "${cp}" org.apache.ranger.audit.test.TestEvents $*
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/scripts/run-hadoop-client.sh
----------------------------------------------------------------------
diff --git a/lookup-client/src/scripts/run-hadoop-client.sh b/lookup-client/src/scripts/run-hadoop-client.sh
index afb4904..03aff46 100644
--- a/lookup-client/src/scripts/run-hadoop-client.sh
+++ b/lookup-client/src/scripts/run-hadoop-client.sh
@@ -17,7 +17,7 @@
case $# in
4 )
- java -cp "./dist/*:./lib/hadoop/*:./conf:." com.xasecure.hadoop.client.HadoopFSTester "${1}" "${2}" "${3}" "${4}" ;;
+ java -cp "./dist/*:./lib/hadoop/*:./conf:." org.apache.ranger.hadoop.client.HadoopFSTester "${1}" "${2}" "${3}" "${4}" ;;
* )
- java -cp "./dist/*:./lib/hadoop/*:./conf:." com.xasecure.hadoop.client.HadoopFSTester ;;
+ java -cp "./dist/*:./lib/hadoop/*:./conf:." org.apache.ranger.hadoop.client.HadoopFSTester ;;
esac
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/scripts/run-hbase-client.sh
----------------------------------------------------------------------
diff --git a/lookup-client/src/scripts/run-hbase-client.sh b/lookup-client/src/scripts/run-hbase-client.sh
index 3790235..1c9cdb4 100644
--- a/lookup-client/src/scripts/run-hbase-client.sh
+++ b/lookup-client/src/scripts/run-hbase-client.sh
@@ -19,11 +19,11 @@ cp="./dist/*:./conf/:.:./lib/hadoop/*:./lib/hive/*:./lib/hbase/*"
case $# in
2 )
-java ${JOPTS} -cp "${cp}" com.xasecure.hbase.client.HBaseClientTester "${1}" "${2}" ;;
+java ${JOPTS} -cp "${cp}" org.apache.ranger.hbase.client.HBaseClientTester "${1}" "${2}" ;;
3 )
-java ${JOPTS} -cp "${cp}" com.xasecure.hbase.client.HBaseClientTester "${1}" "${2}" "${3}" ;;
+java ${JOPTS} -cp "${cp}" org.apache.ranger.hbase.client.HBaseClientTester "${1}" "${2}" "${3}" ;;
4 )
-java ${JOPTS} -cp "${cp}" com.xasecure.hbase.client.HBaseClientTester "${1}" "${2}" "${3}" "${4}" ;;
+java ${JOPTS} -cp "${cp}" org.apache.ranger.hbase.client.HBaseClientTester "${1}" "${2}" "${3}" "${4}" ;;
* )
-java ${JOPTS} -cp "${cp}" com.xasecure.hbase.client.HBaseClientTester;;
+java ${JOPTS} -cp "${cp}" org.apache.ranger.hbase.client.HBaseClientTester;;
esac
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/scripts/run-hive-client.sh
----------------------------------------------------------------------
diff --git a/lookup-client/src/scripts/run-hive-client.sh b/lookup-client/src/scripts/run-hive-client.sh
index f50bbd6..4e80d10 100644
--- a/lookup-client/src/scripts/run-hive-client.sh
+++ b/lookup-client/src/scripts/run-hive-client.sh
@@ -17,13 +17,13 @@
case $# in
2 )
- java -cp "./dist/*:./lib/hadoop/*:./lib/hive/*:./conf:." com.xasecure.hive.client.HiveClientTester "$1" "${2}" ;;
+ java -cp "./dist/*:./lib/hadoop/*:./lib/hive/*:./conf:." org.apache.ranger.hive.client.HiveClientTester "$1" "${2}" ;;
3 )
- java -cp "./dist/*:./lib/hadoop/*:./lib/hive/*:./conf:." com.xasecure.hive.client.HiveClientTester "$1" "${2}" "${3}" ;;
+ java -cp "./dist/*:./lib/hadoop/*:./lib/hive/*:./conf:." org.apache.ranger.hive.client.HiveClientTester "$1" "${2}" "${3}" ;;
4 )
- java -cp "./dist/*:./lib/hadoop/*:./lib/hive/*:./conf:." com.xasecure.hive.client.HiveClientTester "$1" "${2}" "${3}" "${4}" ;;
+ java -cp "./dist/*:./lib/hadoop/*:./lib/hive/*:./conf:." org.apache.ranger.hive.client.HiveClientTester "$1" "${2}" "${3}" "${4}" ;;
5 )
- java -cp "./dist/*:./lib/hadoop/*:./lib/hive/*:./conf:." com.xasecure.hive.client.HiveClientTester "$1" "${2}" "${3}" "${4}" "${5}" ;;
+ java -cp "./dist/*:./lib/hadoop/*:./lib/hive/*:./conf:." org.apache.ranger.hive.client.HiveClientTester "$1" "${2}" "${3}" "${4}" "${5}" ;;
* )
- java -cp "./dist/*:./lib/hadoop/*:./lib/hive/*:./conf:." com.xasecure.hive.client.HiveClientTester ;;
+ java -cp "./dist/*:./lib/hadoop/*:./lib/hive/*:./conf:." org.apache.ranger.hive.client.HiveClientTester ;;
esac
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/.gitignore
----------------------------------------------------------------------
diff --git a/security-admin/.gitignore b/security-admin/.gitignore
index 0f63015..de3a426 100644
--- a/security-admin/.gitignore
+++ b/security-admin/.gitignore
@@ -1,2 +1,3 @@
/target/
/bin/
+/bin/
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/.settings/org.eclipse.wst.common.component
----------------------------------------------------------------------
diff --git a/security-admin/.settings/org.eclipse.wst.common.component b/security-admin/.settings/org.eclipse.wst.common.component
index 5689098..4e51866 100644
--- a/security-admin/.settings/org.eclipse.wst.common.component
+++ b/security-admin/.settings/org.eclipse.wst.common.component
@@ -4,7 +4,6 @@
<wb-resource deploy-path="/" source-path="/src/main/webapp" tag="defaultRootSource"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
- <wb-resource deploy-path="/WEB-INF/classes" source-path="/src/test/java"/>
<dependent-module archiveName="lookup-client-0.4.0.jar" deploy-path="/WEB-INF/lib" handle="module:/resource/lookup-client/lookup-client">
<dependency-type>uses</dependency-type>
</dependent-module>
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/scripts/setup.sh
----------------------------------------------------------------------
diff --git a/security-admin/scripts/setup.sh b/security-admin/scripts/setup.sh
index dc5dbd3..bc241e2 100755
--- a/security-admin/scripts/setup.sh
+++ b/security-admin/scripts/setup.sh
@@ -792,7 +792,7 @@ update_properties() {
then
mkdir -p `dirname "${keystore}"`
- $JAVA_HOME/bin/java -cp "cred/lib/*" com.hortonworks.credentialapi.buildks create "$db_password_alias" -value "$db_password" -provider jceks://file$keystore
+ $JAVA_HOME/bin/java -cp "cred/lib/*" org.apache.ranger.credentialapi.buildks create "$db_password_alias" -value "$db_password" -provider jceks://file$keystore
propertyName=xaDB.jdbc.credential.alias
newPropertyValue="${db_password_alias}"
@@ -829,7 +829,7 @@ update_properties() {
if [ "${keystore}" != "" ]
then
- $JAVA_HOME/bin/java -cp "cred/lib/*" com.hortonworks.credentialapi.buildks create "$audit_db_password_alias" -value "$audit_db_password" -provider jceks://file$keystore
+ $JAVA_HOME/bin/java -cp "cred/lib/*" org.apache.ranger.credentialapi.buildks create "$audit_db_password_alias" -value "$audit_db_password" -provider jceks://file$keystore
propertyName=auditDB.jdbc.credential.alias
newPropertyValue="${audit_db_password_alias}"
@@ -1239,10 +1239,10 @@ execute_java_patches(){
dt=`date '+%s'`
tempFile=/tmp/sql_${dt}_$$.sql
mysqlexec="${SQL_COMMAND_INVOKER} -u ${db_root_user} --password="${db_root_password}" -h ${DB_HOST} ${db_name}"
- javaFiles=`ls -1 $app_home/WEB-INF/classes/com/xasecure/patch/Patch*.class 2> /dev/null | awk -F/ '{ print $NF }' | awk -F_J '{ print $2, $0 }' | sort -k1 -n | awk '{ printf("%s\n",$2) ; }'`
+ javaFiles=`ls -1 $app_home/WEB-INF/classes/org/apache/ranger/patch/Patch*.class 2> /dev/null | awk -F/ '{ print $NF }' | awk -F_J '{ print $2, $0 }' | sort -k1 -n | awk '{ printf("%s\n",$2) ; }'`
for javaPatch in ${javaFiles}
do
- if test -f "$app_home/WEB-INF/classes/com/xasecure/patch/$javaPatch"; then
+ if test -f "$app_home/WEB-INF/classes/org/apache/ranger/patch/$javaPatch"; then
className=$(basename "$javaPatch" .class)
version=`echo ${className} | awk -F'_' '{ print $2 }'`
if [ "${version}" != "" ]
@@ -1252,7 +1252,7 @@ execute_java_patches(){
if [ ${c} -eq 0 ]
then
log "[I] patch ${javaPatch} is being applied..";
- msg=`$JAVA_HOME/bin/java -cp "$app_home/WEB-INF/classes/conf:$app_home/WEB-INF/classes/lib/*:$app_home/WEB-INF/:$app_home/META-INF/:$app_home/WEB-INF/lib/*:$app_home/WEB-INF/classes/:$app_home/WEB-INF/classes/META-INF/" com.xasecure.patch.${className}`
+ msg=`$JAVA_HOME/bin/java -cp "$app_home/WEB-INF/classes/conf:$app_home/WEB-INF/classes/lib/*:$app_home/WEB-INF/:$app_home/META-INF/:$app_home/WEB-INF/lib/*:$app_home/WEB-INF/classes/:$app_home/WEB-INF/classes/META-INF/" org.apache.ranger.patch.${className}`
check_ret_status $? "Unable to apply patch:$javaPatch. $msg"
touch ${tempFile}
echo >> ${tempFile}
@@ -1272,10 +1272,10 @@ execute_java_patches(){
then
dt=`date '+%s'`
tempFile=/tmp/sql_${dt}_$$.sql
- javaFiles=`ls -1 $app_home/WEB-INF/classes/com/xasecure/patch/Patch*.class 2> /dev/null | awk -F/ '{ print $NF }' | awk -F_J '{ print $2, $0 }' | sort -k1 -n | awk '{ printf("%s\n",$2) ; }'`
+ javaFiles=`ls -1 $app_home/WEB-INF/classes/org/apache/ranger/patch/Patch*.class 2> /dev/null | awk -F/ '{ print $NF }' | awk -F_J '{ print $2, $0 }' | sort -k1 -n | awk '{ printf("%s\n",$2) ; }'`
for javaPatch in ${javaFiles}
do
- if test -f "$app_home/WEB-INF/classes/com/xasecure/patch/$javaPatch"; then
+ if test -f "$app_home/WEB-INF/classes/org/apache/ranger/patch/$javaPatch"; then
className=$(basename "$javaPatch" .class)
version=`echo ${className} | awk -F'_' '{ print $2 }'`
if [ "${version}" != "" ]
@@ -1285,7 +1285,7 @@ execute_java_patches(){
if test "${result2#*$version}" == "$result2"
then
log "[I] patch ${javaPatch} is being applied..";
- msg=`$JAVA_HOME/bin/java -cp "$app_home/WEB-INF/classes/conf:$app_home/WEB-INF/classes/lib/*:$app_home/WEB-INF/:$app_home/META-INF/:$app_home/WEB-INF/lib/*:$app_home/WEB-INF/classes/:$app_home/WEB-INF/classes/META-INF/" com.xasecure.patch.${className}`
+ msg=`$JAVA_HOME/bin/java -cp "$app_home/WEB-INF/classes/conf:$app_home/WEB-INF/classes/lib/*:$app_home/WEB-INF/:$app_home/META-INF/:$app_home/WEB-INF/lib/*:$app_home/WEB-INF/classes/:$app_home/WEB-INF/classes/META-INF/" org.apache.ranger.patch.${className}`
check_ret_status $? "Unable to apply patch:$javaPatch. $msg"
touch ${tempFile}
echo >> ${tempFile}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/bin/ranger_install.py
----------------------------------------------------------------------
diff --git a/security-admin/src/bin/ranger_install.py b/security-admin/src/bin/ranger_install.py
index 6b1e324..75b5931 100644
--- a/security-admin/src/bin/ranger_install.py
+++ b/security-admin/src/bin/ranger_install.py
@@ -1021,13 +1021,13 @@ def call_keystore(libpath,aliasKey,aliasValue , filepath,getorcreate):
finalLibPath = libpath.replace('\\','/').replace('//','/')
finalFilePath = 'jceks://file/'+filepath.replace('\\','/').replace('//','/')
if getorcreate == 'create':
- commandtorun = ['java', '-cp', finalLibPath, 'com.hortonworks.credentialapi.buildks' ,'create', aliasKey, '-value', aliasValue, '-provider',finalFilePath]
+ commandtorun = ['java', '-cp', finalLibPath, 'org.apache.ranger.credentialapi.buildks' ,'create', aliasKey, '-value', aliasValue, '-provider',finalFilePath]
p = Popen(commandtorun,stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, error = p.communicate()
statuscode = p.returncode
return statuscode
elif getorcreate == 'get':
- commandtorun = ['java', '-cp', finalLibPath, 'com.hortonworks.credentialapi.buildks' ,'get', aliasKey, '-provider',finalFilePath]
+ commandtorun = ['java', '-cp', finalLibPath, 'org.apache.ranger.credentialapi.buildks' ,'get', aliasKey, '-provider',finalFilePath]
p = Popen(commandtorun,stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, error = p.communicate()
statuscode = p.returncode
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/bin/ranger_usersync.py
----------------------------------------------------------------------
diff --git a/security-admin/src/bin/ranger_usersync.py b/security-admin/src/bin/ranger_usersync.py
index dcf50ef..4309589 100644
--- a/security-admin/src/bin/ranger_usersync.py
+++ b/security-admin/src/bin/ranger_usersync.py
@@ -101,7 +101,7 @@ if service_entry:
init_variables()
jdk_options = get_jdk_options()
class_path = get_ranger_classpath()
- java_class = 'com.xasecure.authentication.UnixAuthenticationService'
+ java_class = 'org.apache.ranger.authentication.UnixAuthenticationService'
class_arguments = ''
dom = getDOMImplementation()
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/bin/service_start.py
----------------------------------------------------------------------
diff --git a/security-admin/src/bin/service_start.py b/security-admin/src/bin/service_start.py
index 446bc54..ad2caa2 100644
--- a/security-admin/src/bin/service_start.py
+++ b/security-admin/src/bin/service_start.py
@@ -32,7 +32,7 @@ if service_entry:
ranger_install.run_setup(cmd)
jdk_options = ranger_install.get_jdk_options()
class_path = ranger_install.get_ranger_classpath()
- java_class = 'com.xasecure.server.tomcat.EmbededServer'
+ java_class = 'org.apache.ranger.server.tomcat.EmbededServer'
class_arguments = ''
from xml.dom.minidom import getDOMImplementation
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/authentication/unix/jaas/RoleUserAuthorityGranter.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/authentication/unix/jaas/RoleUserAuthorityGranter.java b/security-admin/src/main/java/com/xasecure/authentication/unix/jaas/RoleUserAuthorityGranter.java
deleted file mode 100644
index b025568..0000000
--- a/security-admin/src/main/java/com/xasecure/authentication/unix/jaas/RoleUserAuthorityGranter.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * 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 com.xasecure.authentication.unix.jaas;
-
-import java.security.Principal;
-import java.util.Collections;
-import java.util.Set;
-
-import org.springframework.security.authentication.jaas.AuthorityGranter;
-
-public class RoleUserAuthorityGranter implements AuthorityGranter {
-
- @Override
- public Set<String> grant(Principal principal) {
- if (principal instanceof UnixGroupPrincipal) {
- Collections.singleton(principal.getName());
- }
- else {
- Collections.singleton("ROLE_USER");
- }
- return null;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/biz/AssetConnectionMgr.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/biz/AssetConnectionMgr.java b/security-admin/src/main/java/com/xasecure/biz/AssetConnectionMgr.java
deleted file mode 100644
index 7df1321..0000000
--- a/security-admin/src/main/java/com/xasecure/biz/AssetConnectionMgr.java
+++ /dev/null
@@ -1,425 +0,0 @@
-/*
- * 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 com.xasecure.biz;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.Callable;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Component;
-
-import com.xasecure.common.AppConstants;
-import com.xasecure.common.JSONUtil;
-import com.xasecure.common.StringUtil;
-import com.xasecure.common.TimedEventUtil;
-import com.xasecure.db.XADaoManager;
-import com.xasecure.entity.XXAsset;
-import com.xasecure.hadoop.client.HadoopFS;
-import com.xasecure.hbase.client.HBaseClient;
-import com.xasecure.hive.client.HiveClient;
-import com.xasecure.knox.client.KnoxClient;
-import com.xasecure.storm.client.StormClient;
-import com.xasecure.service.XAssetService;
-import com.xasecure.view.VXAsset;
-
-@Component
-@Scope("singleton")
-public class AssetConnectionMgr {
-
- private static Logger logger = Logger.getLogger(AssetConnectionMgr.class);
-
- protected HashMap<String, HadoopFS> hadoopConnectionCache;
- protected HashMap<String, HiveClient> hiveConnectionCache;
- protected HashMap<String, HBaseClient> hbaseConnectionCache;
-
- protected HashMap<String, Boolean> repoConnectStatusMap;
-
- @Autowired
- protected JSONUtil jsonUtil;
-
- @Autowired
- protected StringUtil stringUtil;
-
- @Autowired
- protected XADaoManager xADaoManager;
-
- @Autowired
- XAssetService xAssetService;
-
- public AssetConnectionMgr(){
- hadoopConnectionCache = new HashMap<String, HadoopFS>();
- hiveConnectionCache = new HashMap<String, HiveClient>();
- hbaseConnectionCache = new HashMap<String, HBaseClient>();
- repoConnectStatusMap = new HashMap<String, Boolean>();
- }
-
- public HadoopFS getHadoopConnection(final String dataSourceName) {
- HadoopFS hadoopFS = null;
- XXAsset asset = xADaoManager.getXXAsset().findByAssetName(dataSourceName);
- if (asset != null) {
- // get it from the cache
- synchronized (hadoopConnectionCache) {
- hadoopFS = hadoopConnectionCache.get(asset.getName());
- if (hadoopFS == null) {
- // if it doesn't exist in cache then create the connection
- String config = asset.getConfig();
- if(!stringUtil.isEmpty(config)){
- config=xAssetService.getConfigWithDecryptedPassword(config);
- }
- // FIXME remove this once we start using putting config for
- // default asset "hadoopdev" (should come from properties)
- if (stringUtil.isEmpty(config)
- && asset.getName().equals("hadoopdev")) {
-
- final Callable<HadoopFS> connectHDFS = new Callable<HadoopFS>() {
- @Override
- public HadoopFS call() throws Exception {
- return new HadoopFS(dataSourceName);
- }
- };
-
- try {
- hadoopFS = TimedEventUtil.timedTask(connectHDFS, 10, TimeUnit.SECONDS);
- } catch(Exception e){
- logger.error("Error establishing connection for HDFS repository : "
- + dataSourceName, e);
- }
-
- } else if (!stringUtil.isEmpty(config)) {
- final HashMap<String, String> configMap = (HashMap<String, String>) jsonUtil
- .jsonToMap(config);
- final String assetName = asset.getName();
-
- final Callable<HadoopFS> connectHDFS = new Callable<HadoopFS>() {
- @Override
- public HadoopFS call() throws Exception {
- return new HadoopFS(assetName, configMap);
- }
- };
-
- try {
- hadoopFS = TimedEventUtil.timedTask(connectHDFS, 5, TimeUnit.SECONDS);
- } catch(Exception e){
- logger.error("Error establishing connection for HDFS repository : "
- + dataSourceName + " using configuration : " +config, e);
- }
- // put it into the cache
- } else {
- logger.error("Connection Config not defined for asset :"
- + asset.getName(), new Throwable());
- }
- hadoopConnectionCache.put(asset.getName(), hadoopFS);
- repoConnectStatusMap.put(asset.getName(), true);
- } else {
- List<String> testConnect = hadoopFS.listFiles("/", "*");
- if(testConnect == null){
- hadoopConnectionCache.remove(dataSourceName);
- hadoopFS = getHadoopConnection(dataSourceName);
- }
- }
- }
- } else {
- logger.error("Asset not found with name "+dataSourceName, new Throwable());
- }
-
- return hadoopFS;
- }
-
- public HiveClient getHiveConnection(final String dataSourceName) {
- HiveClient hiveClient = null;
- XXAsset asset = xADaoManager.getXXAsset().findByAssetName(dataSourceName);
- if (asset != null) {
- // get it from the cache
- synchronized (hiveConnectionCache) {
- hiveClient = hiveConnectionCache.get(asset.getName());
- if (hiveClient == null) {
- String config = asset.getConfig();
- if (!stringUtil.isEmpty(config)) {
- config=xAssetService.getConfigWithDecryptedPassword(config);
- final HashMap<String, String> configMap = (HashMap<String, String>) jsonUtil
- .jsonToMap(config);
-
- final Callable<HiveClient> connectHive = new Callable<HiveClient>() {
- @Override
- public HiveClient call() throws Exception {
- return new HiveClient(dataSourceName, configMap);
- }
- };
- try {
- hiveClient = TimedEventUtil.timedTask(connectHive, 5, TimeUnit.SECONDS);
- } catch(Exception e){
- logger.error("Error connecting hive repository : "+
- dataSourceName +" using config : "+ config, e);
- }
- hiveConnectionCache.put(asset.getName(), hiveClient);
- repoConnectStatusMap.put(asset.getName(), true);
- } else {
- logger.error("Connection Config not defined for asset :"
- + asset.getName(), new Throwable());
- }
- } else {
- try {
- List<String> testConnect = hiveClient.getDatabaseList("*");
- } catch(Exception e) {
- hiveConnectionCache.remove(dataSourceName);
- hiveClient = getHiveConnection(dataSourceName);
- }
- }
- }
- } else {
- logger.error("Asset not found with name "+dataSourceName, new Throwable());
- }
- return hiveClient;
- }
-
- public KnoxClient getKnoxClient(String dataSourceName) {
- KnoxClient knoxClient = null;
- logger.debug("Getting knoxClient for datasource: " + dataSourceName);
- XXAsset asset = xADaoManager.getXXAsset().findByAssetName(dataSourceName);
- if (asset == null) {
- logger.error("Asset not found with name " + dataSourceName, new Throwable());
- } else {
- knoxClient = getKnoxClient(asset);
- }
- return knoxClient;
- }
-
- public KnoxClient getKnoxClient(XXAsset asset) {
- KnoxClient knoxClient = null;
- if (asset == null) {
- logger.error("Asset is null", new Throwable());
- } else {
- String config = asset.getConfig();
- if(!stringUtil.isEmpty(config)){
- config=xAssetService.getConfigWithDecryptedPassword(config);
- }
- knoxClient = getKnoxClientByConfig(config);
- }
- return knoxClient;
- }
-
- public KnoxClient getKnoxClientByConfig(String config) {
- KnoxClient knoxClient = null;
- if (config == null || config.trim().isEmpty()) {
- logger.error("Connection Config is empty");
-
- } else {
- final HashMap<String, String> configMap = (HashMap<String, String>) jsonUtil
- .jsonToMap(config);
- String knoxUrl = configMap.get("knox.url");
- String knoxAdminUser = configMap.get("username");
- String knoxAdminPassword = configMap.get("password");
- knoxClient = new KnoxClient(knoxUrl, knoxAdminUser, knoxAdminPassword);
- }
- return knoxClient;
- }
-
- public KnoxClient getKnoxClient(String dataSourceName,
- Map<String, String> configMap) {
- KnoxClient knoxClient = null;
- logger.debug("Getting knoxClient for datasource: " + dataSourceName +
- "configMap: " + configMap);
- if (configMap == null || configMap.isEmpty()) {
- logger.error("Connection ConfigMap is empty");
- } else {
- String knoxUrl = configMap.get("knox.url");
- String knoxAdminUser = configMap.get("username");
- String knoxAdminPassword = configMap.get("password");
- knoxClient = new KnoxClient(knoxUrl, knoxAdminUser, knoxAdminPassword);
- }
- return knoxClient;
- }
-
-
- public static KnoxClient getKnoxClient(final String knoxUrl, String knoxAdminUser, String knoxAdminPassword) {
- KnoxClient knoxClient = null;
- if (knoxUrl == null || knoxUrl.isEmpty()) {
- logger.error("Can not create KnoxClient: knoxUrl is empty");
- } else if (knoxAdminUser == null || knoxAdminUser.isEmpty()) {
- logger.error("Can not create KnoxClient: knoxAdminUser is empty");
- } else if (knoxAdminPassword == null || knoxAdminPassword.isEmpty()) {
- logger.error("Can not create KnoxClient: knoxAdminPassword is empty");
- } else {
- knoxClient = new KnoxClient(knoxUrl, knoxAdminUser, knoxAdminPassword);
- }
- return knoxClient;
- }
-
- public HBaseClient getHBaseConnection(final String dataSourceName) {
- HBaseClient client = null;
- XXAsset asset = xADaoManager.getXXAsset().findByAssetName(
- dataSourceName);
- if (asset != null) {
- // get it from the cache
- synchronized (hbaseConnectionCache) {
- client = hbaseConnectionCache.get(asset.getName());
- if (client == null) {
- // if it doesn't exist in cache then create the connection
- String config = asset.getConfig();
- if(!stringUtil.isEmpty(config)){
- config=xAssetService.getConfigWithDecryptedPassword(config);
- }
- // FIXME remove this once we start using putting config for
- // default asset "dev-hive" (should come from properties)
- if (stringUtil.isEmpty(config)
- && asset.getName().equals("hbase")) {
-
- final Callable<HBaseClient> connectHBase = new Callable<HBaseClient>() {
- @Override
-
- public HBaseClient call() throws Exception {
- HBaseClient hBaseClient=null;
- if(dataSourceName!=null){
- try{
- hBaseClient=new HBaseClient(dataSourceName);
- }catch(Exception ex){
- logger.error("Error connecting HBase repository : ", ex);
- }
- }
- return hBaseClient;
- }
-
- };
-
- try {
- if(connectHBase!=null){
- client = TimedEventUtil.timedTask(connectHBase, 5, TimeUnit.SECONDS);
- }
- } catch(Exception e){
- logger.error("Error connecting HBase repository : " + dataSourceName);
- }
- } else if (!stringUtil.isEmpty(config)) {
- final HashMap<String, String> configMap = (HashMap<String, String>) jsonUtil
- .jsonToMap(config);
-
- final Callable<HBaseClient> connectHBase = new Callable<HBaseClient>() {
- @Override
- public HBaseClient call() throws Exception {
- HBaseClient hBaseClient=null;
- if(dataSourceName!=null && configMap!=null){
- try{
- hBaseClient=new HBaseClient(dataSourceName,configMap);
- }catch(Exception ex){
- logger.error("Error connecting HBase repository : ", ex);
- }
- }
- return hBaseClient;
- }
- };
-
- try {
- if(connectHBase!=null){
- client = TimedEventUtil.timedTask(connectHBase, 5, TimeUnit.SECONDS);
- }
- } catch(Exception e){
- logger.error("Error connecting HBase repository : "+
- dataSourceName +" using config : "+ config);
- }
-
- } else {
- logger.error(
- "Connection Config not defined for asset :"
- + asset.getName(), new Throwable());
- }
- if(client!=null){
- hbaseConnectionCache.put(asset.getName(), client);
- }
- } else {
- List<String> testConnect = client.getTableList(".\\*");
- if(testConnect == null){
- hbaseConnectionCache.remove(dataSourceName);
- client = getHBaseConnection(dataSourceName);
- }
- }
- repoConnectStatusMap.put(asset.getName(), true);
- }
- } else {
- logger.error("Asset not found with name " + dataSourceName,
- new Throwable());
- }
-
- return client;
- }
-
- public boolean destroyConnection(VXAsset asset) {
- boolean result = false;
- if (asset != null) {
- if(asset.getAssetType() == AppConstants.ASSET_HDFS) {
- synchronized (hadoopConnectionCache) {
-
- @SuppressWarnings("unused")
- HadoopFS hadoopFS = hadoopConnectionCache.get(asset.getName());
- // TODO need a way to close the connection
- hadoopConnectionCache.remove(asset.getName());
- repoConnectStatusMap.remove(asset.getName());
-
- }
- } else if(asset.getAssetType() == AppConstants.ASSET_HIVE) {
- synchronized (hadoopConnectionCache) {
-
- HiveClient hiveClient = hiveConnectionCache.get(asset.getName());
- if(hiveClient != null) {
- hiveClient.close();
- }
- hadoopConnectionCache.remove(asset.getName());
- repoConnectStatusMap.remove(asset.getName());
-
- }
- } else if (asset.getAssetType() == AppConstants.ASSET_HBASE) {
- synchronized (hbaseConnectionCache) {
- @SuppressWarnings("unused")
- HBaseClient hBaseClient = hbaseConnectionCache.get(asset
- .getName());
- // TODO need a way to close the connection
- hbaseConnectionCache.remove(asset.getName());
- repoConnectStatusMap.remove(asset.getName());
-
- }
- }
- result = true;
- }
- return result;
- }
-
- public HadoopFS resetHadoopConnection(final String dataSourceName){
- hadoopConnectionCache.remove(dataSourceName);
- return getHadoopConnection(dataSourceName);
- }
-
- public static StormClient getStormClient(final String stormUIURL, String userName, String password) {
- StormClient stormClient = null;
- if (stormUIURL == null || stormUIURL.isEmpty()) {
- logger.error("Can not create KnoxClient: stormUIURL is empty");
- } else if (userName == null || userName.isEmpty()) {
- logger.error("Can not create KnoxClient: knoxAdminUser is empty");
- } else if (password == null || password.isEmpty()) {
- logger.error("Can not create KnoxClient: knoxAdminPassword is empty");
- } else {
- stormClient = new StormClient(stormUIURL, userName, password);
- }
- return stormClient;
- }
-
-}
[21/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/view/VList.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/view/VList.java b/security-admin/src/main/java/com/xasecure/common/view/VList.java
deleted file mode 100644
index 5fbfc80..0000000
--- a/security-admin/src/main/java/com/xasecure/common/view/VList.java
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- * 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 com.xasecure.common.view;
-
-
-import java.util.List;
-
-import javax.xml.bind.annotation.*;
-
-@XmlRootElement
-public abstract class VList extends ViewBaseBean implements
- java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
- /**
- * Start index for the result
- */
- protected int startIndex;
- /**
- * Page size used for the result
- */
- protected int pageSize;
- /**
- * Total records in the database for the given search conditions
- */
- protected long totalCount;
- /**
- * Number of rows returned for the search condition
- */
- protected int resultSize;
- /**
- * Sort type. Either desc or asc
- */
- protected String sortType;
- /**
- * Comma seperated list of the fields for sorting
- */
- protected String sortBy;
-
- protected long queryTimeMS = System.currentTimeMillis();
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VList() {
- }
-
- /**
- * Initialize with existing list
- *
- * @param size
- */
- public VList(@SuppressWarnings("rawtypes") List objectList) {
- int size = 0;
- if (objectList != null) {
- size = objectList.size();
- }
-
- startIndex = 0;
- pageSize = size;
- totalCount = size;
- resultSize = size;
- sortType = null;
- sortBy = null;
- }
-
- abstract public int getListSize();
-
- abstract public List<?> getList();
-
- /**
- * This method sets the value to the member attribute <b>startIndex</b>. You
- * cannot set null to the attribute.
- *
- * @param startIndex
- * Value to set member attribute <b>startIndex</b>
- */
- public void setStartIndex(int startIndex) {
- this.startIndex = startIndex;
- }
-
-
- /**
- * This method sets the value to the member attribute <b>pageSize</b>. You
- * cannot set null to the attribute.
- *
- * @param pageSize
- * Value to set member attribute <b>pageSize</b>
- */
- public void setPageSize(int pageSize) {
- this.pageSize = pageSize;
- }
-
-
- /**
- * This method sets the value to the member attribute <b>totalCount</b>. You
- * cannot set null to the attribute.
- *
- * @param totalCount
- * Value to set member attribute <b>totalCount</b>
- */
- public void setTotalCount(long totalCount) {
- this.totalCount = totalCount;
- }
-
-
-
- /**
- * This method sets the value to the member attribute <b>resultSize</b>. You
- * cannot set null to the attribute.
- *
- * @param resultSize
- * Value to set member attribute <b>resultSize</b>
- */
- public void setResultSize(int resultSize) {
- this.resultSize = resultSize;
- }
-
- /**
- * Returns the value for the member attribute <b>resultSize</b>
- *
- * @return int - value of member attribute <b>resultSize</b>.
- */
- public int getResultSize() {
- return getListSize();
- }
-
- /**
- * This method sets the value to the member attribute <b>sortType</b>. You
- * cannot set null to the attribute.
- *
- * @param sortType
- * Value to set member attribute <b>sortType</b>
- */
- public void setSortType(String sortType) {
- this.sortType = sortType;
- }
-
-
-
- /**
- * This method sets the value to the member attribute <b>sortBy</b>. You
- * cannot set null to the attribute.
- *
- * @param sortBy
- * Value to set member attribute <b>sortBy</b>
- */
- public void setSortBy(String sortBy) {
- this.sortBy = sortBy;
- }
-
-
-
-
-
-
-
- /*
- * (non-Javadoc)
- *
- * @see java.lang.Object#toString()
- */
- @Override
- public String toString() {
- return "VList [startIndex=" + startIndex + ", pageSize="
- + pageSize + ", totalCount=" + totalCount
- + ", resultSize=" + resultSize + ", sortType="
- + sortType + ", sortBy=" + sortBy + ", queryTimeMS="
- + queryTimeMS + "]";
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/view/VTrxLogAttr.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/view/VTrxLogAttr.java b/security-admin/src/main/java/com/xasecure/common/view/VTrxLogAttr.java
deleted file mode 100644
index 36fe606..0000000
--- a/security-admin/src/main/java/com/xasecure/common/view/VTrxLogAttr.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * 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 com.xasecure.common.view;
-
-import java.io.Serializable;
-
-import javax.xml.bind.annotation.XmlRootElement;
-
-import com.xasecure.common.AppConstants;
-
-import com.xasecure.common.XACommonEnums;
-import com.xasecure.common.view.ViewBaseBean;
-
-@XmlRootElement
-public class VTrxLogAttr extends ViewBaseBean implements Serializable{
- private static final long serialVersionUID = 1L;
-
- protected String attribName;
- protected String attribUserFriendlyName;
- protected boolean isEnum;
-
- public VTrxLogAttr(){}
-
- public VTrxLogAttr(String attribName, String attribUserFriendlyName,
- boolean isEnum) {
- super();
- this.attribName = attribName;
- this.attribUserFriendlyName = attribUserFriendlyName;
- this.isEnum = isEnum;
- }
-
-
-
-
- /**
- * @return the attribUserFriendlyName
- */
- public String getAttribUserFriendlyName() {
- return attribUserFriendlyName;
- }
-
-
- /**
- * @return the isEnum
- */
- public boolean isEnum() {
- return isEnum;
- }
-
-
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_XA_TRANSACTION_LOG_ATTRIBUTE;
- }
-
- @Override
- public String toString(){
- String str = "VTrxLogAttr={";
- str += super.toString();
- str += "attribName={" + attribName + "} ";
- str += "attribUserFriendlyName={" + attribUserFriendlyName + "} ";
- str += "isEnum={" + isEnum + "} ";
- str += "}";
- return str;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/view/ViewBaseBean.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/view/ViewBaseBean.java b/security-admin/src/main/java/com/xasecure/common/view/ViewBaseBean.java
deleted file mode 100644
index c48c5a1..0000000
--- a/security-admin/src/main/java/com/xasecure/common/view/ViewBaseBean.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * 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 com.xasecure.common.view;
-
-import javax.xml.bind.annotation.XmlTransient;
-
-import org.codehaus.jackson.annotate.JsonIgnore;
-
-import com.xasecure.common.XACommonEnums;
-import com.xasecure.entity.XXDBBase;
-
-public class ViewBaseBean implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
- @JsonIgnore
- private XXDBBase mObj = null;
-
- /**
- * @return the gjObj
- */
- @XmlTransient
- @JsonIgnore
- public XXDBBase getMObj() {
- return mObj;
- }
-
- /**
- * @param gjObj
- * the gjObj to set
- */
- public void setMObj(XXDBBase gjObj) {
- this.mObj = gjObj;
- }
-
- @XmlTransient
- @JsonIgnore
- public int getMyClassType() {
- return XACommonEnums.CLASS_TYPE_NONE;
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/credentialapi/CredentialReader.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/credentialapi/CredentialReader.java b/security-admin/src/main/java/com/xasecure/credentialapi/CredentialReader.java
deleted file mode 100644
index dccf8a1..0000000
--- a/security-admin/src/main/java/com/xasecure/credentialapi/CredentialReader.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * 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 com.xasecure.credentialapi;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.security.alias.CredentialProvider;
-import org.apache.hadoop.security.alias.CredentialProviderFactory;
-import org.apache.hadoop.security.alias.JavaKeyStoreProvider;
-
-public class CredentialReader {
-
- public static String getDecryptedString(String CrendentialProviderPath,String alias) {
- String credential=null;
- try{
- if(CrendentialProviderPath==null || alias==null){
- return null;
- }
- char[] pass = null;
- Configuration conf = new Configuration();
- String crendentialProviderPrefix=JavaKeyStoreProvider.SCHEME_NAME + "://file";
- crendentialProviderPrefix=crendentialProviderPrefix.toLowerCase();
- CrendentialProviderPath=CrendentialProviderPath.trim();
- alias=alias.trim();
- if(CrendentialProviderPath.toLowerCase().startsWith(crendentialProviderPrefix)){
- conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
- //UserProvider.SCHEME_NAME + ":///," +
- CrendentialProviderPath);
- }else{
- if(CrendentialProviderPath.startsWith("/")){
- conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
- //UserProvider.SCHEME_NAME + ":///," +
- JavaKeyStoreProvider.SCHEME_NAME + "://file" + CrendentialProviderPath);
- }else{
- conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
- //UserProvider.SCHEME_NAME + ":///," +
- JavaKeyStoreProvider.SCHEME_NAME + "://file/" + CrendentialProviderPath);
- }
- }
- List<CredentialProvider> providers = CredentialProviderFactory.getProviders(conf);
- List<String> aliasesList=new ArrayList<String>();
- CredentialProvider.CredentialEntry credEntry=null;
- for(CredentialProvider provider: providers) {
- //System.out.println("Credential Provider :" + provider);
- aliasesList=provider.getAliases();
- if(aliasesList!=null && aliasesList.contains(alias.toLowerCase())){
- credEntry=null;
- credEntry= provider.getCredentialEntry(alias);
- pass = credEntry.getCredential();
- if(pass!=null && pass.length>0){
- credential=String.valueOf(pass);
- break;
- }
- }
- }
- }catch(Exception ex){
- ex.printStackTrace();
- credential=null;
- }
- return credential;
- }
-
- /*
- public static void main(String args[]) throws Exception{
- String keystoreFile =new String("/tmp/mykey3.jceks");
- String password=CredentialReader.getDecryptedString(keystoreFile, "mykey3");
- System.out.println(password);
- }*/
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/db/XADaoManager.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/db/XADaoManager.java b/security-admin/src/main/java/com/xasecure/db/XADaoManager.java
deleted file mode 100644
index cf27d81..0000000
--- a/security-admin/src/main/java/com/xasecure/db/XADaoManager.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * 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 com.xasecure.db;
-
-
-
-import javax.persistence.*;
-
-import com.xasecure.common.*;
-import org.apache.log4j.Logger;
-
-import com.xasecure.common.db.BaseDao;
-
-import org.springframework.stereotype.Component;
-import org.springframework.beans.factory.annotation.Autowired;
-
-@Component
-public class XADaoManager extends XADaoManagerBase {
- final static Logger logger = Logger.getLogger(XADaoManager.class);
-
- @PersistenceContext(unitName = "defaultPU")
- private EntityManager em;
-
- @PersistenceContext(unitName = "loggingPU")
- private EntityManager loggingEM;
-
- @Autowired
- StringUtil stringUtil;
-
- @Override
- public EntityManager getEntityManager() {
- return em;
- }
-
- public EntityManager getEntityManager(String persistenceContextUnit) {
- logger.error("XADaoManager.getEntityManager(" + persistenceContextUnit + ")");
- if (persistenceContextUnit.equalsIgnoreCase("loggingPU")) {
- return loggingEM;
- }
- return getEntityManager();
- }
-
-
- /**
- * @return the stringUtil
- */
- public StringUtil getStringUtil() {
- return stringUtil;
- }
-
- /*
- * (non-Javadoc)
- */
- @Override
- public BaseDao<?> getDaoForClassType(int classType) {
- if (classType == XAConstants.CLASS_TYPE_NONE) {
- return null;
- }
- return super.getDaoForClassType(classType);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/db/XADaoManagerBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/db/XADaoManagerBase.java b/security-admin/src/main/java/com/xasecure/db/XADaoManagerBase.java
deleted file mode 100644
index d5eea00..0000000
--- a/security-admin/src/main/java/com/xasecure/db/XADaoManagerBase.java
+++ /dev/null
@@ -1,214 +0,0 @@
-/*
- * 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 com.xasecure.db;
-
-/**
- *
- */
-
-import javax.persistence.*;
-import java.util.*;
-import org.apache.log4j.Logger;
-import com.xasecure.entity.*;
-import com.xasecure.common.*;
-import com.xasecure.common.db.*;
-import org.springframework.stereotype.Component;
-import org.springframework.beans.factory.annotation.Autowired;
-
-
-public abstract class XADaoManagerBase {
- final static Logger logger = Logger.getLogger(XADaoManagerBase.class);
-
- @Autowired
- protected RESTErrorUtil restErrorUtil;
- abstract public EntityManager getEntityManager();
-
- public XADaoManagerBase() {
- }
-
- public BaseDao<?> getDaoForClassType(int classType) {
- if (classType == AppConstants.CLASS_TYPE_AUTH_SESS) {
- return getXXAuthSession();
- }
- if (classType == AppConstants.CLASS_TYPE_USER_PROFILE) {
- return getXXPortalUser();
- }
- if (classType == AppConstants.CLASS_TYPE_XA_ASSET) {
- return getXXAsset();
- }
- if (classType == AppConstants.CLASS_TYPE_XA_RESOURCE) {
- return getXXResource();
- }
- if (classType == AppConstants.CLASS_TYPE_XA_CRED_STORE) {
- return getXXCredentialStore();
- }
- if (classType == AppConstants.CLASS_TYPE_XA_GROUP) {
- return getXXGroup();
- }
- if (classType == AppConstants.CLASS_TYPE_XA_USER) {
- return getXXUser();
- }
- if (classType == AppConstants.CLASS_TYPE_XA_GROUP_USER) {
- return getXXGroupUser();
- }
- if (classType == AppConstants.CLASS_TYPE_XA_GROUP_GROUP) {
- return getXXGroupGroup();
- }
- if (classType == AppConstants.CLASS_TYPE_XA_PERM_MAP) {
- return getXXPermMap();
- }
- if (classType == AppConstants.CLASS_TYPE_XA_AUDIT_MAP) {
- return getXXAuditMap();
- }
- if (classType == AppConstants.CLASS_TYPE_XA_POLICY_EXPORT_AUDIT) {
- return getXXPolicyExportAudit();
- }
- if (classType == AppConstants.CLASS_TYPE_TRX_LOG) {
- return getXXTrxLog();
- }
- if (classType == AppConstants.CLASS_TYPE_XA_ACCESS_AUDIT) {
- return getXXAccessAudit();
- }
-
- logger.error("No DaoManager found for classType=" + classType, new Throwable());
- return null;
- }
-
- public BaseDao<?> getDaoForClassName(String className) {
- if (className.equals("XXDBBase")) {
- return getXXDBBase();
- }
- if (className.equals("XXAuthSession")) {
- return getXXAuthSession();
- }
- if (className.equals("XXPortalUser")) {
- return getXXPortalUser();
- }
- if (className.equals("XXPortalUserRole")) {
- return getXXPortalUserRole();
- }
- if (className.equals("XXAsset")) {
- return getXXAsset();
- }
- if (className.equals("XXResource")) {
- return getXXResource();
- }
- if (className.equals("XXCredentialStore")) {
- return getXXCredentialStore();
- }
- if (className.equals("XXGroup")) {
- return getXXGroup();
- }
- if (className.equals("XXUser")) {
- return getXXUser();
- }
- if (className.equals("XXGroupUser")) {
- return getXXGroupUser();
- }
- if (className.equals("XXGroupGroup")) {
- return getXXGroupGroup();
- }
- if (className.equals("XXPermMap")) {
- return getXXPermMap();
- }
- if (className.equals("XXAuditMap")) {
- return getXXAuditMap();
- }
- if (className.equals("XXPolicyExportAudit")) {
- return getXXPolicyExportAudit();
- }
- if (className.equals("XXTrxLog")) {
- return getXXTrxLog();
- }
- if (className.equals("XXAccessAudit")) {
- return getXXAccessAudit();
- }
-
- logger.error("No DaoManager found for className=" + className, new Throwable());
- return null;
- }
-
- public XXDBBaseDao getXXDBBase() {
- return new XXDBBaseDao(this);
- }
-
- public XXAuthSessionDao getXXAuthSession() {
- return new XXAuthSessionDao(this);
- }
-
- public XXPortalUserDao getXXPortalUser() {
- return new XXPortalUserDao(this);
- }
-
- public XXPortalUserRoleDao getXXPortalUserRole() {
- return new XXPortalUserRoleDao(this);
- }
-
- public XXAssetDao getXXAsset() {
- return new XXAssetDao(this);
- }
-
- public XXResourceDao getXXResource() {
- return new XXResourceDao(this);
- }
-
- public XXCredentialStoreDao getXXCredentialStore() {
- return new XXCredentialStoreDao(this);
- }
-
- public XXGroupDao getXXGroup() {
- return new XXGroupDao(this);
- }
-
- public XXUserDao getXXUser() {
- return new XXUserDao(this);
- }
-
- public XXGroupUserDao getXXGroupUser() {
- return new XXGroupUserDao(this);
- }
-
- public XXGroupGroupDao getXXGroupGroup() {
- return new XXGroupGroupDao(this);
- }
-
- public XXPermMapDao getXXPermMap() {
- return new XXPermMapDao(this);
- }
-
- public XXAuditMapDao getXXAuditMap() {
- return new XXAuditMapDao(this);
- }
-
- public XXPolicyExportAuditDao getXXPolicyExportAudit() {
- return new XXPolicyExportAuditDao(this);
- }
-
- public XXTrxLogDao getXXTrxLog() {
- return new XXTrxLogDao(this);
- }
-
- public XXAccessAuditDao getXXAccessAudit() {
- return new XXAccessAuditDao(this);
- }
-
-
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/db/XXAccessAuditDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/db/XXAccessAuditDao.java b/security-admin/src/main/java/com/xasecure/db/XXAccessAuditDao.java
deleted file mode 100644
index c0b44d7..0000000
--- a/security-admin/src/main/java/com/xasecure/db/XXAccessAuditDao.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * 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 com.xasecure.db;
-
-import com.xasecure.entity.XXAccessAudit;
-import com.xasecure.common.*;
-import com.xasecure.common.db.*;
-import com.xasecure.entity.*;
-
-public class XXAccessAuditDao extends BaseDao<XXAccessAudit> {
-
- public XXAccessAuditDao( XADaoManagerBase daoManager ) {
- super(daoManager, "loggingPU");
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/db/XXAssetDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/db/XXAssetDao.java b/security-admin/src/main/java/com/xasecure/db/XXAssetDao.java
deleted file mode 100644
index efb68a7..0000000
--- a/security-admin/src/main/java/com/xasecure/db/XXAssetDao.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * 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 com.xasecure.db;
-
-import javax.persistence.NoResultException;
-
-import org.apache.log4j.Logger;
-
-import com.xasecure.entity.XXAsset;
-
-import com.xasecure.common.XACommonEnums;
-import com.xasecure.common.db.*;
-
-public class XXAssetDao extends BaseDao<XXAsset> {
- static final Logger logger = Logger.getLogger(XXAssetDao.class);
-
- public XXAssetDao( XADaoManagerBase daoManager ) {
- super(daoManager);
- }
-
- public XXAsset findByAssetName(String name){
- if (daoManager.getStringUtil().isEmpty(name)) {
- logger.debug("name is empty");
- return null;
- }
- try {
- return getEntityManager()
- .createNamedQuery("XXAsset.findByAssetName", XXAsset.class)
- .setParameter("name", name.trim())
- .setParameter("status",XACommonEnums.STATUS_DELETED)
- .getSingleResult();
- } catch (NoResultException e) {
- // ignore
- }
- return null;
- }
-
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/db/XXAuditMapDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/db/XXAuditMapDao.java b/security-admin/src/main/java/com/xasecure/db/XXAuditMapDao.java
deleted file mode 100644
index 8ecf29c..0000000
--- a/security-admin/src/main/java/com/xasecure/db/XXAuditMapDao.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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 com.xasecure.db;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.persistence.NoResultException;
-
-import org.apache.log4j.Logger;
-
-import com.xasecure.entity.XXAuditMap;
-import com.xasecure.entity.XXPermMap;
-
-import com.xasecure.common.*;
-import com.xasecure.common.db.*;
-import com.xasecure.entity.*;
-
-public class XXAuditMapDao extends BaseDao<XXAuditMap> {
- static final Logger logger = Logger.getLogger(XXAssetDao.class);
-
- public XXAuditMapDao( XADaoManagerBase daoManager ) {
- super(daoManager);
- }
-
- public List<XXAuditMap> findByResourceId(Long resourceId) {
- if (resourceId != null) {
- try {
- return getEntityManager()
- .createNamedQuery("XXAuditMap.findByResourceId", XXAuditMap.class)
- .setParameter("resourceId", resourceId)
- .getResultList();
- } catch (NoResultException e) {
- logger.debug(e.getMessage());
- }
- } else {
- logger.debug("ResourceId not provided.");
- return new ArrayList<XXAuditMap>();
- }
- return new ArrayList<XXAuditMap>();
- }
-
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/db/XXAuthSessionDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/db/XXAuthSessionDao.java b/security-admin/src/main/java/com/xasecure/db/XXAuthSessionDao.java
deleted file mode 100644
index 6cd96b5..0000000
--- a/security-admin/src/main/java/com/xasecure/db/XXAuthSessionDao.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * 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 com.xasecure.db;
-
-import java.util.List;
-
-import javax.persistence.NoResultException;
-
-import com.xasecure.common.db.BaseDao;
-import com.xasecure.entity.XXAuthSession;
-
-public class XXAuthSessionDao extends BaseDao<XXAuthSession> {
-
- public XXAuthSessionDao( XADaoManagerBase daoManager ) {
- super(daoManager);
- }
-
- @SuppressWarnings("unchecked")
- public List<Object[]> getUserLoggedIn(){
- return getEntityManager()
- .createNamedQuery("XXAuthSession.getUserLoggedIn")
- .getResultList();
- }
-
- public XXAuthSession getAuthSessionBySessionId(String sessionId){
- try{
- return (XXAuthSession) getEntityManager()
- .createNamedQuery("XXAuthSession.getAuthSessionBySessionId")
- .setParameter("sessionId", sessionId)
- .getSingleResult();
- } catch(NoResultException ignoreNoResultFound) {
- return null;
- }
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/db/XXCredentialStoreDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/db/XXCredentialStoreDao.java b/security-admin/src/main/java/com/xasecure/db/XXCredentialStoreDao.java
deleted file mode 100644
index b706a6b..0000000
--- a/security-admin/src/main/java/com/xasecure/db/XXCredentialStoreDao.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * 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 com.xasecure.db;
-
-import com.xasecure.entity.XXCredentialStore;
-
-import com.xasecure.common.*;
-import com.xasecure.common.db.*;
-import com.xasecure.entity.*;
-
-public class XXCredentialStoreDao extends BaseDao<XXCredentialStore> {
-
- public XXCredentialStoreDao( XADaoManagerBase daoManager ) {
- super(daoManager);
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/db/XXDBBaseDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/db/XXDBBaseDao.java b/security-admin/src/main/java/com/xasecure/db/XXDBBaseDao.java
deleted file mode 100644
index cb55f8c..0000000
--- a/security-admin/src/main/java/com/xasecure/db/XXDBBaseDao.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * 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 com.xasecure.db;
-
-import com.xasecure.common.db.BaseDao;
-import com.xasecure.entity.*;
-
-public class XXDBBaseDao extends BaseDao<XXDBBase> {
-
- public XXDBBaseDao( XADaoManagerBase daoManager ) {
- super(daoManager);
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/db/XXGroupDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/db/XXGroupDao.java b/security-admin/src/main/java/com/xasecure/db/XXGroupDao.java
deleted file mode 100644
index 52ddae0..0000000
--- a/security-admin/src/main/java/com/xasecure/db/XXGroupDao.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * 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 com.xasecure.db;
-
-
-import java.util.ArrayList;
-import java.util.List;
-
-
-
-import com.xasecure.entity.XXGroup;
-
-import com.xasecure.common.*;
-import com.xasecure.common.db.*;
-import com.xasecure.entity.*;
-
-public class XXGroupDao extends BaseDao<XXGroup> {
-
- public XXGroupDao(XADaoManagerBase daoManager) {
- super(daoManager);
- }
-
- @SuppressWarnings("unchecked")
- public List<XXGroup> findByUserId(Long userId) {
- if (userId == null) {
- return new ArrayList<XXGroup>();
- }
-
- List<XXGroup> groupList = (List<XXGroup>) getEntityManager()
- .createNamedQuery("XXGroup.findByUserId")
- .setParameter("userId", userId).getResultList();
-
- if (groupList == null) {
- groupList = new ArrayList<XXGroup>();
- }
-
- return groupList;
- }
-
- @SuppressWarnings("unchecked")
- public XXGroup findByGroupName(String groupName) {
- if (groupName == null) {
- return null;
- }
- try {
-
- return (XXGroup) getEntityManager()
- .createNamedQuery("XXGroup.findByGroupName")
- .setParameter("name", groupName)
- .getSingleResult();
- } catch (Exception e) {
-
- }
- return null;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/db/XXGroupGroupDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/db/XXGroupGroupDao.java b/security-admin/src/main/java/com/xasecure/db/XXGroupGroupDao.java
deleted file mode 100644
index e914e0a..0000000
--- a/security-admin/src/main/java/com/xasecure/db/XXGroupGroupDao.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * 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 com.xasecure.db;
-
-import com.xasecure.entity.XXGroupGroup;
-
-import com.xasecure.common.*;
-import com.xasecure.common.db.*;
-import com.xasecure.entity.*;
-
-public class XXGroupGroupDao extends BaseDao<XXGroupGroup> {
-
- public XXGroupGroupDao( XADaoManagerBase daoManager ) {
- super(daoManager);
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/db/XXGroupUserDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/db/XXGroupUserDao.java b/security-admin/src/main/java/com/xasecure/db/XXGroupUserDao.java
deleted file mode 100644
index c035f00..0000000
--- a/security-admin/src/main/java/com/xasecure/db/XXGroupUserDao.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * 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 com.xasecure.db;
-
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.persistence.NoResultException;
-
-import org.apache.log4j.Logger;
-
-import com.xasecure.entity.XXGroupUser;
-import com.xasecure.entity.XXPermMap;
-
-import com.xasecure.common.*;
-import com.xasecure.common.db.*;
-import com.xasecure.entity.*;
-
-public class XXGroupUserDao extends BaseDao<XXGroupUser> {
- static final Logger logger = Logger.getLogger(XXGroupUserDao.class);
-
- public XXGroupUserDao(XADaoManagerBase daoManager) {
- super(daoManager);
- }
-
- public void deleteByGroupIdAndUserId(Long groupId, Long userId) {
- getEntityManager()
- .createNamedQuery("XXGroupUser.deleteByGroupIdAndUserId")
- .setParameter("userId", userId)
- .setParameter("parentGroupId", groupId).executeUpdate();
-
- }
-
- public List<XXGroupUser> findByUserId(Long userId) {
- if (userId != null) {
- try {
- return getEntityManager()
- .createNamedQuery("XXGroupUser.findByUserId", XXGroupUser.class)
- .setParameter("userId", userId)
- .getResultList();
- } catch (NoResultException e) {
- logger.debug(e.getMessage());
- }
- } else {
- logger.debug("ResourceId not provided.");
- return new ArrayList<XXGroupUser>();
- }
- return null;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/db/XXPermMapDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/db/XXPermMapDao.java b/security-admin/src/main/java/com/xasecure/db/XXPermMapDao.java
deleted file mode 100644
index b3ceff5..0000000
--- a/security-admin/src/main/java/com/xasecure/db/XXPermMapDao.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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 com.xasecure.db;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.persistence.NoResultException;
-
-import org.apache.log4j.Logger;
-
-import com.xasecure.entity.XXPermMap;
-import com.xasecure.entity.XXResource;
-
-import com.xasecure.common.*;
-import com.xasecure.common.db.*;
-import com.xasecure.entity.*;
-
-public class XXPermMapDao extends BaseDao<XXPermMap> {
- static final Logger logger = Logger.getLogger(XXResourceDao.class);
-
- public XXPermMapDao( XADaoManagerBase daoManager ) {
- super(daoManager);
- }
-
- public List<XXPermMap> findByResourceId(Long resourceId) {
- if (resourceId != null) {
- try {
- return getEntityManager()
- .createNamedQuery("XXPermMap.findByResourceId", XXPermMap.class)
- .setParameter("resourceId", resourceId)
- .getResultList();
- } catch (NoResultException e) {
- logger.debug(e.getMessage());
- }
- } else {
- logger.debug("ResourceId not provided.");
- return new ArrayList<XXPermMap>();
- }
- return null;
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/db/XXPolicyExportAuditDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/db/XXPolicyExportAuditDao.java b/security-admin/src/main/java/com/xasecure/db/XXPolicyExportAuditDao.java
deleted file mode 100644
index ccb34be..0000000
--- a/security-admin/src/main/java/com/xasecure/db/XXPolicyExportAuditDao.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * 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 com.xasecure.db;
-
-import com.xasecure.entity.XXPolicyExportAudit;
-import com.xasecure.common.*;
-import com.xasecure.common.db.*;
-import com.xasecure.entity.*;
-
-public class XXPolicyExportAuditDao extends BaseDao<XXPolicyExportAudit> {
-
- public XXPolicyExportAuditDao( XADaoManagerBase daoManager ) {
- super(daoManager);
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/db/XXPortalUserDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/db/XXPortalUserDao.java b/security-admin/src/main/java/com/xasecure/db/XXPortalUserDao.java
deleted file mode 100644
index adc7f53..0000000
--- a/security-admin/src/main/java/com/xasecure/db/XXPortalUserDao.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * 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 com.xasecure.db;
-
-
-import java.util.List;
-
-import com.xasecure.entity.XXPortalUser;
-import com.xasecure.common.db.*;
-
-public class XXPortalUserDao extends BaseDao<XXPortalUser> {
-
- public XXPortalUserDao(XADaoManagerBase daoManager) {
- super(daoManager);
- }
-
- public XXPortalUser findByLoginId(String loginId) {
- if (daoManager.getStringUtil().isEmpty(loginId)) {
- return null;
- }
-
- @SuppressWarnings("rawtypes")
- List resultList = getEntityManager()
- .createNamedQuery("XXPortalUser.findByLoginId")
- .setParameter("loginId", loginId).getResultList();
- if (resultList.size() != 0) {
- return (XXPortalUser) resultList.get(0);
- }
- return null;
- }
-
- public XXPortalUser findByEmailAddress(String emailAddress) {
- if (daoManager.getStringUtil().isEmpty(emailAddress)) {
- return null;
- }
-
- @SuppressWarnings("rawtypes")
- List resultList = getEntityManager()
- .createNamedQuery("XXPortalUser.findByEmailAddress")
- .setParameter("emailAddress", emailAddress)
- .getResultList();
- if (resultList.size() != 0) {
- return (XXPortalUser) resultList.get(0);
- }
- return null;
- }
-
- @SuppressWarnings("unchecked")
- public List<XXPortalUser> findByRole(String userRole) {
- return getEntityManager().createNamedQuery("XXPortalUser.findByRole")
- .setParameter("userRole", userRole.toUpperCase())
- .getResultList();
- }
-
- @SuppressWarnings("unchecked")
- public List<Object[]> getUserAddedReport(){
- return getEntityManager()
- .createNamedQuery("XXPortalUser.getUserAddedReport")
- .getResultList();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/db/XXPortalUserRoleDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/db/XXPortalUserRoleDao.java b/security-admin/src/main/java/com/xasecure/db/XXPortalUserRoleDao.java
deleted file mode 100644
index f6e7ddc..0000000
--- a/security-admin/src/main/java/com/xasecure/db/XXPortalUserRoleDao.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * 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 com.xasecure.db;
-
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.persistence.NoResultException;
-
-import com.xasecure.entity.XXPortalUserRole;
-import com.xasecure.common.db.*;
-
-public class XXPortalUserRoleDao extends BaseDao<XXPortalUserRole> {
-
- public XXPortalUserRoleDao(XADaoManagerBase daoManager) {
- super(daoManager);
- }
-
- @SuppressWarnings("unchecked")
- public List<XXPortalUserRole> findByUserId(Long userId) {
- if (userId == null) {
- return new ArrayList<XXPortalUserRole>();
- }
- return getEntityManager().createNamedQuery("XXPortalUserRole.findByUserId")
- .setParameter("userId", userId).getResultList();
- }
-
- public XXPortalUserRole findByRoleUserId(Long userId, String role) {
- if(userId == null || role == null || role.isEmpty()){
- return null;
- }
- try{
- return (XXPortalUserRole)getEntityManager().createNamedQuery("XXPortalUserRole.findByRoleUserId")
- .setParameter("userId", userId)
- .setParameter("userRole", role).getSingleResult();
- } catch(NoResultException e){
- //doNothing;
- }
- return null;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/db/XXResourceDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/db/XXResourceDao.java b/security-admin/src/main/java/com/xasecure/db/XXResourceDao.java
deleted file mode 100644
index 323bc06..0000000
--- a/security-admin/src/main/java/com/xasecure/db/XXResourceDao.java
+++ /dev/null
@@ -1,276 +0,0 @@
-/*
- * 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 com.xasecure.db;
-
-
-import java.util.Date;
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.persistence.NoResultException;
-
-import org.apache.log4j.Logger;
-
-
-import com.xasecure.entity.XXResource;
-
-import com.xasecure.common.db.*;
-
-public class XXResourceDao extends BaseDao<XXResource> {
- static final Logger logger = Logger.getLogger(XXResourceDao.class);
-
- public XXResourceDao(XADaoManagerBase daoManager) {
- super(daoManager);
- }
-
- public XXResource findByResourceName(String name) {
- if (daoManager.getStringUtil().isEmpty(name)) {
- logger.debug("name is empty");
- return null;
- }
- try {
- return getEntityManager()
- .createNamedQuery("XXResource.findByResourceName",
- XXResource.class).setParameter("name", name.trim())
- .getSingleResult();
- } catch (NoResultException e) {
- // ignore
- }
- return null;
- }
-
- public List<XXResource> findUpdatedResourcesByAssetId(
- Long assetId, Date lastUpdated) {
- if (assetId != null) {
- try {
- return getEntityManager()
- .createNamedQuery("XXResource.findUpdatedResourcesByAssetId",
- XXResource.class)
- .setParameter("assetId", assetId)
- .setParameter("lastUpdated", lastUpdated)
- .getResultList();
- } catch (NoResultException e) {
- logger.debug(e.getMessage());
- }
- } else {
- logger.debug("AssetId not provided.");
- return new ArrayList<XXResource>();
- }
- return null;
- }
-
- public List<XXResource> findByAssetId(Long assetId) {
- List<XXResource> xResourceList = null;
- if (assetId != null) {
- try {
- xResourceList = getEntityManager()
- .createNamedQuery("XXResource.findByAssetId", XXResource.class)
- .setParameter("assetId", assetId)
- .getResultList();
- } catch (NoResultException e) {
- // ignore
- logger.debug(e.getMessage());
- }
- if(xResourceList == null) {
- xResourceList = new ArrayList<XXResource>();
- }
- } else {
- logger.debug("AssetId not provided.");
- xResourceList = new ArrayList<XXResource>();
- }
- return xResourceList;
- }
-
- public List<XXResource> findByAssetType(Integer assetType) {
- List<XXResource> xResourceList = null;
- if (assetType != null) {
- try {
- xResourceList = getEntityManager()
- .createNamedQuery("XXResource.findByAssetType", XXResource.class)
- .setParameter("assetType", assetType)
- .getResultList();
- } catch (NoResultException e) {
- // ignore
- logger.debug(e.getMessage());
- }
- if(xResourceList == null) {
- xResourceList = new ArrayList<XXResource>();
- }
- } else {
- logger.debug("AssetType not provided.");
- xResourceList = new ArrayList<XXResource>();
- }
- return xResourceList;
- }
-
- public Timestamp getMaxUpdateTimeForAssetName(String assetName) {
- if (assetName == null) {
- return null;
- }
- try {
- Date date=(Date)getEntityManager()
- .createNamedQuery("XXResource.getMaxUpdateTimeForAssetName")
- .setParameter("assetName", assetName)
- .getSingleResult();
- if(date!=null){
- Timestamp timestamp=new Timestamp(date.getTime());
- return timestamp;
- }else{
- return null;
- }
- } catch (NoResultException e) {
- // ignore
- }
- return null;
- }
-
- public List<XXResource> findUpdatedResourcesByAssetName(
- String assetName, Date lastUpdated) {
- if (assetName != null) {
- try {
- return getEntityManager()
- .createNamedQuery(
- "XXResource.findUpdatedResourcesByAssetName",
- XXResource.class)
- .setParameter("assetName", assetName)
- .setParameter("lastUpdated", lastUpdated)
- .getResultList();
- } catch (NoResultException e) {
- logger.debug(e.getMessage());
- }
- } else {
- logger.debug("Asset name not provided.");
- return new ArrayList<XXResource>();
- }
- return null;
- }
-
- public List<XXResource> findByResourceNameAndAssetIdAndRecursiveFlag(
- String name,Long assetId,int isRecursive ) {
- if (daoManager.getStringUtil().isEmpty(name)) {
- logger.debug("name is empty");
- return null;
- }
- if (assetId==null) {
- logger.debug("assetId is null");
- return null;
- }
- try {
- String resourceName = name.trim();
- resourceName = "%"+resourceName+"%";
- return getEntityManager()
- .createNamedQuery(
- "XXResource.findByResourceNameAndAssetIdAndRecursiveFlag",
- XXResource.class).setParameter("name", resourceName)
- .setParameter("assetId", assetId)
- .setParameter("isRecursive", isRecursive)
- .getResultList();
- } catch (NoResultException e) {
- // ignore
- }
- return null;
- }
-
- public List<XXResource> findByResourceNameAndAssetIdAndResourceType(String name,Long assetId,int resourceType) {
- if (daoManager.getStringUtil().isEmpty(name)) {
- logger.debug("name is empty");
- return null;
- }
- if (assetId==null) {
- logger.debug("assetId is null");
- return null;
- }
- try {
- String resourceName = name.trim();
- resourceName = "%"+resourceName+"%";
- return getEntityManager()
- .createNamedQuery(
- "XXResource.findByResourceNameAndAssetIdAndResourceType",
- XXResource.class).setParameter("name", resourceName)
- .setParameter("assetId", assetId)
- .setParameter("resourceType", resourceType)
- .getResultList();
- } catch (NoResultException e) {
- // ignore
- }
- return null;
- }
-
- @SuppressWarnings("unchecked")
- public List<XXResource> findByAssetIdAndResourceTypes(Long assetId,
- List<Integer> resourceType) {
- if (assetId == null) {
- logger.debug("assetId is null");
- return null;
- }
- try {
- StringBuffer query = new StringBuffer(
- "SELECT obj FROM XXResource obj WHERE obj.assetId="
- + assetId);
- String whereClause = makeWhereCaluseForResourceType(resourceType);
- if (!whereClause.trim().isEmpty()) {
- query.append(" and ( " + whereClause + " )");
- }
- return getEntityManager().createQuery(query.toString())
- .getResultList();
- } catch (NoResultException e) {
- // ignore
- }
- return null;
- }
-
- private String makeWhereCaluseForResourceType(List<Integer> resourceTypes) {
- StringBuffer whereClause = new StringBuffer();
- if (resourceTypes != null && resourceTypes.size() != 0) {
-
- for (int i = 0; i < resourceTypes.size() - 1; i++) {
- whereClause.append("obj.resourceType=" + resourceTypes.get(i)
- + " OR ");
- }
- whereClause.append("obj.resourceType="
- + resourceTypes.get(resourceTypes.size() - 1));
- }
- return whereClause.toString();
- }
-
- public List<XXResource> findByAssetIdAndResourceStatus(Long assetId, int resourceStatus) {
- List<XXResource> xResourceList = null;
- if (assetId != null) {
- try {
- xResourceList = getEntityManager()
- .createNamedQuery("XXResource.findByAssetIdAndResourceStatus", XXResource.class)
- .setParameter("assetId", assetId)
- .setParameter("resourceStatus", resourceStatus)
- .getResultList();
- } catch (NoResultException e) {
- // ignore
- logger.debug(e.getMessage());
- }
- if(xResourceList == null) {
- xResourceList = new ArrayList<XXResource>();
- }
- } else {
- logger.debug("AssetId not provided.");
- xResourceList = new ArrayList<XXResource>();
- }
- return xResourceList;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/db/XXTrxLogDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/db/XXTrxLogDao.java b/security-admin/src/main/java/com/xasecure/db/XXTrxLogDao.java
deleted file mode 100644
index 8943bc3..0000000
--- a/security-admin/src/main/java/com/xasecure/db/XXTrxLogDao.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * 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 com.xasecure.db;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.persistence.NoResultException;
-
-import org.apache.log4j.Logger;
-
-import com.xasecure.entity.XXTrxLog;
-
-import com.xasecure.common.db.*;
-
-public class XXTrxLogDao extends BaseDao<XXTrxLog> {
- private static Logger logger = Logger.getLogger(XXTrxLogDao.class);
-
- public XXTrxLogDao( XADaoManagerBase daoManager ) {
- super(daoManager);
- }
-
- public List<XXTrxLog> findByTransactionId(String transactionId){
- if(transactionId == null){
- return null;
- }
-
- List<XXTrxLog> xTrxLogList = new ArrayList<XXTrxLog>();
- try {
- xTrxLogList = getEntityManager()
- .createNamedQuery("XXTrxLog.findByTrxId", XXTrxLog.class)
- .setParameter("transactionId", transactionId)
- .getResultList();
- } catch (NoResultException e) {
- logger.debug(e.getMessage());
- }
-
- return xTrxLogList;
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/db/XXUserDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/db/XXUserDao.java b/security-admin/src/main/java/com/xasecure/db/XXUserDao.java
deleted file mode 100644
index 431bc35..0000000
--- a/security-admin/src/main/java/com/xasecure/db/XXUserDao.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * 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 com.xasecure.db;
-
-
-import javax.persistence.NoResultException;
-
-import org.apache.log4j.Logger;
-
-import com.xasecure.entity.XXUser;
-
-import com.xasecure.common.db.*;
-
-public class XXUserDao extends BaseDao<XXUser> {
- static final Logger logger = Logger.getLogger(XXResourceDao.class);
-
- public XXUserDao(XADaoManagerBase daoManager) {
- super(daoManager);
- }
-
- public XXUser findByUserName(String name) {
- if (daoManager.getStringUtil().isEmpty(name)) {
- logger.debug("name is empty");
- return null;
- }
- try {
- return getEntityManager()
- .createNamedQuery("XXUser.findByUserName", XXUser.class)
- .setParameter("name", name.trim())
- .getSingleResult();
- } catch (NoResultException e) {
- // ignore
- }
- return null;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/entity/XXAccessAudit.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/entity/XXAccessAudit.java b/security-admin/src/main/java/com/xasecure/entity/XXAccessAudit.java
deleted file mode 100644
index 726c59e..0000000
--- a/security-admin/src/main/java/com/xasecure/entity/XXAccessAudit.java
+++ /dev/null
@@ -1,651 +0,0 @@
-/*
- * 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 com.xasecure.entity;
-
-/**
- * Access Audit
- *
- */
-
-import java.util.*;
-import javax.persistence.*;
-import javax.xml.bind.annotation.*;
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-
-
-@Entity
-@Table(name="xa_access_audit")
-@XmlRootElement
-public class XXAccessAudit extends XXDBBase implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
- @Id
- @SequenceGenerator(name="XA_ACCESS_AUDIT_SEQ",sequenceName="XA_ACCESS_AUDIT_SEQ",allocationSize=1)
- @GeneratedValue(strategy=GenerationType.AUTO,generator="XA_ACCESS_AUDIT_SEQ")
- @Column(name="ID")
- protected Long id;
-
- @Override
- public void setId(Long id) {
- this.id=id;
- }
- @Override
- public Long getId() {
- return id;
- }
- /**
- * Repository Type
- * <ul>
- * <li>This attribute is of type enum CommonEnums::AssetType
- * </ul>
- *
- */
- @Column(name="AUDIT_TYPE" , nullable=false )
- protected int auditType = AppConstants.ASSET_UNKNOWN;
-
- /**
- * Access Result
- * <ul>
- * <li>This attribute is of type enum CommonEnums::AccessResult
- * </ul>
- *
- */
- @Column(name="ACCESS_RESULT" )
- protected int accessResult = XAConstants.ACCESS_RESULT_DENIED;
-
- /**
- * Access Type
- * <ul>
- * <li>The maximum length for this attribute is <b>255</b>.
- * </ul>
- *
- */
- @Column(name="ACCESS_TYPE" , length=255)
- protected String accessType;
-
- /**
- * Acl Enforcer
- * <ul>
- * <li>The maximum length for this attribute is <b>255</b>.
- * </ul>
- *
- */
- @Column(name="ACL_ENFORCER" , length=255)
- protected String aclEnforcer;
-
- /**
- * Agent Id
- * <ul>
- * <li>The maximum length for this attribute is <b>255</b>.
- * </ul>
- *
- */
- @Column(name="AGENT_ID" , length=255)
- protected String agentId;
-
- /**
- * Client Ip
- * <ul>
- * <li>The maximum length for this attribute is <b>255</b>.
- * </ul>
- *
- */
- @Column(name="CLIENT_IP" , length=255)
- protected String clientIP;
-
- /**
- * Client Type
- * <ul>
- * <li>The maximum length for this attribute is <b>255</b>.
- * </ul>
- *
- */
- @Column(name="CLIENT_TYPE" , length=255)
- protected String clientType;
-
- /**
- * Policy Id
- * <ul>
- * </ul>
- *
- */
- @Column(name="POLICY_ID" )
- protected long policyId;
-
- /**
- * Repository Name
- * <ul>
- * <li>The maximum length for this attribute is <b>255</b>.
- * </ul>
- *
- */
- @Column(name="REPO_NAME" , length=255)
- protected String repoName;
-
- /**
- * Repository Type
- * <ul>
- * </ul>
- *
- */
- @Column(name="REPO_TYPE" )
- protected int repoType;
-
- /**
- * Reason of result
- * <ul>
- * <li>The maximum length for this attribute is <b>255</b>.
- * </ul>
- *
- */
- @Column(name="RESULT_REASON" , length=255)
- protected String resultReason;
-
- /**
- * Session Id
- * <ul>
- * <li>The maximum length for this attribute is <b>255</b>.
- * </ul>
- *
- */
- @Column(name="SESSION_ID" , length=255)
- protected String sessionId;
-
- /**
- * Event Time
- * <ul>
- * </ul>
- *
- */
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name="EVENT_TIME" )
- protected Date eventTime = DateUtil.getUTCDate();
-
- /**
- * Requesting User
- * <ul>
- * <li>The maximum length for this attribute is <b>255</b>.
- * </ul>
- *
- */
- @Column(name="REQUEST_USER" , length=255)
- protected String requestUser;
-
- /**
- * Action
- * <ul>
- * <li>The maximum length for this attribute is <b>2000</b>.
- * </ul>
- *
- */
- @Column(name="ACTION" , length=2000)
- protected String action;
-
- /**
- * Requesting Data
- * <ul>
- * <li>The maximum length for this attribute is <b>2000</b>.
- * </ul>
- *
- */
- @Column(name="REQUEST_DATA" , length=2000)
- protected String requestData;
-
- /**
- * Resource Path
- * <ul>
- * <li>The maximum length for this attribute is <b>2000</b>.
- * </ul>
- *
- */
- @Column(name="RESOURCE_PATH" , length=2000)
- protected String resourcePath;
-
- /**
- * Resource Type
- * <ul>
- * <li>The maximum length for this attribute is <b>255</b>.
- * </ul>
- *
- */
- @Column(name="RESOURCE_TYPE" , length=255)
- protected String resourceType;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public XXAccessAudit ( ) {
- auditType = AppConstants.ASSET_UNKNOWN;
- accessResult = XAConstants.ACCESS_RESULT_DENIED;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_XA_ACCESS_AUDIT;
- }
-
- /**
- * This method sets the value to the member attribute <b>auditType</b>.
- * You cannot set null to the attribute.
- * @param auditType Value to set member attribute <b>auditType</b>
- */
- public void setAuditType( int auditType ) {
- this.auditType = auditType;
- }
-
- /**
- * Returns the value for the member attribute <b>auditType</b>
- * @return int - value of member attribute <b>auditType</b>.
- */
- public int getAuditType( ) {
- return this.auditType;
- }
-
- /**
- * This method sets the value to the member attribute <b>accessResult</b>.
- * You cannot set null to the attribute.
- * @param accessResult Value to set member attribute <b>accessResult</b>
- */
- public void setAccessResult( int accessResult ) {
- this.accessResult = accessResult;
- }
-
- /**
- * Returns the value for the member attribute <b>accessResult</b>
- * @return int - value of member attribute <b>accessResult</b>.
- */
- public int getAccessResult( ) {
- return this.accessResult;
- }
-
- /**
- * This method sets the value to the member attribute <b>accessType</b>.
- * You cannot set null to the attribute.
- * @param accessType Value to set member attribute <b>accessType</b>
- */
- public void setAccessType( String accessType ) {
- this.accessType = accessType;
- }
-
- /**
- * Returns the value for the member attribute <b>accessType</b>
- * @return String - value of member attribute <b>accessType</b>.
- */
- public String getAccessType( ) {
- return this.accessType;
- }
-
- /**
- * This method sets the value to the member attribute <b>aclEnforcer</b>.
- * You cannot set null to the attribute.
- * @param aclEnforcer Value to set member attribute <b>aclEnforcer</b>
- */
- public void setAclEnforcer( String aclEnforcer ) {
- this.aclEnforcer = aclEnforcer;
- }
-
- /**
- * Returns the value for the member attribute <b>aclEnforcer</b>
- * @return String - value of member attribute <b>aclEnforcer</b>.
- */
- public String getAclEnforcer( ) {
- return this.aclEnforcer;
- }
-
- /**
- * This method sets the value to the member attribute <b>agentId</b>.
- * You cannot set null to the attribute.
- * @param agentId Value to set member attribute <b>agentId</b>
- */
- public void setAgentId( String agentId ) {
- this.agentId = agentId;
- }
-
- /**
- * Returns the value for the member attribute <b>agentId</b>
- * @return String - value of member attribute <b>agentId</b>.
- */
- public String getAgentId( ) {
- return this.agentId;
- }
-
- /**
- * This method sets the value to the member attribute <b>clientIP</b>.
- * You cannot set null to the attribute.
- * @param clientIP Value to set member attribute <b>clientIP</b>
- */
- public void setClientIP( String clientIP ) {
- this.clientIP = clientIP;
- }
-
- /**
- * Returns the value for the member attribute <b>clientIP</b>
- * @return String - value of member attribute <b>clientIP</b>.
- */
- public String getClientIP( ) {
- return this.clientIP;
- }
-
- /**
- * This method sets the value to the member attribute <b>clientType</b>.
- * You cannot set null to the attribute.
- * @param clientType Value to set member attribute <b>clientType</b>
- */
- public void setClientType( String clientType ) {
- this.clientType = clientType;
- }
-
- /**
- * Returns the value for the member attribute <b>clientType</b>
- * @return String - value of member attribute <b>clientType</b>.
- */
- public String getClientType( ) {
- return this.clientType;
- }
-
- /**
- * This method sets the value to the member attribute <b>policyId</b>.
- * You cannot set null to the attribute.
- * @param policyId Value to set member attribute <b>policyId</b>
- */
- public void setPolicyId( long policyId ) {
- this.policyId = policyId;
- }
-
- /**
- * Returns the value for the member attribute <b>policyId</b>
- * @return long - value of member attribute <b>policyId</b>.
- */
- public long getPolicyId( ) {
- return this.policyId;
- }
-
- /**
- * This method sets the value to the member attribute <b>repoName</b>.
- * You cannot set null to the attribute.
- * @param repoName Value to set member attribute <b>repoName</b>
- */
- public void setRepoName( String repoName ) {
- this.repoName = repoName;
- }
-
- /**
- * Returns the value for the member attribute <b>repoName</b>
- * @return String - value of member attribute <b>repoName</b>.
- */
- public String getRepoName( ) {
- return this.repoName;
- }
-
- /**
- * This method sets the value to the member attribute <b>repoType</b>.
- * You cannot set null to the attribute.
- * @param repoType Value to set member attribute <b>repoType</b>
- */
- public void setRepoType( int repoType ) {
- this.repoType = repoType;
- }
-
- /**
- * Returns the value for the member attribute <b>repoType</b>
- * @return int - value of member attribute <b>repoType</b>.
- */
- public int getRepoType( ) {
- return this.repoType;
- }
-
- /**
- * This method sets the value to the member attribute <b>resultReason</b>.
- * You cannot set null to the attribute.
- * @param resultReason Value to set member attribute <b>resultReason</b>
- */
- public void setResultReason( String resultReason ) {
- this.resultReason = resultReason;
- }
-
- /**
- * Returns the value for the member attribute <b>resultReason</b>
- * @return String - value of member attribute <b>resultReason</b>.
- */
- public String getResultReason( ) {
- return this.resultReason;
- }
-
- /**
- * This method sets the value to the member attribute <b>sessionId</b>.
- * You cannot set null to the attribute.
- * @param sessionId Value to set member attribute <b>sessionId</b>
- */
- public void setSessionId( String sessionId ) {
- this.sessionId = sessionId;
- }
-
- /**
- * Returns the value for the member attribute <b>sessionId</b>
- * @return String - value of member attribute <b>sessionId</b>.
- */
- public String getSessionId( ) {
- return this.sessionId;
- }
-
- /**
- * This method sets the value to the member attribute <b>eventTime</b>.
- * You cannot set null to the attribute.
- * @param eventTime Value to set member attribute <b>eventTime</b>
- */
- public void setEventTime( Date eventTime ) {
- this.eventTime = eventTime;
- }
-
- /**
- * Returns the value for the member attribute <b>eventTime</b>
- * @return Date - value of member attribute <b>eventTime</b>.
- */
- public Date getEventTime( ) {
- return this.eventTime;
- }
-
- /**
- * This method sets the value to the member attribute <b>requestUser</b>.
- * You cannot set null to the attribute.
- * @param requestUser Value to set member attribute <b>requestUser</b>
- */
- public void setRequestUser( String requestUser ) {
- this.requestUser = requestUser;
- }
-
- /**
- * Returns the value for the member attribute <b>requestUser</b>
- * @return String - value of member attribute <b>requestUser</b>.
- */
- public String getRequestUser( ) {
- return this.requestUser;
- }
-
- /**
- * This method sets the value to the member attribute <b>action</b>.
- * You cannot set null to the attribute.
- * @param action Value to set member attribute <b>action</b>
- */
- public void setAction( String action ) {
- this.action = action;
- }
-
- /**
- * Returns the value for the member attribute <b>action</b>
- * @return String - value of member attribute <b>action</b>.
- */
- public String getAction( ) {
- return this.action;
- }
-
- /**
- * This method sets the value to the member attribute <b>requestData</b>.
- * You cannot set null to the attribute.
- * @param requestData Value to set member attribute <b>requestData</b>
- */
- public void setRequestData( String requestData ) {
- this.requestData = requestData;
- }
-
- /**
- * Returns the value for the member attribute <b>requestData</b>
- * @return String - value of member attribute <b>requestData</b>.
- */
- public String getRequestData( ) {
- return this.requestData;
- }
-
- /**
- * This method sets the value to the member attribute <b>resourcePath</b>.
- * You cannot set null to the attribute.
- * @param resourcePath Value to set member attribute <b>resourcePath</b>
- */
- public void setResourcePath( String resourcePath ) {
- this.resourcePath = resourcePath;
- }
-
- /**
- * Returns the value for the member attribute <b>resourcePath</b>
- * @return String - value of member attribute <b>resourcePath</b>.
- */
- public String getResourcePath( ) {
- return this.resourcePath;
- }
-
- /**
- * This method sets the value to the member attribute <b>resourceType</b>.
- * You cannot set null to the attribute.
- * @param resourceType Value to set member attribute <b>resourceType</b>
- */
- public void setResourceType( String resourceType ) {
- this.resourceType = resourceType;
- }
-
- /**
- * Returns the value for the member attribute <b>resourceType</b>
- * @return String - value of member attribute <b>resourceType</b>.
- */
- public String getResourceType( ) {
- return this.resourceType;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- @Override
- public String toString( ) {
- String str = "XXAccessAudit={";
- str += super.toString();
- str += "auditType={" + auditType + "} ";
- str += "accessResult={" + accessResult + "} ";
- str += "accessType={" + accessType + "} ";
- str += "aclEnforcer={" + aclEnforcer + "} ";
- str += "agentId={" + agentId + "} ";
- str += "clientIP={" + clientIP + "} ";
- str += "clientType={" + clientType + "} ";
- str += "policyId={" + policyId + "} ";
- str += "repoName={" + repoName + "} ";
- str += "repoType={" + repoType + "} ";
- str += "resultReason={" + resultReason + "} ";
- str += "sessionId={" + sessionId + "} ";
- str += "eventTime={" + eventTime + "} ";
- str += "requestUser={" + requestUser + "} ";
- str += "action={" + action + "} ";
- str += "requestData={" + requestData + "} ";
- str += "resourcePath={" + resourcePath + "} ";
- str += "resourceType={" + resourceType + "} ";
- str += "}";
- return str;
- }
-
- /**
- * Checks for all attributes except referenced db objects
- * @return true if all attributes match
- */
- @Override
- public boolean equals( Object obj) {
- if ( !super.equals(obj) ) {
- return false;
- }
- XXAccessAudit other = (XXAccessAudit) obj;
- if( this.auditType != other.auditType ) return false;
- if( this.accessResult != other.accessResult ) return false;
- if ((this.accessType == null && other.accessType != null) || (this.accessType != null && !this.accessType.equals(other.accessType))) {
- return false;
- }
- if ((this.aclEnforcer == null && other.aclEnforcer != null) || (this.aclEnforcer != null && !this.aclEnforcer.equals(other.aclEnforcer))) {
- return false;
- }
- if ((this.agentId == null && other.agentId != null) || (this.agentId != null && !this.agentId.equals(other.agentId))) {
- return false;
- }
- if ((this.clientIP == null && other.clientIP != null) || (this.clientIP != null && !this.clientIP.equals(other.clientIP))) {
- return false;
- }
- if ((this.clientType == null && other.clientType != null) || (this.clientType != null && !this.clientType.equals(other.clientType))) {
- return false;
- }
- if( this.policyId != other.policyId ) return false;
- if ((this.repoName == null && other.repoName != null) || (this.repoName != null && !this.repoName.equals(other.repoName))) {
- return false;
- }
- if( this.repoType != other.repoType ) return false;
- if ((this.resultReason == null && other.resultReason != null) || (this.resultReason != null && !this.resultReason.equals(other.resultReason))) {
- return false;
- }
- if ((this.sessionId == null && other.sessionId != null) || (this.sessionId != null && !this.sessionId.equals(other.sessionId))) {
- return false;
- }
- if ((this.eventTime == null && other.eventTime != null) || (this.eventTime != null && !this.eventTime.equals(other.eventTime))) {
- return false;
- }
- if ((this.requestUser == null && other.requestUser != null) || (this.requestUser != null && !this.requestUser.equals(other.requestUser))) {
- return false;
- }
- if ((this.action == null && other.action != null) || (this.action != null && !this.action.equals(other.action))) {
- return false;
- }
- if ((this.requestData == null && other.requestData != null) || (this.requestData != null && !this.requestData.equals(other.requestData))) {
- return false;
- }
- if ((this.resourcePath == null && other.resourcePath != null) || (this.resourcePath != null && !this.resourcePath.equals(other.resourcePath))) {
- return false;
- }
- if ((this.resourceType == null && other.resourceType != null) || (this.resourceType != null && !this.resourceType.equals(other.resourceType))) {
- return false;
- }
- return true;
- }
- public static String getEnumName(String fieldName ) {
- if( fieldName.equals("auditType") ) {
- return "CommonEnums.AssetType";
- }
- if( fieldName.equals("accessResult") ) {
- return "CommonEnums.AccessResult";
- }
- //Later TODO
- //return super.getEnumName(fieldName);
- return null;
- }
-
-}
[47/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/provider/DbAuditProvider.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/DbAuditProvider.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/DbAuditProvider.java
new file mode 100644
index 0000000..7414a7a
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/DbAuditProvider.java
@@ -0,0 +1,355 @@
+/**
+ * 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.audit.provider;
+
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Properties;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.EntityTransaction;
+import javax.persistence.Persistence;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.audit.dao.DaoManager;
+import org.apache.ranger.audit.model.AuditEventBase;
+import org.apache.ranger.authorization.hadoop.utils.RangerCredentialProvider;
+
+
+/*
+ * NOTE:
+ * - Instances of this class are not thread-safe.
+ */
+public class DbAuditProvider extends BaseAuditProvider {
+
+ private static final Log LOG = LogFactory.getLog(DbAuditProvider.class);
+
+ public static final String AUDIT_DB_IS_ASYNC_PROP = "xasecure.audit.db.is.async";
+ public static final String AUDIT_DB_MAX_QUEUE_SIZE_PROP = "xasecure.audit.db.async.max.queue.size" ;
+ public static final String AUDIT_DB_MAX_FLUSH_INTERVAL_PROP = "xasecure.audit.db.async.max.flush.interval.ms";
+
+ private static final String AUDIT_DB_BATCH_SIZE_PROP = "xasecure.audit.db.batch.size" ;
+ private static final String AUDIT_DB_RETRY_MIN_INTERVAL_PROP = "xasecure.audit.db.config.retry.min.interval.ms";
+ private static final String AUDIT_JPA_CONFIG_PROP_PREFIX = "xasecure.audit.jpa.";
+ private static final String AUDIT_DB_CREDENTIAL_PROVIDER_FILE = "xasecure.audit.credential.provider.file";
+ private static final String AUDIT_DB_CREDENTIAL_PROVIDER_ALIAS = "auditDBCred";
+ private static final String AUDIT_JPA_JDBC_PASSWORD = "javax.persistence.jdbc.password";
+
+ private EntityManagerFactory entityManagerFactory;
+ private DaoManager daoManager;
+
+ private int mCommitBatchSize = 1;
+ private int mDbRetryMinIntervalMs = 60 * 1000;
+ private long mLastCommitTime = System.currentTimeMillis();
+ private ArrayList<AuditEventBase> mUncommitted = new ArrayList<AuditEventBase>();
+ private Map<String, String> mDbProperties = null;
+ private long mLastDbFailedTime = 0;
+
+ public DbAuditProvider() {
+ LOG.info("DbAuditProvider: creating..");
+ }
+
+ @Override
+ public void init(Properties props) {
+ LOG.info("DbAuditProvider.init()");
+
+ super.init(props);
+
+ mDbProperties = BaseAuditProvider.getPropertiesWithPrefix(props, AUDIT_JPA_CONFIG_PROP_PREFIX);
+ mCommitBatchSize = BaseAuditProvider.getIntProperty(props, AUDIT_DB_BATCH_SIZE_PROP, 1000);
+ mDbRetryMinIntervalMs = BaseAuditProvider.getIntProperty(props, AUDIT_DB_RETRY_MIN_INTERVAL_PROP, 15 * 1000);
+
+ boolean isAsync = BaseAuditProvider.getBooleanProperty(props, AUDIT_DB_IS_ASYNC_PROP, false);
+
+ if(! isAsync) {
+ mCommitBatchSize = 1; // Batching not supported in sync mode
+ }
+
+ String jdbcPassword = getCredentialString(BaseAuditProvider.getStringProperty(props, AUDIT_DB_CREDENTIAL_PROVIDER_FILE), AUDIT_DB_CREDENTIAL_PROVIDER_ALIAS);
+
+ if(jdbcPassword != null && !jdbcPassword.isEmpty()) {
+ mDbProperties.put(AUDIT_JPA_JDBC_PASSWORD, jdbcPassword);
+ }
+ }
+
+ @Override
+ public void log(AuditEventBase event) {
+ LOG.debug("DbAuditProvider.log()");
+
+ boolean isSuccess = false;
+
+ try {
+ if(preCreate(event)) {
+ DaoManager daoMgr = daoManager;
+
+ if(daoMgr != null) {
+ event.persist(daoMgr);
+
+ isSuccess = postCreate(event);
+ }
+ }
+ } catch(Exception excp) {
+ logDbError("DbAuditProvider.log(): failed", excp);
+ } finally {
+ if(! isSuccess) {
+ logFailedEvent(event);
+ }
+ }
+ }
+
+ @Override
+ public void start() {
+ LOG.info("DbAuditProvider.start()");
+
+ init();
+ }
+
+ @Override
+ public void stop() {
+ LOG.info("DbAuditProvider.stop()");
+
+ cleanUp();
+ }
+
+ @Override
+ public void waitToComplete() {
+ LOG.info("DbAuditProvider.waitToComplete()");
+ }
+
+ @Override
+ public boolean isFlushPending() {
+ return mUncommitted.size() > 0;
+ }
+
+ @Override
+ public long getLastFlushTime() {
+ return mLastCommitTime;
+ }
+
+ @Override
+ public void flush() {
+ if(mUncommitted.size() > 0) {
+ boolean isSuccess = commitTransaction();
+
+ if(! isSuccess) {
+ for(AuditEventBase evt : mUncommitted) {
+ logFailedEvent(evt);
+ }
+ }
+
+ mUncommitted.clear();
+ }
+ }
+
+ private synchronized boolean init() {
+ long now = System.currentTimeMillis();
+
+ if((now - mLastDbFailedTime) < mDbRetryMinIntervalMs) {
+ return false;
+ }
+
+ LOG.info("DbAuditProvider: init()");
+
+ try {
+ entityManagerFactory = Persistence.createEntityManagerFactory("xa_server", mDbProperties);
+
+ daoManager = new DaoManager();
+ daoManager.setEntityManagerFactory(entityManagerFactory);
+
+ daoManager.getEntityManager(); // this forces the connection to be made to DB
+ } catch(Exception excp) {
+ logDbError("DbAuditProvider: DB initalization failed", excp);
+
+ cleanUp();
+
+ return false;
+ }
+
+ return true;
+ }
+
+ private synchronized void cleanUp() {
+ LOG.info("DbAuditProvider: cleanUp()");
+
+ try {
+ if(entityManagerFactory != null && entityManagerFactory.isOpen()) {
+ entityManagerFactory.close();
+ }
+ } catch(Exception excp) {
+ LOG.error("DbAuditProvider.cleanUp(): failed", excp);
+ } finally {
+ entityManagerFactory = null;
+ daoManager = null;
+ }
+ }
+
+ private boolean isDbConnected() {
+ EntityManager em = getEntityManager();
+
+ return em != null && em.isOpen();
+ }
+
+ private EntityManager getEntityManager() {
+ DaoManager daoMgr = daoManager;
+
+ if(daoMgr != null) {
+ try {
+ return daoMgr.getEntityManager();
+ } catch(Exception excp) {
+ logDbError("DbAuditProvider.getEntityManager(): failed", excp);
+
+ cleanUp();
+ }
+ }
+
+ return null;
+ }
+
+ private void clearEntityManager() {
+ try {
+ EntityManager em = getEntityManager();
+
+ if(em != null) {
+ em.clear();
+ }
+ } catch(Exception excp) {
+ LOG.warn("DbAuditProvider.clearEntityManager(): failed", excp);
+ }
+ }
+
+ private EntityTransaction getTransaction() {
+ EntityManager em = getEntityManager();
+
+ return em != null ? em.getTransaction() : null;
+ }
+
+ private boolean isInTransaction() {
+ EntityTransaction trx = getTransaction();
+
+ return trx != null && trx.isActive();
+ }
+
+ private boolean beginTransaction() {
+ EntityTransaction trx = getTransaction();
+
+ if(trx != null && !trx.isActive()) {
+ trx.begin();
+ }
+
+ if(trx == null) {
+ LOG.warn("DbAuditProvider.beginTransaction(): trx is null");
+ }
+
+ return trx != null;
+ }
+
+ private boolean commitTransaction() {
+ boolean ret = false;
+ EntityTransaction trx = null;
+
+ try {
+ trx = getTransaction();
+
+ if(trx != null && trx.isActive()) {
+ trx.commit();
+
+ ret =true;
+ } else {
+ throw new Exception("trx is null or not active");
+ }
+ } catch(Exception excp) {
+ logDbError("DbAuditProvider.commitTransaction(): failed", excp);
+
+ cleanUp(); // so that next insert will try to init()
+ } finally {
+ mLastCommitTime = System.currentTimeMillis();
+
+ clearEntityManager();
+ }
+
+ return ret;
+ }
+
+ private boolean preCreate(AuditEventBase event) {
+ boolean ret = true;
+
+ if(!isDbConnected()) {
+ ret = init();
+ }
+
+ if(ret) {
+ if(! isInTransaction()) {
+ ret = beginTransaction();
+ }
+ }
+
+ return ret;
+ }
+
+ private boolean postCreate(AuditEventBase event) {
+ boolean ret = true;
+
+ if(mCommitBatchSize <= 1) {
+ ret = commitTransaction();
+ } else {
+ mUncommitted.add(event);
+
+ if((mUncommitted.size() % mCommitBatchSize) == 0) {
+ ret = commitTransaction();
+
+ if(! ret) {
+ for(AuditEventBase evt : mUncommitted) {
+ if(evt != event) {
+ logFailedEvent(evt);
+ }
+ }
+ }
+
+ mUncommitted.clear();
+ }
+ }
+ return ret;
+ }
+
+ private void logDbError(String msg, Exception excp) {
+ long now = System.currentTimeMillis();
+
+ if((now - mLastDbFailedTime) > mDbRetryMinIntervalMs) {
+ mLastDbFailedTime = now;
+ }
+
+ LOG.warn(msg, excp);
+ }
+
+ private String getCredentialString(String url,String alias) {
+ String ret = null;
+
+ if(url != null && alias != null) {
+ char[] cred = RangerCredentialProvider.getInstance().getCredentialString(url,alias);
+
+ if ( cred != null ) {
+ ret = new String(cred);
+ }
+ }
+
+ return ret;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/provider/DebugTracer.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/DebugTracer.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/DebugTracer.java
new file mode 100644
index 0000000..7396fd0
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/DebugTracer.java
@@ -0,0 +1,28 @@
+/*
+ * 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.audit.provider;
+
+public interface DebugTracer {
+ void debug(String msg);
+ void debug(String msg, Throwable excp);
+ void info(String msg);
+ void info(String msg, Throwable excp);
+ void warn(String msg);
+ void warn(String msg, Throwable excp);
+ void error(String msg);
+ void error(String msg, Throwable excp);
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/provider/DummyAuditProvider.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/DummyAuditProvider.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/DummyAuditProvider.java
new file mode 100644
index 0000000..a6e3ef1
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/DummyAuditProvider.java
@@ -0,0 +1,65 @@
+/**
+ * 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.audit.provider;
+
+import java.util.Properties;
+
+import org.apache.ranger.audit.model.AuditEventBase;
+
+
+public class DummyAuditProvider implements AuditProvider {
+ @Override
+ public void init(Properties prop) {
+ // intentionally left empty
+ }
+
+ @Override
+ public void log(AuditEventBase event) {
+ // intentionally left empty
+ }
+
+ @Override
+ public void start() {
+ // intentionally left empty
+ }
+
+ @Override
+ public void stop() {
+ // intentionally left empty
+ }
+
+ @Override
+ public void waitToComplete() {
+ // intentionally left empty
+ }
+
+ @Override
+ public boolean isFlushPending() {
+ return false;
+ }
+
+ @Override
+ public long getLastFlushTime() {
+ return 0;
+ }
+
+ @Override
+ public void flush() {
+ // intentionally left empty
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/provider/LocalFileLogBuffer.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/LocalFileLogBuffer.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/LocalFileLogBuffer.java
new file mode 100644
index 0000000..cdc4d53
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/LocalFileLogBuffer.java
@@ -0,0 +1,687 @@
+/*
+ * 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.audit.provider;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileFilter;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.UnsupportedEncodingException;
+import java.io.Writer;
+import java.security.PrivilegedAction;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.TreeSet;
+
+import org.apache.hadoop.security.UserGroupInformation;
+
+
+public class LocalFileLogBuffer<T> implements LogBuffer<T> {
+ private String mDirectory = null;
+ private String mFile = null;
+ private int mFlushIntervalSeconds = 1 * 60;
+ private int mFileBufferSizeBytes = 8 * 1024;
+ private String mEncoding = null;
+ private boolean mIsAppend = true;
+ private int mRolloverIntervalSeconds = 10 * 60;
+ private String mArchiveDirectory = null;
+ private int mArchiveFileCount = 10;
+ private DebugTracer mLogger = null;
+
+ private Writer mWriter = null;
+ private String mBufferFilename = null;
+ private long mNextRolloverTime = 0;
+ private long mNextFlushTime = 0;
+ private int mFileOpenRetryIntervalInMs = 60 * 1000;
+ private long mNextFileOpenRetryTime = 0;
+
+ private DestinationDispatcherThread<T> mDispatcherThread = null;
+
+ public LocalFileLogBuffer(DebugTracer tracer) {
+ mLogger = tracer;
+ }
+
+ public String getDirectory() {
+ return mDirectory;
+ }
+
+ public void setDirectory(String directory) {
+ mDirectory = directory;
+ }
+
+ public String getFile() {
+ return mFile;
+ }
+
+ public void setFile(String file) {
+ mFile = file;
+ }
+
+ public int getFileBufferSizeBytes() {
+ return mFileBufferSizeBytes;
+ }
+
+ public void setFileBufferSizeBytes(int fileBufferSizeBytes) {
+ mFileBufferSizeBytes = fileBufferSizeBytes;
+ }
+
+ public int getFlushIntervalSeconds() {
+ return mFlushIntervalSeconds;
+ }
+
+ public void setFlushIntervalSeconds(int flushIntervalSeconds) {
+ mFlushIntervalSeconds = flushIntervalSeconds;
+ }
+
+ public String getEncoding() {
+ return mEncoding;
+ }
+
+ public void setEncoding(String encoding) {
+ mEncoding = encoding;
+ }
+
+ public boolean getIsAppend() {
+ return mIsAppend;
+ }
+
+ public void setIsAppend(boolean isAppend) {
+ mIsAppend = isAppend;
+ }
+
+ public int getRolloverIntervalSeconds() {
+ return mRolloverIntervalSeconds;
+ }
+
+ public void setRolloverIntervalSeconds(int rolloverIntervalSeconds) {
+ mRolloverIntervalSeconds = rolloverIntervalSeconds;
+ }
+
+ public String getArchiveDirectory() {
+ return mArchiveDirectory;
+ }
+
+ public void setArchiveDirectory(String archiveDirectory) {
+ mArchiveDirectory = archiveDirectory;
+ }
+
+ public int getArchiveFileCount() {
+ return mArchiveFileCount;
+ }
+
+ public void setArchiveFileCount(int archiveFileCount) {
+ mArchiveFileCount = archiveFileCount;
+ }
+
+
+ @Override
+ public void start(LogDestination<T> destination) {
+ mLogger.debug("==> LocalFileLogBuffer.start()");
+
+ mDispatcherThread = new DestinationDispatcherThread<T>(this, destination, mLogger);
+
+ mDispatcherThread.start();
+
+ mLogger.debug("<== LocalFileLogBuffer.start()");
+ }
+
+ @Override
+ public void stop() {
+ mLogger.debug("==> LocalFileLogBuffer.stop()");
+
+ DestinationDispatcherThread<T> dispatcherThread = mDispatcherThread;
+ mDispatcherThread = null;
+
+ if(dispatcherThread != null && dispatcherThread.isAlive()) {
+ dispatcherThread.stopThread();
+
+ try {
+ dispatcherThread.join();
+ } catch (InterruptedException e) {
+ mLogger.warn("LocalFileLogBuffer.stop(): failed in waiting for DispatcherThread", e);
+ }
+ }
+
+ closeFile();
+
+ mLogger.debug("<== LocalFileLogBuffer.stop()");
+ }
+
+ @Override
+ public boolean isAvailable() {
+ return mWriter != null;
+ }
+
+ @Override
+ public boolean add(T log) {
+ boolean ret = false;
+
+ String msg = MiscUtil.stringify(log);
+
+ if(msg.contains(MiscUtil.LINE_SEPARATOR)) {
+ msg = msg.replace(MiscUtil.LINE_SEPARATOR, MiscUtil.ESCAPE_STR + MiscUtil.LINE_SEPARATOR);
+ }
+
+ synchronized(this) {
+ checkFileStatus();
+
+ Writer writer = mWriter;
+
+ if(writer != null) {
+ try {
+ writer.write(msg + MiscUtil.LINE_SEPARATOR);
+
+ if(mFileBufferSizeBytes == 0) {
+ writer.flush();
+ }
+
+ ret = true;
+ } catch(IOException excp) {
+ mLogger.warn("LocalFileLogBuffer.add(): write failed", excp);
+
+ closeFile();
+ }
+ }
+ }
+
+ return ret;
+ }
+
+ @Override
+ public boolean isEmpty() {
+ return mDispatcherThread == null || mDispatcherThread.isIdle();
+ }
+
+ private synchronized void openFile() {
+ mLogger.debug("==> LocalFileLogBuffer.openFile()");
+
+ long now = System.currentTimeMillis();
+
+ closeFile();
+
+ if(mNextFileOpenRetryTime <= now) {
+ try {
+ mNextRolloverTime = MiscUtil.getNextRolloverTime(mNextRolloverTime, (mRolloverIntervalSeconds * 1000L));
+
+ long startTime = MiscUtil.getRolloverStartTime(mNextRolloverTime, (mRolloverIntervalSeconds * 1000L));
+
+ mBufferFilename = MiscUtil.replaceTokens(mDirectory + File.separator + mFile, startTime);
+
+ MiscUtil.createParents(new File(mBufferFilename));
+
+ FileOutputStream ostream = null;
+ try {
+ ostream = new FileOutputStream(mBufferFilename, mIsAppend);
+ } catch(Exception excp) {
+ mLogger.warn("LocalFileLogBuffer.openFile(): failed to open file " + mBufferFilename, excp);
+ }
+
+ if(ostream != null) {
+ mWriter = createWriter(ostream);
+
+ if(mWriter != null) {
+ mLogger.debug("LocalFileLogBuffer.openFile(): opened file " + mBufferFilename);
+
+ mNextFlushTime = System.currentTimeMillis() + (mFlushIntervalSeconds * 1000L);
+ } else {
+ mLogger.warn("LocalFileLogBuffer.openFile(): failed to open file for write " + mBufferFilename);
+
+ mBufferFilename = null;
+ }
+ }
+ } finally {
+ if(mWriter == null) {
+ mNextFileOpenRetryTime = now + mFileOpenRetryIntervalInMs;
+ }
+ }
+ }
+
+ mLogger.debug("<== LocalFileLogBuffer.openFile()");
+ }
+
+ private synchronized void closeFile() {
+ mLogger.debug("==> LocalFileLogBuffer.closeFile()");
+
+ Writer writer = mWriter;
+
+ mWriter = null;
+
+ if(writer != null) {
+ try {
+ writer.flush();
+ writer.close();
+ } catch(IOException excp) {
+ mLogger.warn("LocalFileLogBuffer: failed to close file " + mBufferFilename, excp);
+ }
+
+ if(mDispatcherThread != null) {
+ mDispatcherThread.addLogfile(mBufferFilename);
+ }
+ }
+
+ mLogger.debug("<== LocalFileLogBuffer.closeFile()");
+ }
+
+ private void rollover() {
+ mLogger.debug("==> LocalFileLogBuffer.rollover()");
+
+ closeFile();
+
+ openFile();
+
+ mLogger.debug("<== LocalFileLogBuffer.rollover()");
+ }
+
+ private void checkFileStatus() {
+ long now = System.currentTimeMillis();
+
+ if(now > mNextRolloverTime) {
+ rollover();
+ } else if(mWriter == null) {
+ openFile();
+ } else if(now > mNextFlushTime) {
+ try {
+ mNextFlushTime = now + (mFlushIntervalSeconds * 1000L);
+
+ mWriter.flush();
+ } catch (IOException excp) {
+ mLogger.warn("LocalFileLogBuffer: failed to flush to file " + mBufferFilename, excp);
+ }
+ }
+ }
+
+ private Writer createWriter(OutputStream os ) {
+ Writer writer = null;
+
+ if(os != null) {
+ if(mEncoding != null) {
+ try {
+ writer = new OutputStreamWriter(os, mEncoding);
+ } catch(UnsupportedEncodingException excp) {
+ mLogger.warn("LocalFileLogBuffer: failed to create output writer for file " + mBufferFilename, excp);
+ }
+ }
+
+ if(writer == null) {
+ writer = new OutputStreamWriter(os);
+ }
+
+ if(mFileBufferSizeBytes > 0 && writer != null) {
+ writer = new BufferedWriter(writer, mFileBufferSizeBytes);
+ }
+ }
+
+ return writer;
+ }
+
+ boolean isCurrentFilename(String filename) {
+ return mBufferFilename != null && filename != null && filename.equals(mBufferFilename);
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+
+ sb.append("LocalFileLogBuffer {");
+ sb.append("Directory=").append(mDirectory).append("; ");
+ sb.append("File=").append(mFile).append("; ");
+ sb.append("RolloverIntervaSeconds=").append(mRolloverIntervalSeconds).append("; ");
+ sb.append("ArchiveDirectory=").append(mArchiveDirectory).append("; ");
+ sb.append("ArchiveFileCount=").append(mArchiveFileCount);
+ sb.append("}");
+
+ return sb.toString();
+ }
+
+}
+
+class DestinationDispatcherThread<T> extends Thread {
+ private TreeSet<String> mCompletedLogfiles = new TreeSet<String>();
+ private boolean mStopThread = false;
+ private LocalFileLogBuffer<T> mFileLogBuffer = null;
+ private LogDestination<T> mDestination = null;
+ private DebugTracer mLogger = null;
+
+ private String mCurrentLogfile = null;
+ private BufferedReader mReader = null;
+
+ public DestinationDispatcherThread(LocalFileLogBuffer<T> fileLogBuffer, LogDestination<T> destination, DebugTracer tracer) {
+ super(DestinationDispatcherThread.class.getSimpleName() + "-" + System.currentTimeMillis());
+
+ mLogger = tracer;
+
+ mFileLogBuffer = fileLogBuffer;
+ mDestination = destination;
+
+ setDaemon(true);
+ }
+
+ public void addLogfile(String filename) {
+ mLogger.debug("==> DestinationDispatcherThread.addLogfile(" + filename + ")");
+
+ if(filename != null) {
+ synchronized(mCompletedLogfiles) {
+ mCompletedLogfiles.add(filename);
+ mCompletedLogfiles.notify();
+ }
+ }
+
+ mLogger.debug("<== DestinationDispatcherThread.addLogfile(" + filename + ")");
+ }
+
+ public void stopThread() {
+ mStopThread = true;
+ }
+
+ public boolean isIdle() {
+ synchronized(mCompletedLogfiles) {
+ return mCompletedLogfiles.isEmpty() && mCurrentLogfile == null;
+ }
+ }
+
+ @Override
+ public void run() {
+ UserGroupInformation loginUser = null;
+
+ try {
+ loginUser = UserGroupInformation.getLoginUser();
+ } catch (IOException excp) {
+ mLogger.error("DestinationDispatcherThread.run(): failed to get login user details. Audit files will not be sent to HDFS destination", excp);
+ }
+
+ if(loginUser == null) {
+ mLogger.error("DestinationDispatcherThread.run(): failed to get login user. Audit files will not be sent to HDFS destination");
+
+ return;
+ }
+
+ loginUser.doAs(new PrivilegedAction<Integer>() {
+ @Override
+ public Integer run() {
+ doRun();
+
+ return 0;
+ }
+ });
+ }
+
+ private void doRun() {
+ init();
+
+ mDestination.start();
+
+ long pollIntervalInMs = 1000L;
+
+ while(! mStopThread) {
+ synchronized(mCompletedLogfiles) {
+ while(mCompletedLogfiles.isEmpty() && !mStopThread) {
+ try {
+ mCompletedLogfiles.wait(pollIntervalInMs);
+ } catch(InterruptedException excp) {
+ throw new RuntimeException("DestinationDispatcherThread.run(): failed to wait for log file", excp);
+ }
+ }
+
+ mCurrentLogfile = mCompletedLogfiles.pollFirst();
+ }
+
+ if(mCurrentLogfile != null) {
+ sendCurrentFile();
+ }
+ }
+
+ mDestination.stop();
+ }
+
+ private void init() {
+ mLogger.debug("==> DestinationDispatcherThread.init()");
+
+ String dirName = MiscUtil.replaceTokens(mFileLogBuffer.getDirectory(), 0);
+
+ if(dirName != null) {
+ File directory = new File(dirName);
+
+ if(directory.exists() && directory.isDirectory()) {
+ File[] files = directory.listFiles();
+
+ if(files != null) {
+ for(File file : files) {
+ if(file.exists() && file.isFile() && file.canRead()) {
+ String filename = file.getAbsolutePath();
+ if(! mFileLogBuffer.isCurrentFilename(filename)) {
+ addLogfile(filename);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ mLogger.debug("<== DestinationDispatcherThread.init()");
+ }
+
+ private boolean sendCurrentFile() {
+ mLogger.debug("==> DestinationDispatcherThread.sendCurrentFile()");
+
+ boolean ret = false;
+
+ long destinationPollIntervalInMs = 1000L;
+
+ openCurrentFile();
+
+ while(!mStopThread) {
+ String log = getNextStringifiedLog();
+
+ if(log == null) { // reached end-of-file
+ ret = true;
+
+ break;
+ }
+
+ // loop until log is sent successfully
+ while(!mStopThread && !mDestination.sendStringified(log)) {
+ try {
+ Thread.sleep(destinationPollIntervalInMs);
+ } catch(InterruptedException excp) {
+ throw new RuntimeException("LocalFileLogBuffer.sendCurrentFile(" + mCurrentLogfile + "): failed while waiting for destination to be available", excp);
+ }
+ }
+ }
+
+ closeCurrentFile();
+
+ if(!mStopThread) {
+ mDestination.flush();
+ archiveCurrentFile();
+ }
+
+ mLogger.debug("<== DestinationDispatcherThread.sendCurrentFile()");
+
+ return ret;
+ }
+
+ private String getNextStringifiedLog() {
+ String log = null;
+
+ if(mReader != null) {
+ try {
+ while(true) {
+ String line = mReader.readLine();
+
+ if(line == null) { // reached end-of-file
+ break;
+ }
+
+ if(line.endsWith(MiscUtil.ESCAPE_STR)) {
+ line = line.substring(0, line.length() - MiscUtil.ESCAPE_STR.length());
+
+ if(log == null) {
+ log = line;
+ } else {
+ log += MiscUtil.LINE_SEPARATOR;
+ log += line;
+ }
+
+ continue;
+ } else {
+ if(log == null) {
+ log = line;
+ } else {
+ log += line;
+ }
+ break;
+ }
+ }
+ } catch (IOException excp) {
+ mLogger.warn("getNextStringifiedLog.getNextLog(): failed to read from file " + mCurrentLogfile, excp);
+ }
+ }
+
+ return log;
+ }
+
+ private void openCurrentFile() {
+ mLogger.debug("==> openCurrentFile(" + mCurrentLogfile + ")");
+
+ if(mCurrentLogfile != null) {
+ try {
+ FileInputStream inStr = new FileInputStream(mCurrentLogfile);
+
+ InputStreamReader strReader = createReader(inStr);
+
+ if(strReader != null) {
+ mReader = new BufferedReader(strReader);
+ }
+ } catch(FileNotFoundException excp) {
+ mLogger.warn("openNextFile(): error while opening file " + mCurrentLogfile, excp);
+ }
+ }
+
+ mLogger.debug("<== openCurrentFile(" + mCurrentLogfile + ")");
+ }
+
+ private void closeCurrentFile() {
+ mLogger.debug("==> closeCurrentFile(" + mCurrentLogfile + ")");
+
+ if(mReader != null) {
+ try {
+ mReader.close();
+ } catch(IOException excp) {
+ // ignore
+ }
+ }
+ mReader = null;
+
+ mLogger.debug("<== closeCurrentFile(" + mCurrentLogfile + ")");
+ }
+
+ private void archiveCurrentFile() {
+ if(mCurrentLogfile != null) {
+ File logFile = new File(mCurrentLogfile);
+ String archiveDirName = MiscUtil.replaceTokens(mFileLogBuffer.getArchiveDirectory(), 0);
+ String archiveFilename = archiveDirName + File.separator +logFile.getName();
+
+ try {
+ if(logFile.exists()) {
+ File archiveFile = new File(archiveFilename);
+
+ MiscUtil.createParents(archiveFile);
+
+ if(! logFile.renameTo(archiveFile)) {
+ // TODO: renameTo() does not work in all cases. in case of failure, copy the file contents to the destination and delete the file
+ mLogger.warn("archiving failed to move file: " + mCurrentLogfile + " ==> " + archiveFilename);
+ }
+
+ File archiveDir = new File(archiveDirName);
+ File[] files = archiveDir.listFiles(new FileFilter() {
+ @Override
+ public boolean accept(File f) {
+ return f.isFile();
+ }
+ });
+
+ int numOfFilesToDelete = files == null ? 0 : (files.length - mFileLogBuffer.getArchiveFileCount());
+
+ if(numOfFilesToDelete > 0) {
+ Arrays.sort(files, new Comparator<File>() {
+ @Override
+ public int compare(File f1, File f2) {
+ return (int)(f1.lastModified() - f2.lastModified());
+ }
+ });
+
+ for(int i = 0; i < numOfFilesToDelete; i++) {
+ if(! files[i].delete()) {
+ mLogger.warn("archiving failed to delete file: " + files[i].getAbsolutePath());
+ }
+ }
+ }
+ }
+ } catch(Exception excp) {
+ mLogger.warn("archiveCurrentFile(): faile to move " + mCurrentLogfile + " to archive location " + archiveFilename, excp);
+ }
+ }
+ mCurrentLogfile = null;
+ }
+
+ public InputStreamReader createReader(InputStream iStr) {
+ InputStreamReader reader = null;
+
+ if(iStr != null) {
+ String encoding = mFileLogBuffer.getEncoding();
+
+ if(encoding != null) {
+ try {
+ reader = new InputStreamReader(iStr, encoding);
+ } catch(UnsupportedEncodingException excp) {
+ mLogger.warn("createReader(): failed to create input reader.", excp);
+ }
+ }
+
+ if(reader == null) {
+ reader = new InputStreamReader(iStr);
+ }
+ }
+
+ return reader;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+
+ sb.append("DestinationDispatcherThread {");
+ sb.append("ThreadName=").append(this.getName()).append("; ");
+ sb.append("CompletedLogfiles.size()=").append(mCompletedLogfiles.size()).append("; ");
+ sb.append("StopThread=").append(mStopThread).append("; ");
+ sb.append("CurrentLogfile=").append(mCurrentLogfile);
+ sb.append("}");
+
+ return sb.toString();
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/provider/Log4jAuditProvider.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/Log4jAuditProvider.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/Log4jAuditProvider.java
new file mode 100644
index 0000000..0d0809a
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/Log4jAuditProvider.java
@@ -0,0 +1,100 @@
+/**
+ * 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.audit.provider;
+
+import java.util.Properties;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.audit.model.AuditEventBase;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+
+public class Log4jAuditProvider extends BaseAuditProvider {
+
+ private static final Log LOG = LogFactory.getLog(Log4jAuditProvider.class);
+ private static final Log AUDITLOG = LogFactory.getLog("xaaudit." + Log4jAuditProvider.class.getName());
+
+ public static final String AUDIT_LOG4J_IS_ASYNC_PROP = "xasecure.audit.log4j.is.async";
+ public static final String AUDIT_LOG4J_MAX_QUEUE_SIZE_PROP = "xasecure.audit.log4j.async.max.queue.size" ;
+ public static final String AUDIT_LOG4J_MAX_FLUSH_INTERVAL_PROP = "xasecure.audit.log4j.async.max.flush.interval.ms";
+
+ private Gson mGsonBuilder = null;
+
+ public Log4jAuditProvider() {
+ LOG.info("Log4jAuditProvider: creating..");
+ }
+
+ @Override
+ public void init(Properties props) {
+ LOG.info("Log4jAuditProvider.init()");
+
+ super.init(props);
+
+ try {
+ mGsonBuilder = new GsonBuilder().setDateFormat("yyyyMMdd-HH:mm:ss.SSS-Z").create();
+ } catch(Throwable excp) {
+ LOG.warn("Log4jAuditProvider.init(): failed to create GsonBuilder object. events will be formated using toString(), instead of Json", excp);
+ }
+ }
+
+ @Override
+ public void log(AuditEventBase event) {
+ if(! AUDITLOG.isInfoEnabled())
+ return;
+
+ if(event != null) {
+ String eventStr = mGsonBuilder != null ? mGsonBuilder.toJson(event) : event.toString();
+
+ AUDITLOG.info(eventStr);
+ }
+ }
+
+ @Override
+ public void start() {
+ // intentionally left empty
+ }
+
+ @Override
+ public void stop() {
+ // intentionally left empty
+ }
+
+ @Override
+ public void waitToComplete() {
+ // intentionally left empty
+ }
+
+ @Override
+ public boolean isFlushPending() {
+ return false;
+ }
+
+ @Override
+ public long getLastFlushTime() {
+ return 0;
+ }
+
+ @Override
+ public void flush() {
+ // intentionally left empty
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/provider/Log4jTracer.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/Log4jTracer.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/Log4jTracer.java
new file mode 100644
index 0000000..bdb1a47
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/Log4jTracer.java
@@ -0,0 +1,59 @@
+/*
+ * 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.audit.provider;
+
+import org.apache.commons.logging.Log;
+
+public class Log4jTracer implements DebugTracer {
+ private Log mLogger = null;
+
+ public Log4jTracer(Log logger) {
+ mLogger = logger;
+ }
+
+ public void debug(String msg) {
+ mLogger.debug(msg);
+ }
+
+ public void debug(String msg, Throwable excp) {
+ mLogger.debug(msg, excp);
+ }
+
+ public void info(String msg) {
+ mLogger.info(msg);
+ }
+
+ public void info(String msg, Throwable excp) {
+ mLogger.info(msg, excp);
+ }
+
+ public void warn(String msg) {
+ mLogger.warn(msg);
+ }
+
+ public void warn(String msg, Throwable excp) {
+ mLogger.warn(msg, excp);
+ }
+
+ public void error(String msg) {
+ mLogger.error(msg);
+ }
+
+ public void error(String msg, Throwable excp) {
+ mLogger.error(msg, excp);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/provider/LogBuffer.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/LogBuffer.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/LogBuffer.java
new file mode 100644
index 0000000..aebef1b
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/LogBuffer.java
@@ -0,0 +1,32 @@
+/*
+ * 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.audit.provider;
+
+
+public interface LogBuffer<T> {
+ public void start(LogDestination<T> destination);
+
+ public void stop();
+
+ boolean isAvailable();
+
+ public boolean isEmpty();
+
+ public boolean add(T log);
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/provider/LogDestination.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/LogDestination.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/LogDestination.java
new file mode 100644
index 0000000..44e94ad
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/LogDestination.java
@@ -0,0 +1,34 @@
+/*
+ * 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.audit.provider;
+
+
+public interface LogDestination<T> {
+ public void start();
+
+ public void stop();
+
+ boolean isAvailable();
+
+ public boolean send(T log);
+
+ public boolean sendStringified(String log);
+
+ public boolean flush();
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/provider/MiscUtil.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/MiscUtil.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/MiscUtil.java
new file mode 100644
index 0000000..17230b2
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/MiscUtil.java
@@ -0,0 +1,250 @@
+/*
+ * 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.audit.provider;
+
+import java.io.File;
+import java.net.InetAddress;
+import java.rmi.dgc.VMID;
+import java.text.SimpleDateFormat;
+import java.util.UUID;
+
+import org.apache.log4j.helpers.LogLog;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+public class MiscUtil {
+ public static final String TOKEN_START = "%";
+ public static final String TOKEN_END = "%";
+ public static final String TOKEN_HOSTNAME = "hostname";
+ public static final String TOKEN_APP_TYPE = "app-type";
+ public static final String TOKEN_JVM_INSTANCE = "jvm-instance";
+ public static final String TOKEN_TIME = "time:";
+ public static final String TOKEN_PROPERTY = "property:";
+ public static final String TOKEN_ENV = "env:";
+ public static final String ESCAPE_STR = "\\";
+
+ static VMID sJvmID = new VMID();
+
+ public static String LINE_SEPARATOR = System.getProperty("line.separator");
+
+ private static Gson sGsonBuilder = null;
+ private static String sApplicationType = null;
+
+ static {
+ try {
+ sGsonBuilder = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss.SSS").create();
+ } catch(Throwable excp) {
+ LogLog.warn("failed to create GsonBuilder object. stringigy() will return obj.toString(), instead of Json", excp);
+ }
+ }
+
+ public static String replaceTokens(String str, long time) {
+ if(str == null) {
+ return str;
+ }
+
+ if(time <= 0) {
+ time = System.currentTimeMillis();
+ }
+
+ for(int startPos = 0; startPos < str.length(); ) {
+ int tagStartPos = str.indexOf(TOKEN_START, startPos);
+
+ if(tagStartPos == -1) {
+ break;
+ }
+
+ int tagEndPos = str.indexOf(TOKEN_END, tagStartPos + TOKEN_START.length());
+
+ if(tagEndPos == -1) {
+ break;
+ }
+
+ String tag = str.substring(tagStartPos, tagEndPos+TOKEN_END.length());
+ String token = tag.substring(TOKEN_START.length(), tag.lastIndexOf(TOKEN_END));
+ String val = "";
+
+ if(token != null) {
+ if(token.equals(TOKEN_HOSTNAME)) {
+ val = getHostname();
+ } else if(token.equals(TOKEN_APP_TYPE)) {
+ val = getApplicationType();
+ } else if(token.equals(TOKEN_JVM_INSTANCE)) {
+ val = getJvmInstanceId();
+ } else if(token.startsWith(TOKEN_PROPERTY)) {
+ String propertyName = token.substring(TOKEN_PROPERTY.length());
+
+ val = getSystemProperty(propertyName);
+ } else if(token.startsWith(TOKEN_ENV)) {
+ String envName = token.substring(TOKEN_ENV.length());
+
+ val = getEnv(envName);
+ } else if(token.startsWith(TOKEN_TIME)) {
+ String dtFormat = token.substring(TOKEN_TIME.length());
+
+ val = getFormattedTime(time, dtFormat);
+ }
+ }
+
+ if(val == null) {
+ val = "";
+ }
+
+ str = str.substring(0, tagStartPos) + val + str.substring(tagEndPos + TOKEN_END.length());
+ startPos = tagStartPos + val.length();
+ }
+
+ return str;
+ }
+
+ public static String getHostname() {
+ String ret = null;
+
+ try {
+ ret = InetAddress.getLocalHost().getHostName();
+ } catch (Exception excp) {
+ LogLog.warn("getHostname()", excp);
+ }
+
+ return ret;
+ }
+
+ public static void setApplicationType(String applicationType) {
+ sApplicationType = applicationType;
+ }
+
+ public static String getApplicationType() {
+ return sApplicationType;
+ }
+
+ public static String getJvmInstanceId() {
+ String ret = Integer.toString(Math.abs(sJvmID.toString().hashCode()));
+
+ return ret;
+ }
+
+ public static String getSystemProperty(String propertyName) {
+ String ret = null;
+
+ try {
+ ret = propertyName != null ? System.getProperty(propertyName) : null;
+ } catch (Exception excp) {
+ LogLog.warn("getSystemProperty(" + propertyName + ") failed", excp);
+ }
+
+ return ret;
+ }
+
+ public static String getEnv(String envName) {
+ String ret = null;
+
+ try {
+ ret = envName != null ? System.getenv(envName) : null;
+ } catch (Exception excp) {
+ LogLog.warn("getenv(" + envName + ") failed", excp);
+ }
+
+ return ret;
+ }
+
+ public static String getFormattedTime(long time, String format) {
+ String ret = null;
+
+ try {
+ SimpleDateFormat sdf = new SimpleDateFormat(format);
+
+ ret = sdf.format(time);
+ } catch (Exception excp) {
+ LogLog.warn("SimpleDateFormat.format() failed: " + format, excp);
+ }
+
+ return ret;
+ }
+
+ public static void createParents(File file) {
+ if(file != null) {
+ String parentName = file.getParent();
+
+ if (parentName != null) {
+ File parentDir = new File(parentName);
+
+ if(!parentDir.exists()) {
+ if(! parentDir.mkdirs()) {
+ LogLog.warn("createParents(): failed to create " + parentDir.getAbsolutePath());
+ }
+ }
+ }
+ }
+ }
+
+ public static long getNextRolloverTime(long lastRolloverTime, long interval) {
+ long now = System.currentTimeMillis() / 1000 * 1000; // round to second
+
+ if(lastRolloverTime <= 0) {
+ // should this be set to the next multiple-of-the-interval from start of the day?
+ return now + interval;
+ } else if(lastRolloverTime <= now) {
+ long nextRolloverTime = now + interval;
+
+ // keep it at 'interval' boundary
+ long trimInterval = (nextRolloverTime - lastRolloverTime) % interval;
+
+ return nextRolloverTime - trimInterval;
+ } else {
+ return lastRolloverTime;
+ }
+ }
+
+ public static long getRolloverStartTime(long nextRolloverTime, long interval) {
+ return (nextRolloverTime <= interval) ? System.currentTimeMillis() : nextRolloverTime - interval;
+ }
+
+ public static int parseInteger(String str, int defValue) {
+ int ret = defValue;
+
+ if(str != null) {
+ try {
+ ret = Integer.parseInt(str);
+ } catch(Exception excp) {
+ // ignore
+ }
+ }
+
+ return ret;
+ }
+
+ public static String generateUniqueId() {
+ return UUID.randomUUID().toString();
+ }
+
+ public static <T> String stringify(T log) {
+ String ret = null;
+
+ if(log != null) {
+ if(log instanceof String) {
+ ret = (String)log;
+ } else if(MiscUtil.sGsonBuilder != null) {
+ ret = MiscUtil.sGsonBuilder.toJson(log);
+ } else {
+ ret = log.toString();
+ }
+ }
+
+ return ret;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/provider/MultiDestAuditProvider.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/MultiDestAuditProvider.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/MultiDestAuditProvider.java
new file mode 100644
index 0000000..0c2bca6
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/MultiDestAuditProvider.java
@@ -0,0 +1,161 @@
+/**
+ * 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.audit.provider;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.audit.model.AuditEventBase;
+import org.apache.ranger.audit.model.HBaseAuditEvent;
+import org.apache.ranger.audit.model.HdfsAuditEvent;
+import org.apache.ranger.audit.model.HiveAuditEvent;
+import org.apache.ranger.audit.model.KnoxAuditEvent;
+import org.apache.ranger.audit.model.StormAuditEvent;
+
+
+public class MultiDestAuditProvider extends BaseAuditProvider {
+
+ private static final Log LOG = LogFactory.getLog(MultiDestAuditProvider.class);
+
+ protected List<AuditProvider> mProviders = new ArrayList<AuditProvider>();
+
+
+ public MultiDestAuditProvider() {
+ LOG.info("MultiDestAuditProvider: creating..");
+ }
+
+ public MultiDestAuditProvider(AuditProvider provider) {
+ addAuditProvider(provider);
+ }
+
+ @Override
+ public void init(Properties props) {
+ LOG.info("MultiDestAuditProvider.init()");
+
+ super.init(props);
+
+ for(AuditProvider provider : mProviders) {
+ try {
+ provider.init(props);
+ } catch(Throwable excp) {
+ LOG.info("MultiDestAuditProvider.init(): failed" + provider.getClass().getCanonicalName() + ")");
+ }
+ }
+ }
+
+ public void addAuditProvider(AuditProvider provider) {
+ if(provider != null) {
+ LOG.info("MultiDestAuditProvider.addAuditProvider(providerType=" + provider.getClass().getCanonicalName() + ")");
+
+ mProviders.add(provider);
+ }
+ }
+
+ public void addAuditProviders(List<AuditProvider> providers) {
+ if(providers != null) {
+ for(AuditProvider provider : providers) {
+ addAuditProvider(provider);
+ }
+ }
+ }
+
+ @Override
+ public void log(AuditEventBase event) {
+ for(AuditProvider provider : mProviders) {
+ try {
+ provider.log(event);
+ } catch(Throwable excp) {
+ logFailedEvent(event, excp);
+ }
+ }
+ }
+
+ @Override
+ public void start() {
+ for(AuditProvider provider : mProviders) {
+ try {
+ provider.start();
+ } catch(Throwable excp) {
+ LOG.error("AsyncAuditProvider.start(): failed for provider { " + provider.getClass().getName() + " }", excp);
+ }
+ }
+ }
+
+ @Override
+ public void stop() {
+ for(AuditProvider provider : mProviders) {
+ try {
+ provider.stop();
+ } catch(Throwable excp) {
+ LOG.error("AsyncAuditProvider.stop(): failed for provider { " + provider.getClass().getName() + " }", excp);
+ }
+ }
+ }
+
+ @Override
+ public void waitToComplete() {
+ for(AuditProvider provider : mProviders) {
+ try {
+ provider.waitToComplete();
+ } catch(Throwable excp) {
+ LOG.error("AsyncAuditProvider.waitToComplete(): failed for provider { " + provider.getClass().getName() + " }", excp);
+ }
+ }
+ }
+
+ @Override
+ public boolean isFlushPending() {
+ for(AuditProvider provider : mProviders) {
+ if(provider.isFlushPending()) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ @Override
+ public long getLastFlushTime() {
+ long lastFlushTime = 0;
+ for(AuditProvider provider : mProviders) {
+ long flushTime = provider.getLastFlushTime();
+
+ if(flushTime != 0) {
+ if(lastFlushTime == 0 || lastFlushTime > flushTime) {
+ lastFlushTime = flushTime;
+ }
+ }
+ }
+
+ return lastFlushTime;
+ }
+
+ @Override
+ public void flush() {
+ for(AuditProvider provider : mProviders) {
+ try {
+ provider.flush();
+ } catch(Throwable excp) {
+ LOG.error("AsyncAuditProvider.flush(): failed for provider { " + provider.getClass().getName() + " }", excp);
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/provider/hdfs/HdfsAuditProvider.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/hdfs/HdfsAuditProvider.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/hdfs/HdfsAuditProvider.java
new file mode 100644
index 0000000..620951c
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/hdfs/HdfsAuditProvider.java
@@ -0,0 +1,92 @@
+/*
+ * 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.audit.provider.hdfs;
+
+import java.util.Map;
+import java.util.Properties;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.audit.model.AuditEventBase;
+import org.apache.ranger.audit.provider.BaseAuditProvider;
+import org.apache.ranger.audit.provider.BufferedAuditProvider;
+import org.apache.ranger.audit.provider.DebugTracer;
+import org.apache.ranger.audit.provider.LocalFileLogBuffer;
+import org.apache.ranger.audit.provider.Log4jTracer;
+import org.apache.ranger.audit.provider.MiscUtil;
+
+public class HdfsAuditProvider extends BufferedAuditProvider {
+ private static final Log LOG = LogFactory.getLog(HdfsAuditProvider.class);
+
+ public static final String AUDIT_HDFS_IS_ASYNC_PROP = "xasecure.audit.hdfs.is.async";
+ public static final String AUDIT_HDFS_MAX_QUEUE_SIZE_PROP = "xasecure.audit.hdfs.async.max.queue.size" ;
+ public static final String AUDIT_HDFS_MAX_FLUSH_INTERVAL_PROP = "xasecure.audit.hdfs.async.max.flush.interval.ms";
+
+ public HdfsAuditProvider() {
+ }
+
+ public void init(Properties props) {
+ LOG.info("HdfsAuditProvider.init()");
+
+ super.init(props);
+
+ Map<String, String> hdfsProps = BaseAuditProvider.getPropertiesWithPrefix(props, "xasecure.audit.hdfs.config.");
+
+ String encoding = hdfsProps.get("encoding");
+
+ String hdfsDestinationDirectory = hdfsProps.get("destination.directory");
+ String hdfsDestinationFile = hdfsProps.get("destination.file");
+ int hdfsDestinationFlushIntervalSeconds = MiscUtil.parseInteger(hdfsProps.get("destination.flush.interval.seconds"), 15 * 60);
+ int hdfsDestinationRolloverIntervalSeconds = MiscUtil.parseInteger(hdfsProps.get("destination.rollover.interval.seconds"), 24 * 60 * 60);
+ int hdfsDestinationOpenRetryIntervalSeconds = MiscUtil.parseInteger(hdfsProps.get("destination.open.retry.interval.seconds"), 60);
+
+ String localFileBufferDirectory = hdfsProps.get("local.buffer.directory");
+ String localFileBufferFile = hdfsProps.get("local.buffer.file");
+ int localFileBufferFlushIntervalSeconds = MiscUtil.parseInteger(hdfsProps.get("local.buffer.flush.interval.seconds"), 1 * 60);
+ int localFileBufferFileBufferSizeBytes = MiscUtil.parseInteger(hdfsProps.get("local.buffer.file.buffer.size.bytes"), 8 * 1024);
+ int localFileBufferRolloverIntervalSeconds = MiscUtil.parseInteger(hdfsProps.get("local.buffer.rollover.interval.seconds"), 10 * 60);
+ String localFileBufferArchiveDirectory = hdfsProps.get("local.archive.directory");
+ int localFileBufferArchiveFileCount = MiscUtil.parseInteger(hdfsProps.get("local.archive.max.file.count"), 10);
+
+ DebugTracer tracer = new Log4jTracer(LOG);
+
+ HdfsLogDestination<AuditEventBase> mHdfsDestination = new HdfsLogDestination<AuditEventBase>(tracer);
+
+ mHdfsDestination.setDirectory(hdfsDestinationDirectory);
+ mHdfsDestination.setFile(hdfsDestinationFile);
+ mHdfsDestination.setFlushIntervalSeconds(hdfsDestinationFlushIntervalSeconds);
+ mHdfsDestination.setEncoding(encoding);
+ mHdfsDestination.setRolloverIntervalSeconds(hdfsDestinationRolloverIntervalSeconds);
+ mHdfsDestination.setOpenRetryIntervalSeconds(hdfsDestinationOpenRetryIntervalSeconds);
+
+ LocalFileLogBuffer<AuditEventBase> mLocalFileBuffer = new LocalFileLogBuffer<AuditEventBase>(tracer);
+
+ mLocalFileBuffer.setDirectory(localFileBufferDirectory);
+ mLocalFileBuffer.setFile(localFileBufferFile);
+ mLocalFileBuffer.setFlushIntervalSeconds(localFileBufferFlushIntervalSeconds);
+ mLocalFileBuffer.setFileBufferSizeBytes(localFileBufferFileBufferSizeBytes);
+ mLocalFileBuffer.setEncoding(encoding);
+ mLocalFileBuffer.setRolloverIntervalSeconds(localFileBufferRolloverIntervalSeconds);
+ mLocalFileBuffer.setArchiveDirectory(localFileBufferArchiveDirectory);
+ mLocalFileBuffer.setArchiveFileCount(localFileBufferArchiveFileCount);
+
+ setBufferAndDestination(mLocalFileBuffer, mHdfsDestination);
+ }
+}
+
+
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/provider/hdfs/HdfsLogDestination.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/hdfs/HdfsLogDestination.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/hdfs/HdfsLogDestination.java
new file mode 100644
index 0000000..6b5cb4b
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/hdfs/HdfsLogDestination.java
@@ -0,0 +1,451 @@
+/*
+ * 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.audit.provider.hdfs;
+
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FSDataOutputStream;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.ranger.audit.provider.DebugTracer;
+import org.apache.ranger.audit.provider.LogDestination;
+import org.apache.ranger.audit.provider.MiscUtil;
+
+public class HdfsLogDestination<T> implements LogDestination<T> {
+ public final static String EXCP_MSG_FILESYSTEM_CLOSED = "Filesystem closed";
+
+ private String mDirectory = null;
+ private String mFile = null;
+ private int mFlushIntervalSeconds = 1 * 60;
+ private String mEncoding = null;
+ private boolean mIsAppend = false;
+ private int mRolloverIntervalSeconds = 24 * 60 * 60;
+ private int mOpenRetryIntervalSeconds = 60;
+ private DebugTracer mLogger = null;
+
+ private FSDataOutputStream mFsDataOutStream = null;
+ private OutputStreamWriter mWriter = null;
+ private String mHdfsFilename = null;
+ private long mNextRolloverTime = 0;
+ private long mNextFlushTime = 0;
+ private long mLastOpenFailedTime = 0;
+ private boolean mIsStopInProgress = false;
+
+ public HdfsLogDestination(DebugTracer tracer) {
+ mLogger = tracer;
+ }
+
+ public String getDirectory() {
+ return mDirectory;
+ }
+
+ public void setDirectory(String directory) {
+ this.mDirectory = directory;
+ }
+
+ public String getFile() {
+ return mFile;
+ }
+
+ public void setFile(String file) {
+ this.mFile = file;
+ }
+
+ public int getFlushIntervalSeconds() {
+ return mFlushIntervalSeconds;
+ }
+
+ public void setFlushIntervalSeconds(int flushIntervalSeconds) {
+ mFlushIntervalSeconds = flushIntervalSeconds;
+ }
+
+ public String getEncoding() {
+ return mEncoding;
+ }
+
+ public void setEncoding(String encoding) {
+ mEncoding = encoding;
+ }
+
+ public int getRolloverIntervalSeconds() {
+ return mRolloverIntervalSeconds;
+ }
+
+ public void setRolloverIntervalSeconds(int rolloverIntervalSeconds) {
+ this.mRolloverIntervalSeconds = rolloverIntervalSeconds;
+ }
+
+ public int getOpenRetryIntervalSeconds() {
+ return mOpenRetryIntervalSeconds;
+ }
+
+ public void setOpenRetryIntervalSeconds(int minIntervalOpenRetrySeconds) {
+ this.mOpenRetryIntervalSeconds = minIntervalOpenRetrySeconds;
+ }
+
+ @Override
+ public void start() {
+ mLogger.debug("==> HdfsLogDestination.start()");
+
+ openFile();
+
+ mLogger.debug("<== HdfsLogDestination.start()");
+ }
+
+ @Override
+ public void stop() {
+ mLogger.debug("==> HdfsLogDestination.stop()");
+
+ mIsStopInProgress = true;
+
+ closeFile();
+
+ mIsStopInProgress = false;
+
+ mLogger.debug("<== HdfsLogDestination.stop()");
+ }
+
+ @Override
+ public boolean isAvailable() {
+ return mWriter != null;
+ }
+
+ @Override
+ public boolean send(T log) {
+ boolean ret = false;
+
+ if(log != null) {
+ String msg = log.toString();
+
+ ret = sendStringified(msg);
+ }
+
+ return ret;
+ }
+
+ @Override
+ public boolean sendStringified(String log) {
+ boolean ret = false;
+
+ checkFileStatus();
+
+ OutputStreamWriter writer = mWriter;
+
+ if(writer != null) {
+ try {
+ writer.write(log + MiscUtil.LINE_SEPARATOR);
+
+ ret = true;
+ } catch (IOException excp) {
+ mLogger.warn("HdfsLogDestination.sendStringified(): write failed", excp);
+
+ closeFile();
+ }
+ }
+
+ return ret;
+ }
+
+ @Override
+ public boolean flush() {
+ mLogger.debug("==> HdfsLogDestination.flush()");
+
+ boolean ret = false;
+
+ OutputStreamWriter writer = mWriter;
+
+ if(writer != null) {
+ try {
+ writer.flush();
+
+ ret = true;
+ } catch (IOException excp) {
+ logException("HdfsLogDestination: flush() failed", excp);
+ }
+ }
+
+ FSDataOutputStream ostream = mFsDataOutStream;
+
+ if(ostream != null) {
+ try {
+ ostream.hflush();
+
+ ret = true;
+ } catch (IOException excp) {
+ logException("HdfsLogDestination: hflush() failed", excp);
+ }
+ }
+
+ if(ret) {
+ mNextFlushTime = System.currentTimeMillis() + (mFlushIntervalSeconds * 1000L);
+ }
+
+ mLogger.debug("<== HdfsLogDestination.flush()");
+
+ return ret;
+ }
+
+ private void openFile() {
+ mLogger.debug("==> HdfsLogDestination.openFile()");
+
+ closeFile();
+
+ mNextRolloverTime = MiscUtil.getNextRolloverTime(mNextRolloverTime, (mRolloverIntervalSeconds * 1000L));
+
+ long startTime = MiscUtil.getRolloverStartTime(mNextRolloverTime, (mRolloverIntervalSeconds * 1000L));
+
+ mHdfsFilename = MiscUtil.replaceTokens(mDirectory + org.apache.hadoop.fs.Path.SEPARATOR + mFile, startTime);
+
+ FSDataOutputStream ostream = null;
+ FileSystem fileSystem = null;
+ Path pathLogfile = null;
+ Configuration conf = null;
+ boolean bOverwrite = false;
+
+ try {
+ mLogger.debug("HdfsLogDestination.openFile(): opening file " + mHdfsFilename);
+
+ URI uri = URI.create(mHdfsFilename);
+
+ // TODO: mechanism to XA-HDFS plugin to disable auditing of access checks to the current HDFS file
+
+ conf = new Configuration();
+ pathLogfile = new Path(mHdfsFilename);
+ fileSystem = FileSystem.get(uri, conf);
+
+ try {
+ if(fileSystem.exists(pathLogfile)) { // file already exists. either append to the file or write to a new file
+ if(mIsAppend) {
+ mLogger.info("HdfsLogDestination.openFile(): opening file for append " + mHdfsFilename);
+
+ ostream = fileSystem.append(pathLogfile);
+ } else {
+ mHdfsFilename = getNewFilename(mHdfsFilename, fileSystem);
+ pathLogfile = new Path(mHdfsFilename);
+ }
+ }
+
+ // if file does not exist or if mIsAppend==false, create the file
+ if(ostream == null) {
+ mLogger.info("HdfsLogDestination.openFile(): opening file for write " + mHdfsFilename);
+
+ createParents(pathLogfile, fileSystem);
+ ostream = fileSystem.create(pathLogfile, bOverwrite);
+ }
+ } catch(IOException excp) {
+ // append may not be supported by the filesystem; or the file might already be open by another application. Try a different filename
+ String failedFilename = mHdfsFilename;
+
+ mHdfsFilename = getNewFilename(mHdfsFilename, fileSystem);
+ pathLogfile = new Path(mHdfsFilename);
+
+ mLogger.info("HdfsLogDestination.openFile(): failed in opening file " + failedFilename + ". Will try opening " + mHdfsFilename);
+ }
+
+ if(ostream == null){
+ mLogger.info("HdfsLogDestination.openFile(): opening file for write " + mHdfsFilename);
+
+ createParents(pathLogfile, fileSystem);
+ ostream = fileSystem.create(pathLogfile, bOverwrite);
+ }
+ } catch(Throwable ex) {
+ mLogger.warn("HdfsLogDestination.openFile() failed", ex);
+ } finally {
+ // TODO: unset the property set above to exclude auditing of logfile opening
+ // System.setProperty(hdfsCurrentFilenameProperty, null);
+ }
+
+ mWriter = createWriter(ostream);
+
+ if(mWriter != null) {
+ mLogger.debug("HdfsLogDestination.openFile(): opened file " + mHdfsFilename);
+
+ mFsDataOutStream = ostream;
+ mNextFlushTime = System.currentTimeMillis() + (mFlushIntervalSeconds * 1000L);
+ mLastOpenFailedTime = 0;
+ } else {
+ mLogger.warn("HdfsLogDestination.openFile(): failed to open file for write " + mHdfsFilename);
+
+ mHdfsFilename = null;
+ mLastOpenFailedTime = System.currentTimeMillis();
+ }
+
+ mLogger.debug("<== HdfsLogDestination.openFile(" + mHdfsFilename + ")");
+ }
+
+ private void closeFile() {
+ mLogger.debug("==> HdfsLogDestination.closeFile()");
+
+ flush();
+
+ OutputStreamWriter writer = mWriter;
+
+ mWriter = null;
+ mFsDataOutStream = null;
+
+ if(writer != null) {
+ try {
+ mLogger.info("HdfsLogDestination.closeFile(): closing file " + mHdfsFilename);
+
+ writer.close();
+ } catch(IOException excp) {
+ logException("HdfsLogDestination: failed to close file " + mHdfsFilename, excp);
+ }
+ }
+
+ mLogger.debug("<== HdfsLogDestination.closeFile()");
+ }
+
+ private void rollover() {
+ mLogger.debug("==> HdfsLogDestination.rollover()");
+
+ closeFile();
+
+ openFile();
+
+ mLogger.debug("<== HdfsLogDestination.rollover()");
+ }
+
+ private void checkFileStatus() {
+ long now = System.currentTimeMillis();
+
+ if(mWriter == null) {
+ if(now > (mLastOpenFailedTime + (mOpenRetryIntervalSeconds * 1000L))) {
+ openFile();
+ }
+ } else if(now > mNextRolloverTime) {
+ rollover();
+ } else if(now > mNextFlushTime) {
+ flush();
+ }
+ }
+
+ private OutputStreamWriter createWriter(OutputStream os ) {
+ OutputStreamWriter writer = null;
+
+ if(os != null) {
+ if(mEncoding != null) {
+ try {
+ writer = new OutputStreamWriter(os, mEncoding);
+ } catch(UnsupportedEncodingException excp) {
+ mLogger.warn("HdfsLogDestination.createWriter(): failed to create output writer.", excp);
+ }
+ }
+
+ if(writer == null) {
+ writer = new OutputStreamWriter(os);
+ }
+ }
+
+ return writer;
+ }
+
+ private void createParents(Path pathLogfile, FileSystem fileSystem) {
+ try {
+ Path parentPath = pathLogfile != null ? pathLogfile.getParent() : null;
+
+ if(parentPath != null && fileSystem != null && !fileSystem.exists(parentPath)) {
+ fileSystem.mkdirs(parentPath);
+ }
+ } catch (IOException e) {
+ logException("HdfsLogDestination.createParents() failed", e);
+ } catch (Throwable e) {
+ mLogger.warn("HdfsLogDestination.createParents() failed", e);
+ }
+ }
+
+ private String getNewFilename(String fileName, FileSystem fileSystem) {
+ if(fileName == null) {
+ return "";
+ }
+
+ for(int i = 1; ; i++) {
+ String ret = fileName;
+
+ String strToAppend = "-" + Integer.toString(i);
+
+ int extnPos = ret.lastIndexOf(".");
+
+ if(extnPos < 0) {
+ ret += strToAppend;
+ } else {
+ String extn = ret.substring(extnPos);
+
+ ret = ret.substring(0, extnPos) + strToAppend + extn;
+ }
+
+ if(fileSystem != null && fileExists(ret, fileSystem)) {
+ continue;
+ } else {
+ return ret;
+ }
+ }
+ }
+
+ private boolean fileExists(String fileName, FileSystem fileSystem) {
+ boolean ret = false;
+
+ if(fileName != null && fileSystem != null) {
+ Path path = new Path(fileName);
+
+ try {
+ ret = fileSystem.exists(path);
+ } catch(IOException excp) {
+ // ignore
+ }
+ }
+
+ return ret;
+ }
+
+ private void logException(String msg, IOException excp) {
+ // during shutdown, the underlying FileSystem might already be closed; so don't print error details
+
+ if(mIsStopInProgress) {
+ return;
+ }
+
+ String excpMsgToExclude = EXCP_MSG_FILESYSTEM_CLOSED;;
+ String excpMsg = excp != null ? excp.getMessage() : null;
+ boolean excpExcludeLogging = (excpMsg != null && excpMsg.contains(excpMsgToExclude));
+
+ if(! excpExcludeLogging) {
+ mLogger.warn(msg, excp);
+ }
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+
+ sb.append("HdfsLogDestination {");
+ sb.append("Directory=").append(mDirectory).append("; ");
+ sb.append("File=").append(mFile).append("; ");
+ sb.append("RolloverIntervalSeconds=").append(mRolloverIntervalSeconds);
+ sb.append("}");
+
+ return sb.toString();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/test/TestEvents.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/test/TestEvents.java b/agents-audit/src/main/java/org/apache/ranger/audit/test/TestEvents.java
new file mode 100644
index 0000000..34b8e4b
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/test/TestEvents.java
@@ -0,0 +1,152 @@
+/*
+ * 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.audit.test;
+import org.apache.commons.logging.Log;
+import org.apache.log4j.xml.DOMConfigurator;
+import org.apache.ranger.audit.model.AuditEventBase;
+import org.apache.ranger.audit.model.HBaseAuditEvent;
+import org.apache.ranger.audit.model.HdfsAuditEvent;
+import org.apache.ranger.audit.model.HiveAuditEvent;
+import org.apache.ranger.audit.model.KnoxAuditEvent;
+import org.apache.ranger.audit.model.StormAuditEvent;
+import org.apache.ranger.audit.provider.AuditProvider;
+import org.apache.ranger.audit.provider.AuditProviderFactory;
+import org.apache.ranger.audit.provider.AuditProviderFactory.ApplicationType;
+import org.apache.commons.logging.LogFactory;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.util.Date;
+import java.util.Properties;
+
+public class TestEvents {
+
+ private static final Log LOG = LogFactory.getLog(TestEvents.class);
+
+ public static void main(String[] args) {
+ DOMConfigurator.configure("log4j.xml");
+
+ LOG.info("==> TestEvents.main()");
+
+ try {
+ Properties auditProperties = new Properties();
+
+ String AUDIT_PROPERTIES_FILE = "xasecure-audit.properties";
+
+ File propFile = new File(AUDIT_PROPERTIES_FILE);
+
+ if(propFile.exists()) {
+ LOG.info("Loading Audit properties file" + AUDIT_PROPERTIES_FILE);
+
+ auditProperties.load(new FileInputStream(propFile));
+ } else {
+ LOG.info("Audit properties file missing: " + AUDIT_PROPERTIES_FILE);
+
+ auditProperties.setProperty("xasecure.audit.jpa.javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xa_db");
+ auditProperties.setProperty("xasecure.audit.jpa.javax.persistence.jdbc.user", "xaaudit");
+ auditProperties.setProperty("xasecure.audit.jpa.javax.persistence.jdbc.password", "xaaudit");
+ auditProperties.setProperty("xasecure.audit.jpa.javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
+
+ auditProperties.setProperty("xasecure.audit.is.enabled", "true");
+ auditProperties.setProperty("xasecure.audit.log4j.is.enabled", "false");
+ auditProperties.setProperty("xasecure.audit.log4j.is.async", "false");
+ auditProperties.setProperty("xasecure.audit.log4j.async.max.queue.size", "100000");
+ auditProperties.setProperty("xasecure.audit.log4j.async.max.flush.interval.ms", "30000");
+ auditProperties.setProperty("xasecure.audit.db.is.enabled", "true");
+ auditProperties.setProperty("xasecure.audit.db.is.async", "true");
+ auditProperties.setProperty("xasecure.audit.db.async.max.queue.size", "100000");
+ auditProperties.setProperty("xasecure.audit.db.async.max.flush.interval.ms", "30000");
+ auditProperties.setProperty("xasecure.audit.db.batch.size", "100");
+ }
+
+ AuditProviderFactory.getInstance().init(auditProperties, ApplicationType.Hdfs);
+
+ AuditProvider provider = AuditProviderFactory.getAuditProvider();
+
+ LOG.info("provider=" + provider.toString());
+
+ String strEventCount = args.length > 0 ? args[0] : auditProperties.getProperty("xasecure.audit.test.event.count");
+ String strEventPauseTimeInMs = args.length > 1 ? args[1] : auditProperties.getProperty("xasecure.audit.test.event.pause.time.ms");
+ String strSleepTimeBeforeExit = args.length > 2 ? args[2] : auditProperties.getProperty("xasecure.audit.test.sleep.time.before.exit.seconds");
+
+ int eventCount = (strEventCount == null) ? 1024 : Integer.parseInt(strEventCount);
+ int eventPauseTime = (strEventPauseTimeInMs == null) ? 0 : Integer.parseInt(strEventPauseTimeInMs);
+ int sleepTimeBeforeExit = ((strSleepTimeBeforeExit == null) ? 0 : Integer.parseInt(strSleepTimeBeforeExit)) * 1000;
+
+ for(int i = 0; i < eventCount; i++) {
+ AuditEventBase event = getTestEvent(i);
+
+ LOG.info("==> TestEvents.main(" + (i+1) + "): adding " + event.getClass().getName());
+ provider.log(event);
+
+ if(eventPauseTime > 0) {
+ Thread.sleep(eventPauseTime);
+ }
+ }
+
+ provider.waitToComplete();
+
+ // incase of HdfsAuditProvider, logs are saved to local file system which gets sent to HDFS asynchronusly in a separate thread.
+ // So, at this point it is possible that few local log files haven't made to HDFS.
+ if(sleepTimeBeforeExit > 0) {
+ LOG.info("waiting for " + sleepTimeBeforeExit + "ms before exiting..");
+
+ try {
+ Thread.sleep(sleepTimeBeforeExit);
+ } catch(Exception excp) {
+ LOG.info("error while waiting before exiting..");
+ }
+ }
+
+ provider.stop();
+ } catch(Exception excp) {
+ LOG.info(excp.getLocalizedMessage());
+ excp.printStackTrace();
+ }
+
+ LOG.info("<== TestEvents.main()");
+ }
+
+ private static AuditEventBase getTestEvent(int idx) {
+ AuditEventBase event = null;
+
+ switch(idx % 5) {
+ case 0:
+ event = new HdfsAuditEvent();
+ break;
+ case 1:
+ event = new HBaseAuditEvent();
+ break;
+ case 2:
+ event = new HiveAuditEvent();
+ break;
+ case 3:
+ event = new KnoxAuditEvent();
+ break;
+ case 4:
+ event = new StormAuditEvent();
+ break;
+ }
+ event.setEventTime(new Date());
+ event.setResultReason(Integer.toString(idx));
+
+ return event;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/resources/META-INF/persistence.xml
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/resources/META-INF/persistence.xml b/agents-audit/src/main/resources/META-INF/persistence.xml
index 0b87ab9..21b8f06 100644
--- a/agents-audit/src/main/resources/META-INF/persistence.xml
+++ b/agents-audit/src/main/resources/META-INF/persistence.xml
@@ -17,12 +17,12 @@
-->
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="xa_server">
- <class>com.xasecure.audit.entity.XXBaseAuditEvent</class>
- <class>com.xasecure.audit.entity.XXHBaseAuditEvent</class>
- <class>com.xasecure.audit.entity.XXHdfsAuditEvent</class>
- <class>com.xasecure.audit.entity.XXHiveAuditEvent</class>
- <class>com.xasecure.audit.entity.XXKnoxAuditEvent</class>
- <class>com.xasecure.audit.entity.XXStormAuditEvent</class>
+ <class>org.apache.ranger.audit.entity.XXBaseAuditEvent</class>
+ <class>org.apache.ranger.audit.entity.XXHBaseAuditEvent</class>
+ <class>org.apache.ranger.audit.entity.XXHdfsAuditEvent</class>
+ <class>org.apache.ranger.audit.entity.XXHiveAuditEvent</class>
+ <class>org.apache.ranger.audit.entity.XXKnoxAuditEvent</class>
+ <class>org.apache.ranger.audit.entity.XXStormAuditEvent</class>
<properties>
<property name="eclipselink.logging.level" value="SEVERE"/>
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-common/conf/log4j.properties
----------------------------------------------------------------------
diff --git a/agents-common/conf/log4j.properties b/agents-common/conf/log4j.properties
index ca599f2..dd22c6d 100644
--- a/agents-common/conf/log4j.properties
+++ b/agents-common/conf/log4j.properties
@@ -13,7 +13,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-log4j.logger.xaaudit.com.xasecure.audit.provider.Log4jAuditProvider=INFO, hdfsAppender
+log4j.logger.xaaudit.org.apache.ranger.audit.provider.Log4jAuditProvider=INFO, hdfsAppender
log4j.appender.hdfsAppender=org.apache.log4j.HdfsRollingFileAppender
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-common/scripts/enable-agent.sh
----------------------------------------------------------------------
diff --git a/agents-common/scripts/enable-agent.sh b/agents-common/scripts/enable-agent.sh
index 8024b74..f8d90ad 100755
--- a/agents-common/scripts/enable-agent.sh
+++ b/agents-common/scripts/enable-agent.sh
@@ -185,7 +185,7 @@ create_jceks() {
tempFile=/tmp/jce.$$.out
- $JAVA_HOME/bin/java -cp ":${PROJ_INSTALL_LIB_DIR}/*:" com.hortonworks.credentialapi.buildks create "${alias}" -value "${pass}" -provider "jceks://file${jceksFile}" > ${tempFile} 2>&1
+ $JAVA_HOME/bin/java -cp ":${PROJ_INSTALL_LIB_DIR}/*:" org.apache.ranger.credentialapi.buildks create "${alias}" -value "${pass}" -provider "jceks://file${jceksFile}" > ${tempFile} 2>&1
if [ $? -ne 0 ]
then
@@ -359,7 +359,7 @@ then
cp ${fullpathorgfn} ${archivefn}
if [ $? -eq 0 ]
then
- ${JAVA} -cp "${INSTALL_CP}" com.xasecure.utils.install.XmlConfigChanger -i ${archivefn} -o ${newfn} -c ${f} -p ${INSTALL_ARGS}
+ ${JAVA} -cp "${INSTALL_CP}" org.apache.ranger.utils.install.XmlConfigChanger -i ${archivefn} -o ${newfn} -c ${f} -p ${INSTALL_ARGS}
if [ $? -eq 0 ]
then
diff -w ${newfn} ${fullpathorgfn} > /dev/null 2>&1
@@ -544,13 +544,13 @@ then
}
{
if ($1 == "nimbus.authorizer") {
- if ($2 ~ /^[ \t]*"com.xasecure.authorization.storm.authorizer.XaSecureStormAuthorizer"[ \t]*$/) {
+ if ($2 ~ /^[ \t]*"org.apache.ranger.authorization.storm.authorizer.RangerStormAuthorizer"[ \t]*$/) {
configured = 1 ;
printf("%s\n",$0) ;
}
else {
printf("#%s\n",$0);
- printf("nimbus.authorizer: \"com.xasecure.authorization.storm.authorizer.XaSecureStormAuthorizer\"\n") ;
+ printf("nimbus.authorizer: \"org.apache.ranger.authorization.storm.authorizer.RangerStormAuthorizer\"\n") ;
configured = 1 ;
}
}
@@ -560,7 +560,7 @@ then
}
END {
if (configured == 0) {
- printf("nimbus.authorizer: \"com.xasecure.authorization.storm.authorizer.XaSecureStormAuthorizer\"\n") ;
+ printf("nimbus.authorizer: \"org.apache.ranger.authorization.storm.authorizer.RangerStormAuthorizer\"\n") ;
}
}' ${CFG_FILE} > ${CFG_FILE}.new && cat ${CFG_FILE}.new > ${CFG_FILE} && rm -f ${CFG_FILE}.new
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-common/src/main/java/com/xasecure/admin/client/XaAdminClient.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/com/xasecure/admin/client/XaAdminClient.java b/agents-common/src/main/java/com/xasecure/admin/client/XaAdminClient.java
deleted file mode 100644
index 74d096a..0000000
--- a/agents-common/src/main/java/com/xasecure/admin/client/XaAdminClient.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * 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 com.xasecure.admin.client;
-
-
-import com.xasecure.admin.client.datatype.GrantRevokeData;
-
-
-public interface XaAdminClient {
- String getPolicies(String repositoryName, long lastModifiedTime, int policyCount, String agentName);
-
- void grantPrivilege(GrantRevokeData grData) throws Exception;
-
- void revokePrivilege(GrantRevokeData grData) throws Exception;
-}
[16/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/UserServiceBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/UserServiceBase.java b/security-admin/src/main/java/com/xasecure/service/UserServiceBase.java
deleted file mode 100644
index d445b3c..0000000
--- a/security-admin/src/main/java/com/xasecure/service/UserServiceBase.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-import com.xasecure.view.*;
-import com.xasecure.service.*;
-
-public abstract class UserServiceBase<T extends XXPortalUser, V extends VXPortalUser>
- extends AbstractBaseResourceService<T, V> {
- public static final String NAME = "User";
-
- public UserServiceBase() {
-
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected XXPortalUser mapViewToEntityBean(VXPortalUser vObj, XXPortalUser mObj, int OPERATION_CONTEXT) {
- return mObj;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected VXPortalUser mapEntityToViewBean(VXPortalUser vObj, XXPortalUser mObj) {
- return vObj;
- }
-
- /**
- * @param searchCriteria
- * @return
- */
- public VXPortalUserList searchUsers(SearchCriteria searchCriteria) {
- VXPortalUserList returnList = new VXPortalUserList();
- List<VXPortalUser> userList = new ArrayList<VXPortalUser>();
-
- @SuppressWarnings("unchecked")
- List<XXPortalUser> resultList = (List<XXPortalUser>)searchResources(searchCriteria,
- searchFields, sortFields, returnList);
-
- // Iterate over the result list and create the return list
- for (XXPortalUser gjUser : resultList) {
- @SuppressWarnings("unchecked")
- VXPortalUser vUser = populateViewBean((T)gjUser);
- userList.add(vUser);
- }
-
- returnList.setVXPortalUsers(userList);
- return returnList;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XAccessAuditService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XAccessAuditService.java b/security-admin/src/main/java/com/xasecure/service/XAccessAuditService.java
deleted file mode 100644
index 08168d8..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XAccessAuditService.java
+++ /dev/null
@@ -1,265 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import javax.persistence.Query;
-
-import com.xasecure.common.SearchCriteria;
-import com.xasecure.common.SearchField;
-import com.xasecure.common.SearchUtil;
-import com.xasecure.common.SortField;
-import com.xasecure.common.SearchField.DATA_TYPE;
-import com.xasecure.common.SearchField.SEARCH_TYPE;
-import com.xasecure.common.SortField.SORT_ORDER;
-import com.xasecure.common.view.VList;
-import com.xasecure.view.*;
-import com.xasecure.db.XADaoManager;
-import com.xasecure.entity.*;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Service;
-
-@Service
-@Scope("singleton")
-public class XAccessAuditService extends XAccessAuditServiceBase<XXAccessAudit, VXAccessAudit>{
- public static final String NAME = "XAccessAudit";
- public List<SortField> sortFields = new ArrayList<SortField>();
- public List<SearchField> searchFields = new ArrayList<SearchField>();
-
- @Autowired
- protected SearchUtil searchUtil;
-
- @Autowired
- XADaoManager appDaoMgr;
-
- protected String queryStr;
- protected final String distinctCountQueryStr;
- protected final String distinctQueryStr;
- protected String countQueryStr;
-
-
- public XAccessAuditService() {
- countQueryStr = "SELECT COUNT(obj) FROM XXAccessAudit obj ";
- queryStr = "SELECT obj FROM XXAccessAudit obj ";
- distinctCountQueryStr = "SELECT COUNT(distinct obj.id) FROM XXAccessAudit obj ";
- distinctQueryStr = "SELECT distinct obj FROM XXAccessAudit obj ";
-
- searchFields.add(new SearchField("accessType", "obj.accessType",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
- searchFields.add(new SearchField("aclEnforcer", "obj.aclEnforcer",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
- searchFields.add(new SearchField("agentId", "obj.agentId",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
- searchFields.add(new SearchField("repoName", "obj.repoName",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
- searchFields.add(new SearchField("sessionId", "obj.sessionId",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
- searchFields.add(new SearchField("requestUser", "obj.requestUser",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
- searchFields.add(new SearchField("requestData", "obj.requestData",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
- searchFields.add(new SearchField("resourcePath", "obj.resourcePath",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
- searchFields.add(new SearchField("clientIP", "obj.clientIP",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
-
- searchFields.add(new SearchField("auditType", "obj.auditType",
- SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
- searchFields.add(new SearchField("accessResult", "obj.accessResult",
- SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
- searchFields.add(new SearchField("assetId", "obj.assetId",
- SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
- searchFields.add(new SearchField("policyId", "obj.policyId",
- SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
- searchFields.add(new SearchField("repoType", "obj.repoType",
- SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
-
- searchFields.add(new SearchField("startDate", "obj.eventTime",
- DATA_TYPE.DATE, SEARCH_TYPE.GREATER_EQUAL_THAN));
- searchFields.add(new SearchField("endDate", "obj.eventTime",
- DATA_TYPE.DATE, SEARCH_TYPE.LESS_EQUAL_THAN));
- sortFields.add(new SortField("eventTime", "obj.eventTime", true, SORT_ORDER.DESC));
-}
-
- protected XXAccessAudit mapViewToEntityBean(VXAccessAudit vObj, XXAccessAudit mObj, int OPERATION_CONTEXT) {
- mObj.setId(vObj.getId());
- mObj.setAuditType( vObj.getAuditType());
- mObj.setAccessResult( vObj.getAccessResult());
- mObj.setAccessType( vObj.getAccessType());
- mObj.setAclEnforcer( vObj.getAclEnforcer());
- mObj.setAgentId( vObj.getAgentId());
- mObj.setPolicyId( vObj.getPolicyId());
- mObj.setRepoName( vObj.getRepoName());
- mObj.setRepoType( vObj.getRepoType());
- mObj.setResultReason( vObj.getResultReason());
- mObj.setSessionId( vObj.getSessionId());
- mObj.setEventTime( vObj.getEventTime());
- mObj.setRequestUser( vObj.getRequestUser());
- mObj.setRequestData( vObj.getRequestData());
- mObj.setResourcePath( vObj.getResourcePath());
- mObj.setResourceType(vObj.getResourceType());
- mObj.setClientIP(vObj.getClientIP());
- mObj.setClientType(vObj.getClientType());
- return mObj;
- }
-
- protected VXAccessAudit mapEntityToViewBean(VXAccessAudit vObj, XXAccessAudit mObj) {
- vObj.setAuditType( mObj.getAuditType());
- vObj.setAccessResult( mObj.getAccessResult());
- vObj.setAccessType( mObj.getAccessType());
- vObj.setAclEnforcer( mObj.getAclEnforcer());
- vObj.setAgentId( mObj.getAgentId());
- vObj.setPolicyId( mObj.getPolicyId());
- vObj.setRepoName( mObj.getRepoName());
- vObj.setRepoType( mObj.getRepoType());
- vObj.setResultReason( mObj.getResultReason());
- vObj.setSessionId( mObj.getSessionId());
- vObj.setEventTime( mObj.getEventTime());
- vObj.setRequestUser( mObj.getRequestUser());
- vObj.setRequestData( mObj.getRequestData());
- vObj.setResourcePath( mObj.getResourcePath());
- vObj.setResourceType( mObj.getResourceType());
- vObj.setClientIP( mObj.getClientIP());
- vObj.setClientType( mObj.getClientType());
- return vObj;
- }
-
- /**
- * @param searchCriteria
- * @return
- */
- public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) {
- VXAccessAuditList returnList = new VXAccessAuditList();
- List<VXAccessAudit> xAccessAuditList = new ArrayList<VXAccessAudit>();
-
- List<XXAccessAudit> resultList = (List<XXAccessAudit>)searchResources(searchCriteria,
- searchFields, sortFields, returnList);
-
- // Iterate over the result list and create the return list
- for (XXAccessAudit gjXAccessAudit : resultList) {
- VXAccessAudit vXAccessAudit = populateViewBean(gjXAccessAudit);
- xAccessAuditList.add(vXAccessAudit);
- }
-
- returnList.setVXAccessAudits(xAccessAuditList);
- return returnList;
- }
-
- public VXAccessAudit populateViewBean(XXAccessAudit gjXAccessAudit) {
- VXAccessAudit vXAccessAudit = new VXAccessAudit();
- return mapEntityToViewBean(vXAccessAudit, gjXAccessAudit);
- }
- /*
- protected List<XXAccessAudit> searchResources(SearchCriteria searchCriteria,
- List<SearchField> searchFieldList, List<SortField> sortFieldList,
- VList vList) {
-
- // Get total count of the rows which meet the search criteria
- long count = -1;
- if (searchCriteria.isGetCount()) {
- count = getCountForSearchQuery(searchCriteria, searchFieldList);
- if (count == 0) {
- return Collections.emptyList();
- }
- }
- // construct the sort clause
- String sortClause = searchUtil.constructSortClause(searchCriteria,
- sortFieldList);
-
- String q=queryStr;
- if(searchCriteria.isDistinct()){
- q=distinctQueryStr;
- }
- // construct the query object for retrieving the data
- Query query = createQuery(q, sortClause, searchCriteria,
- searchFieldList, false);
-
- List<XXAccessAudit> resultList = appDaoMgr.getXXAccessAudit().executeQueryInSecurityContext(
- XXAccessAudit.class, query);
-
- if (vList != null) {
- // Set the meta values for the query result
- vList.setPageSize(query.getMaxResults());
- vList.setSortBy(searchCriteria.getSortBy());
- vList.setSortType(searchCriteria.getSortType());
- vList.setStartIndex(query.getFirstResult());
- vList.setTotalCount(count);
- vList.setResultSize(resultList.size());
- }
- return resultList;
- }
-
- public VXLong getSearchCount(SearchCriteria searchCriteria,
- List<SearchField> searchFieldList) {
- long count = getCountForSearchQuery(searchCriteria, searchFieldList);
-
- VXLong vXLong = new VXLong();
- vXLong.setValue(count);
- return vXLong;
- }
-
- protected long getCountForSearchQuery(SearchCriteria searchCriteria,
- List<SearchField> searchFieldList) {
-
- String q = countQueryStr;
- // Get total count of the rows which meet the search criteria
- if( searchCriteria.isDistinct()) {
- q = distinctCountQueryStr;
- }
-
- // Get total count of the rows which meet the search criteria
- Query query = createQuery(q, null, searchCriteria,
- searchFieldList, true);
-
- // Make the database call to get the total count
- Long count = appDaoMgr.getXXAccessAudit().executeCountQueryInSecurityContext(XXAccessAudit.class,
- query);
- if (count == null) {
- // If no data that meets the criteria, return 0
- return 0;
- }
- return count.longValue();
- }
-
-// protected Query createQuery(String searchString, String sortString,
-// SearchCriteria searchCriteria, List<SearchField> searchFieldList,
-// boolean isCountQuery) {
-// Query query = searchUtil.createSearchQuery(appDaoMgr.getXXAccessAudit().getEntityManager(), searchString, sortString,
-// searchCriteria, searchFieldList, isCountQuery);
-// return query;
-// }
-*/
- @Override
- protected void validateForCreate(VXAccessAudit viewBaseBean) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void validateForUpdate(VXAccessAudit viewBaseBean, XXAccessAudit t) {
- // TODO Auto-generated method stub
-
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XAccessAuditServiceBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XAccessAuditServiceBase.java b/security-admin/src/main/java/com/xasecure/service/XAccessAuditServiceBase.java
deleted file mode 100644
index 168ecb9..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XAccessAuditServiceBase.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-/**
- *
- */
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-import com.xasecure.view.*;
-import com.xasecure.service.*;
-
-public abstract class XAccessAuditServiceBase<T extends XXAccessAudit, V extends VXAccessAudit>
- extends AbstractBaseResourceService<T, V> {
- public static final String NAME = "XAccessAudit";
-
- public XAccessAuditServiceBase() {
-
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected XXAccessAudit mapViewToEntityBean(VXAccessAudit vObj, XXAccessAudit mObj, int OPERATION_CONTEXT) {
- mObj.setAuditType( vObj.getAuditType());
- mObj.setAccessResult( vObj.getAccessResult());
- mObj.setAccessType( vObj.getAccessType());
- mObj.setAclEnforcer( vObj.getAclEnforcer());
- mObj.setAgentId( vObj.getAgentId());
- mObj.setClientIP( vObj.getClientIP());
- mObj.setClientType( vObj.getClientType());
- mObj.setPolicyId( vObj.getPolicyId());
- mObj.setRepoName( vObj.getRepoName());
- mObj.setRepoType( vObj.getRepoType());
- mObj.setResultReason( vObj.getResultReason());
- mObj.setSessionId( vObj.getSessionId());
- mObj.setEventTime( vObj.getEventTime());
- mObj.setRequestUser( vObj.getRequestUser());
- mObj.setAction( vObj.getAction());
- mObj.setRequestData( vObj.getRequestData());
- mObj.setResourcePath( vObj.getResourcePath());
- mObj.setResourceType( vObj.getResourceType());
- return mObj;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected VXAccessAudit mapEntityToViewBean(VXAccessAudit vObj, XXAccessAudit mObj) {
- vObj.setAuditType( mObj.getAuditType());
- vObj.setAccessResult( mObj.getAccessResult());
- vObj.setAccessType( mObj.getAccessType());
- vObj.setAclEnforcer( mObj.getAclEnforcer());
- vObj.setAgentId( mObj.getAgentId());
- vObj.setClientIP( mObj.getClientIP());
- vObj.setClientType( mObj.getClientType());
- vObj.setPolicyId( mObj.getPolicyId());
- vObj.setRepoName( mObj.getRepoName());
- vObj.setRepoType( mObj.getRepoType());
- vObj.setResultReason( mObj.getResultReason());
- vObj.setSessionId( mObj.getSessionId());
- vObj.setEventTime( mObj.getEventTime());
- vObj.setRequestUser( mObj.getRequestUser());
- vObj.setAction( mObj.getAction());
- vObj.setRequestData( mObj.getRequestData());
- vObj.setResourcePath( mObj.getResourcePath());
- vObj.setResourceType( mObj.getResourceType());
- return vObj;
- }
-
- /**
- * @param searchCriteria
- * @return
- */
- public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) {
- VXAccessAuditList returnList = new VXAccessAuditList();
- List<VXAccessAudit> xAccessAuditList = new ArrayList<VXAccessAudit>();
-
- @SuppressWarnings("unchecked")
- List<XXAccessAudit> resultList = (List<XXAccessAudit>)searchResources(searchCriteria,
- searchFields, sortFields, returnList);
-
- // Iterate over the result list and create the return list
- for (XXAccessAudit gjXAccessAudit : resultList) {
- @SuppressWarnings("unchecked")
- VXAccessAudit vXAccessAudit = populateViewBean((T)gjXAccessAudit);
- xAccessAuditList.add(vXAccessAudit);
- }
-
- returnList.setVXAccessAudits(xAccessAuditList);
- return returnList;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XAgentService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XAgentService.java b/security-admin/src/main/java/com/xasecure/service/XAgentService.java
deleted file mode 100644
index 97e1e9e..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XAgentService.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.Callable;
-import java.util.concurrent.TimeUnit;
-
-import com.xasecure.common.DateUtil;
-import com.xasecure.common.PropertiesUtil;
-import com.xasecure.common.SearchCriteria;
-import com.xasecure.common.StringUtil;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Service;
-
-import com.xasecure.common.AppConstants;
-import com.xasecure.common.TimedEventUtil;
-import com.xasecure.view.VXAuditRecord;
-import com.xasecure.view.VXAuditRecordList;
-
-@Service
-@Scope("singleton")
-public class XAgentService {
-
- @Autowired
- StringUtil stringUtil;
-
- @Autowired
- DateUtil dateUtil;
-
- private static Logger logger = Logger.getLogger(XAgentService.class);
-
- protected String defaultDBDateFormat="yyyy-MM-dd";
- protected boolean auditSupported = false;
-
- public XAgentService() {
- defaultDBDateFormat = PropertiesUtil.getProperty(
- "xa.db.defaultDateformat", defaultDBDateFormat);
- auditSupported = PropertiesUtil.getBooleanProperty("xa.audit.supported",
- false);
- }
-
- private boolean isHDFSLog(String loggerName, int fieldCount) {
- boolean ret = false ;
- if (loggerName != null) {
- ret = loggerName.startsWith("org.") ;
- }
- else {
- ret = (fieldCount == 5) ;
- }
- return ret;
- }
-
- private boolean isHiveLog(String loggerName, int fieldCount) {
- boolean ret = false ;
- if (loggerName != null) {
- ret = loggerName.startsWith("com.xasecure.authorization.hive") || loggerName.startsWith("com.xasecure.pdp.hive.") ;
- }
- else {
- ret = (fieldCount == 11) ;
- }
- return ret;
- }
-
- private boolean isHBaseLog(String loggerName, int fieldCount) {
- boolean ret = false ;
- if (loggerName != null) {
- ret = loggerName.startsWith("com.xasecure.authorization.hbase") ;
- }
- else {
- ret = ((fieldCount != 5) && (fieldCount != 11)) ;
- }
- return ret;
- }
-
-
- // The resource type field in the message has "@" at the start
- // remove and then compare
-
- private int getResourceType(String field) {
- field = field.startsWith("@") ? field.substring(1) : field;
-
- int resourceType = AppConstants.RESOURCE_UNKNOWN;
- if (field.equals("db")) {
- resourceType = AppConstants.RESOURCE_DB;
- } else if (field.equals("table")) {
- resourceType = AppConstants.RESOURCE_TABLE;
- } else if (field.equals("column")) {
- resourceType = AppConstants.RESOURCE_COLUMN;
- }
-
- return resourceType;
- }
-
- private String bulidWhereClause(SearchCriteria searchCriteria) {
- StringBuffer whereClause = new StringBuffer();
- Date startDate = (Date) searchCriteria.getParamValue("startDate");
- Date endDate = (Date) searchCriteria.getParamValue("endDate");
-
- if (startDate == null) {
- startDate = new Date(0);
- }
-
- if (endDate == null) {
- endDate = DateUtil.getUTCDate();
-
- }
- String startDateString = DateUtil.dateToString(startDate, defaultDBDateFormat);
- String endDateString = DateUtil.dateToString(endDate, defaultDBDateFormat);
-
- whereClause.append(" DATE(inserted_date) BETWEEN '" + startDateString
- + "' AND '" + endDateString + "'");
-
- if (whereClause.length() != 0) {
- return "WHERE " + whereClause.toString();
- }
-
- return "";
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XAssetService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XAssetService.java b/security-admin/src/main/java/com/xasecure/service/XAssetService.java
deleted file mode 100644
index 3b3d651..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XAssetService.java
+++ /dev/null
@@ -1,400 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-import java.io.IOException;
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import com.xasecure.common.JSONUtil;
-import com.xasecure.common.MessageEnums;
-import com.xasecure.common.PasswordUtils;
-import com.xasecure.common.PropertiesUtil;
-import com.xasecure.common.SearchField;
-import com.xasecure.common.SearchField.DATA_TYPE;
-import com.xasecure.common.SearchField.SEARCH_TYPE;
-import com.xasecure.common.StringUtil;
-import com.xasecure.entity.*;
-
-import org.codehaus.jackson.map.ObjectMapper;
-import org.codehaus.jackson.type.TypeReference;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Service;
-
-import com.xasecure.common.AppConstants;
-import com.xasecure.common.view.VTrxLogAttr;
-import com.xasecure.db.XADaoManager;
-import com.xasecure.util.XAEnumUtil;
-import com.xasecure.view.*;
-
-@Service
-@Scope("singleton")
-public class XAssetService extends XAssetServiceBase<XXAsset, VXAsset> {
-
- @Autowired
- JSONUtil jsonUtil;
-
- @Autowired
- XADaoManager appDaoMgr;
-
- @Autowired
- StringUtil stringUtil;
-
- static HashMap<String, VTrxLogAttr> trxLogAttrs = new HashMap<String, VTrxLogAttr>();
- static {
- trxLogAttrs.put("name", new VTrxLogAttr("name", "Repository Name", false));
- trxLogAttrs.put("description", new VTrxLogAttr("description", "Repository Description", false));
- trxLogAttrs.put("activeStatus", new VTrxLogAttr("activeStatus", "Repository Status", true));
- trxLogAttrs.put("config", new VTrxLogAttr("config", "Connection Configurations", false));
- }
-
- private String hiddenPasswordString;
-
- @Autowired
- XAEnumUtil xaEnumUtil;
-
- public XAssetService(){
- super();
- hiddenPasswordString = PropertiesUtil.getProperty("xa.password.hidden", "*****");
- searchFields.add(new SearchField("status", "obj.activeStatus",
- SearchField.DATA_TYPE.INT_LIST, SearchField.SEARCH_TYPE.FULL));
- searchFields.add(new SearchField("name", "obj.name", DATA_TYPE.STRING,
- SEARCH_TYPE.PARTIAL));
- searchFields.add(new SearchField("type", "obj.assetType",
- DATA_TYPE.INTEGER, SEARCH_TYPE.FULL));
- }
-
- @Override
- protected void validateForCreate(VXAsset vObj) {
- XXAsset xxAsset = appDaoMgr.getXXAsset()
- .findByAssetName(vObj.getName());
- if (xxAsset != null) {
- String errorMessage = "Repository Name already exists";
- throw restErrorUtil.createRESTException(errorMessage,
- MessageEnums.INVALID_INPUT_DATA, null, null,
- vObj.toString());
- }
- if(vObj.getName()==null || vObj.getName().trim().length()==0){
- String errorMessage = "Repository Name can't be empty";
- throw restErrorUtil.createRESTException(errorMessage,
- MessageEnums.INVALID_INPUT_DATA, null, null,
- vObj.toString());
- }
-
- validateConfig(vObj);
- }
-
- @Override
- protected void validateForUpdate(VXAsset vObj, XXAsset mObj) {
- if (!vObj.getName().equalsIgnoreCase(mObj.getName())) {
- validateForCreate(vObj);
- }else{
- validateConfig(vObj);
- }
- }
-
- @Override
- protected XXAsset mapViewToEntityBean(VXAsset vObj, XXAsset mObj,
- int OPERATION_CONTEXT) {
- String oldConfig = (mObj != null) ? mObj.getConfig() : null;
- super.mapViewToEntityBean(vObj, mObj, OPERATION_CONTEXT);
- String config = vObj.getConfig();
- if (config != null && !config.isEmpty()) {
- Map<String, String> configMap = jsonUtil.jsonToMap(config);
- Entry<String, String> passwordEntry = getPasswordEntry(configMap);
- if (passwordEntry != null) {
- // If "*****" then get password from db and update
- String password = passwordEntry.getValue();
- if (password != null) {
- if (password.equals(hiddenPasswordString)) {
- if (oldConfig != null && !oldConfig.isEmpty()) {
- Map<String, String> oldConfigMap = jsonUtil
- .jsonToMap(oldConfig);
- Entry<String, String> oldPasswordEntry
- = getPasswordEntry(oldConfigMap);
- if (oldPasswordEntry != null) {
- configMap.put(oldPasswordEntry.getKey(),
- oldPasswordEntry.getValue());
- }
- }
- }
- config = jsonUtil.readMapToString(configMap);
- }
- }
- }
- mObj.setConfig(config);
- return mObj;
- }
-
- @Override
- protected VXAsset mapEntityToViewBean(VXAsset vObj, XXAsset mObj) {
- vObj = super.mapEntityToViewBean(vObj, mObj);
- String config = vObj.getConfig();
- if (config != null && !config.isEmpty()) {
- Map<String, String> configMap = jsonUtil.jsonToMap(config);
- Entry<String, String> passwordEntry = getPasswordEntry(configMap);
- if (passwordEntry != null) {
- configMap.put(passwordEntry.getKey(), hiddenPasswordString);
- }
- config = jsonUtil.readMapToString(configMap);
- }
- vObj.setConfig(config);
- return vObj;
- }
-
- private Entry<String, String> getPasswordEntry(Map<String, String> configMap) {
- Entry<String, String> entry = null;
-
- for(Entry<String, String> e : configMap.entrySet()) {
- if(e.getKey().toLowerCase().contains("password")){
- entry = e;
- break;
- }
- }
-
- return entry;
- }
-
- private Entry<String, String> getIsEncryptedEntry(Map<String, String> configMap){
- Entry<String, String> entry = null;
- for(Entry<String, String> e : configMap.entrySet()) {
- if(e.getKey().toLowerCase().contains("isencrypted")){
- entry = e;
- break;
- }
- }
- return entry;
- }
-
- public void validateConfig(VXAsset vObj) {
- HashMap<String, Object> configrationMap = null;
- if (vObj.getAssetType() == AppConstants.ASSET_HDFS) {
- ObjectMapper objectMapper = new ObjectMapper();
- TypeReference<HashMap<String, Object>> typeRef = new TypeReference
- <HashMap<String, Object>>() {};
- try {
- configrationMap = objectMapper.readValue(vObj.getConfig(),
- typeRef);
- } catch (Exception e) {
- logger.error("Error in config json", e);
- }
-
- if (configrationMap != null) {
- String fs_default_name = configrationMap.get("fs.default.name")
- .toString();
-
- if (fs_default_name.isEmpty()) {
- throw restErrorUtil.createRESTException(
- "serverMsg.fsDefaultNameEmptyError",
- MessageEnums.INVALID_INPUT_DATA, null, "fs.default.name",
- vObj.toString());
- }
- /*String expression="^+(hdfs://)\\s*(.*?):[0-9]{1,5}";
-// String expression = "^+(hdfs://)[a-z,A-Z,0-9,.]*+:[0-9]{1,5}";
- Pattern pattern = Pattern.compile(expression,
- Pattern.CASE_INSENSITIVE);
- // String inputStr = "hdfs://192.168.1.16:2";
- Matcher matcher = pattern.matcher(fs_default_name);
- if (!matcher.matches()) {
- throw restErrorUtil.createRESTException(
- "serverMsg.fsDefaultNameValidationError",
- MessageEnums.INVALID_INPUT_DATA, null, "fs.default.name",
- vObj.toString());
- }*/
- }
- }
- }
-
- public List<XXTrxLog> getTransactionLog(VXAsset vResource, String action){
- return getTransactionLog(vResource, null, action);
- }
-
- public List<XXTrxLog> getTransactionLog(VXAsset vObj, XXAsset mObj, String action){
- if(vObj == null && (action == null || !action.equalsIgnoreCase("update"))){
- return null;
- }
-
- List<XXTrxLog> trxLogList = new ArrayList<XXTrxLog>();
- Field[] fields = vObj.getClass().getDeclaredFields();
-
- try {
- Field nameField = vObj.getClass().getDeclaredField("name");
- nameField.setAccessible(true);
- String objectName = ""+nameField.get(vObj);
-
- for(Field field : fields){
- field.setAccessible(true);
- String fieldName = field.getName();
- if(!trxLogAttrs.containsKey(fieldName)){
- continue;
- }
-
- VTrxLogAttr vTrxLogAttr = trxLogAttrs.get(fieldName);
-
- XXTrxLog xTrxLog = new XXTrxLog();
- xTrxLog.setAttributeName(vTrxLogAttr.getAttribUserFriendlyName());
-
- String value = null;
- boolean isEnum = vTrxLogAttr.isEnum();
- if(isEnum){
- String enumName = XXAsset.getEnumName(fieldName);
- int enumValue = field.get(vObj) == null ? 0 : Integer.parseInt(""+field.get(vObj));
- value = xaEnumUtil.getLabel(enumName, enumValue);
- } else {
- value = ""+field.get(vObj);
- }
-
- if(action.equalsIgnoreCase("create")){
- if(stringUtil.isEmpty(value)){
- continue;
- }
- xTrxLog.setNewValue(value);
- } else if(action.equalsIgnoreCase("delete")){
- xTrxLog.setPreviousValue(value);
- } else if(action.equalsIgnoreCase("update")){
- String oldValue = null;
- Field[] mFields = mObj.getClass().getDeclaredFields();
- for(Field mField : mFields){
- mField.setAccessible(true);
- String mFieldName = mField.getName();
- if(fieldName.equalsIgnoreCase(mFieldName)){
- if(isEnum){
- String enumName = XXAsset.getEnumName(mFieldName);
- int enumValue = mField.get(mObj) == null ? 0 : Integer.parseInt(""+mField.get(mObj));
- oldValue = xaEnumUtil.getLabel(enumName, enumValue);
- } else {
- oldValue = mField.get(mObj)+"";
- }
- break;
- }
- }
- if(fieldName.equalsIgnoreCase("config")){
- Map<String, String> vConfig = jsonUtil.jsonToMap(value);
- Map<String, String> xConfig = jsonUtil.jsonToMap(oldValue);
-
- Map<String, String> newConfig = new HashMap<String, String>();
- Map<String, String> oldConfig = new HashMap<String, String>();
-
- for (Entry<String, String> entry: vConfig.entrySet()) {
- String key = entry.getKey();
- if (!xConfig.containsKey(key)) {
- newConfig.put(key, entry.getValue());
- } else if(!entry.getValue().equalsIgnoreCase(xConfig.get(key))){
- if(key.equalsIgnoreCase("password") && entry
- .getValue().equalsIgnoreCase(hiddenPasswordString)){
- continue;
- }
- newConfig.put(key, entry.getValue());
- oldConfig.put(key, xConfig.get(key));
- }
- }
-
- oldValue = jsonUtil.readMapToString(oldConfig);
- value = jsonUtil.readMapToString(newConfig);
- }
- if(value.equalsIgnoreCase(oldValue)){
- continue;
- }
- xTrxLog.setPreviousValue(oldValue);
- xTrxLog.setNewValue(value);
- }
-
- xTrxLog.setAction(action);
- xTrxLog.setObjectClassType(AppConstants.CLASS_TYPE_XA_ASSET);
- xTrxLog.setObjectId(vObj.getId());
- xTrxLog.setObjectName(objectName);
- trxLogList.add(xTrxLog);
-
- }
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (NoSuchFieldException e) {
- e.printStackTrace();
- } catch (SecurityException e) {
- e.printStackTrace();
- }
-
- return trxLogList;
- }
-
- public String getConfigWithEncryptedPassword(String config,boolean isForced){
- try {
- if (config != null && !config.isEmpty()) {
- Map<String, String> configMap = jsonUtil.jsonToMap(config);
- Entry<String, String> passwordEntry = getPasswordEntry(configMap);
- Entry<String, String> isEncryptedEntry = getIsEncryptedEntry(configMap);
- if (passwordEntry != null){
- if(isEncryptedEntry==null || !isEncryptedEntry.getValue().equalsIgnoreCase("true")||isForced==true){
- String password=passwordEntry.getValue();
- String encryptPassword=PasswordUtils.encryptPassword(password);
- String decryptPassword=PasswordUtils.decryptPassword(encryptPassword);
- if(decryptPassword.equalsIgnoreCase(password)){
- configMap.put(passwordEntry.getKey(),
- encryptPassword);
- configMap.put("isencrypted", "true");
- }
- }
- }
- config = jsonUtil.readMapToString(configMap);
- }
- } catch (IOException e) {
- String errorMessage = "Password encryption error";
- throw restErrorUtil.createRESTException(errorMessage,
- MessageEnums.INVALID_INPUT_DATA, null, null,
- e.getMessage());
- }
- return config;
- }
- public String getConfigWithDecryptedPassword(String config){
- try {
- if (config != null && !config.isEmpty()) {
- Map<String, String> configMap = jsonUtil.jsonToMap(config);
- Entry<String, String> passwordEntry = getPasswordEntry(configMap);
- Entry<String, String> isEncryptedEntry = getIsEncryptedEntry(configMap);
- if (isEncryptedEntry!=null && passwordEntry != null){
- if (!stringUtil.isEmpty(isEncryptedEntry.getValue())
- && isEncryptedEntry.getValue().equalsIgnoreCase(
- "true")) {
- String encryptPassword = passwordEntry.getValue();
- String decryptPassword = PasswordUtils
- .decryptPassword(encryptPassword);
- configMap.put(passwordEntry.getKey(), decryptPassword);
- }
- }
- config = jsonUtil.readMapToString(configMap);
- }
- } catch (IOException e) {
- String errorMessage = "Password decryption error";
- throw restErrorUtil.createRESTException(errorMessage,
- MessageEnums.INVALID_INPUT_DATA, null, null,
- e.getMessage());
- }
- return config;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XAssetServiceBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XAssetServiceBase.java b/security-admin/src/main/java/com/xasecure/service/XAssetServiceBase.java
deleted file mode 100644
index 71ec819..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XAssetServiceBase.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-/**
- *
- */
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-import com.xasecure.view.*;
-import com.xasecure.service.*;
-
-public abstract class XAssetServiceBase<T extends XXAsset, V extends VXAsset>
- extends AbstractBaseResourceService<T, V> {
- public static final String NAME = "XAsset";
-
- public XAssetServiceBase() {
-
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected XXAsset mapViewToEntityBean(VXAsset vObj, XXAsset mObj, int OPERATION_CONTEXT) {
- mObj.setName( vObj.getName());
- mObj.setDescription( vObj.getDescription());
- mObj.setActiveStatus( vObj.getActiveStatus());
- mObj.setAssetType( vObj.getAssetType());
- mObj.setConfig( vObj.getConfig());
- mObj.setSupportNative( vObj.isSupportNative());
- return mObj;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected VXAsset mapEntityToViewBean(VXAsset vObj, XXAsset mObj) {
- vObj.setName( mObj.getName());
- vObj.setDescription( mObj.getDescription());
- vObj.setActiveStatus( mObj.getActiveStatus());
- vObj.setAssetType( mObj.getAssetType());
- vObj.setConfig( mObj.getConfig());
- vObj.setSupportNative( mObj.isSupportNative());
- return vObj;
- }
-
- /**
- * @param searchCriteria
- * @return
- */
- public VXAssetList searchXAssets(SearchCriteria searchCriteria) {
- VXAssetList returnList = new VXAssetList();
- List<VXAsset> xAssetList = new ArrayList<VXAsset>();
-
- @SuppressWarnings("unchecked")
- List<XXAsset> resultList = (List<XXAsset>)searchResources(searchCriteria,
- searchFields, sortFields, returnList);
-
- // Iterate over the result list and create the return list
- for (XXAsset gjXAsset : resultList) {
- @SuppressWarnings("unchecked")
- VXAsset vXAsset = populateViewBean((T)gjXAsset);
- xAssetList.add(vXAsset);
- }
-
- returnList.setVXAssets(xAssetList);
- return returnList;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XAuditMapService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XAuditMapService.java b/security-admin/src/main/java/com/xasecure/service/XAuditMapService.java
deleted file mode 100644
index 137cf19..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XAuditMapService.java
+++ /dev/null
@@ -1,188 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-import com.xasecure.common.SearchField;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Service;
-
-import com.xasecure.common.AppConstants;
-import com.xasecure.common.view.VTrxLogAttr;
-import com.xasecure.db.XADaoManager;
-import com.xasecure.entity.*;
-import com.xasecure.util.XAEnumUtil;
-import com.xasecure.view.*;
-
-@Service
-@Scope("singleton")
-public class XAuditMapService extends
- XAuditMapServiceBase<XXAuditMap, VXAuditMap> {
-
- @Autowired
- XAEnumUtil xaEnumUtil;
-
- @Autowired
- XADaoManager xADaoManager;
-
- static HashMap<String, VTrxLogAttr> trxLogAttrs = new HashMap<String, VTrxLogAttr>();
- static {
-// trxLogAttrs.put("groupId", new VTrxLogAttr("groupId", "Group Audit", false));
-// trxLogAttrs.put("userId", new VTrxLogAttr("userId", "User Audit", false));
- trxLogAttrs.put("auditType", new VTrxLogAttr("auditType", "Audit Type", true));
- }
-
- public XAuditMapService() {
- searchFields.add(new SearchField("resourceId", "obj.resourceId",
- SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
- }
-
- @Override
- protected void validateForCreate(VXAuditMap vObj) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void validateForUpdate(VXAuditMap vObj, XXAuditMap mObj) {
- // TODO Auto-generated method stub
-
- }
-
- public List<XXTrxLog> getTransactionLog(VXAuditMap vXAuditMap, String action){
- return getTransactionLog(vXAuditMap, null, action);
- }
-
- public List<XXTrxLog> getTransactionLog(VXAuditMap vObj, VXAuditMap mObj, String action){
- if(vObj == null && (action == null || !action.equalsIgnoreCase("update"))){
- return null;
- }
-
- List<XXTrxLog> trxLogList = new ArrayList<XXTrxLog>();
- Field[] fields = vObj.getClass().getDeclaredFields();
-
- try {
- for(Field field : fields){
- field.setAccessible(true);
- String fieldName = field.getName();
- if(!trxLogAttrs.containsKey(fieldName)){
- continue;
- }
-
- VTrxLogAttr vTrxLogAttr = trxLogAttrs.get(fieldName);
-
- XXTrxLog xTrxLog = new XXTrxLog();
- xTrxLog.setAttributeName(vTrxLogAttr.getAttribUserFriendlyName());
-
- String value = null;
- boolean isEnum = vTrxLogAttr.isEnum();
- if(isEnum){
- String enumName = XXAuditMap.getEnumName(fieldName);
- int enumValue = field.get(vObj) == null ? 0 : Integer.parseInt(""+field.get(vObj));
- value = xaEnumUtil.getLabel(enumName, enumValue);
- } else {
- value = ""+field.get(vObj);
- XXUser xUser = xADaoManager.getXXUser().getById(Long.parseLong(value));
- value = xUser.getName();
- }
-
- if(action.equalsIgnoreCase("create")){
- xTrxLog.setNewValue(value);
- } else if(action.equalsIgnoreCase("delete")){
- xTrxLog.setPreviousValue(value);
- } else if(action.equalsIgnoreCase("update")){
- // Not Changed.
- xTrxLog.setNewValue(value);
- xTrxLog.setPreviousValue(value);
- }
-
- xTrxLog.setAction(action);
- xTrxLog.setObjectClassType(AppConstants.CLASS_TYPE_XA_AUDIT_MAP);
- xTrxLog.setObjectId(vObj.getId());
- xTrxLog.setParentObjectClassType(AppConstants.CLASS_TYPE_XA_RESOURCE);
- xTrxLog.setParentObjectId(vObj.getResourceId());
-// xTrxLog.setParentObjectName(vObj.get);
-// xTrxLog.setObjectName(objectName);
- trxLogList.add(xTrxLog);
-
- }
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (SecurityException e) {
- e.printStackTrace();
- }
-
- return trxLogList;
- }
-
- @Override
- protected XXAuditMap mapViewToEntityBean(VXAuditMap vObj, XXAuditMap mObj, int OPERATION_CONTEXT) {
- super.mapViewToEntityBean(vObj, mObj, OPERATION_CONTEXT);
- if(vObj!=null && mObj!=null){
- XXPortalUser xXPortalUser=null;
- if(mObj.getAddedByUserId()==null || mObj.getAddedByUserId()==0){
- if(!stringUtil.isEmpty(vObj.getOwner())){
- xXPortalUser=xADaoManager.getXXPortalUser().findByLoginId(vObj.getOwner());
- if(xXPortalUser!=null){
- mObj.setAddedByUserId(xXPortalUser.getId());
- }
- }
- }
- if(mObj.getUpdatedByUserId()==null || mObj.getUpdatedByUserId()==0){
- if(!stringUtil.isEmpty(vObj.getUpdatedBy())){
- xXPortalUser= xADaoManager.getXXPortalUser().findByLoginId(vObj.getUpdatedBy());
- if(xXPortalUser!=null){
- mObj.setUpdatedByUserId(xXPortalUser.getId());
- }
- }
- }
- }
- return mObj;
- }
-
- @Override
- protected VXAuditMap mapEntityToViewBean(VXAuditMap vObj, XXAuditMap mObj) {
- super.mapEntityToViewBean(vObj, mObj);
- if(mObj!=null && vObj!=null){
- XXPortalUser xXPortalUser=null;
- if(stringUtil.isEmpty(vObj.getOwner())){
- xXPortalUser= xADaoManager.getXXPortalUser().getById(mObj.getAddedByUserId());
- if(xXPortalUser!=null){
- vObj.setOwner(xXPortalUser.getLoginId());
- }
- }
- if(stringUtil.isEmpty(vObj.getUpdatedBy())){
- xXPortalUser= xADaoManager.getXXPortalUser().getById(mObj.getUpdatedByUserId());
- if(xXPortalUser!=null){
- vObj.setUpdatedBy(xXPortalUser.getLoginId());
- }
- }
- }
- return vObj;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XAuditMapServiceBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XAuditMapServiceBase.java b/security-admin/src/main/java/com/xasecure/service/XAuditMapServiceBase.java
deleted file mode 100644
index fca1ca5..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XAuditMapServiceBase.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-/**
- *
- */
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-import com.xasecure.view.*;
-import com.xasecure.service.*;
-
-public abstract class XAuditMapServiceBase<T extends XXAuditMap, V extends VXAuditMap>
- extends AbstractBaseResourceService<T, V> {
- public static final String NAME = "XAuditMap";
-
- public XAuditMapServiceBase() {
-
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected XXAuditMap mapViewToEntityBean(VXAuditMap vObj, XXAuditMap mObj, int OPERATION_CONTEXT) {
- mObj.setResourceId( vObj.getResourceId());
- mObj.setGroupId( vObj.getGroupId());
- mObj.setUserId( vObj.getUserId());
- mObj.setAuditType( vObj.getAuditType());
- return mObj;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected VXAuditMap mapEntityToViewBean(VXAuditMap vObj, XXAuditMap mObj) {
- vObj.setResourceId( mObj.getResourceId());
- vObj.setGroupId( mObj.getGroupId());
- vObj.setUserId( mObj.getUserId());
- vObj.setAuditType( mObj.getAuditType());
- return vObj;
- }
-
- /**
- * @param searchCriteria
- * @return
- */
- public VXAuditMapList searchXAuditMaps(SearchCriteria searchCriteria) {
- VXAuditMapList returnList = new VXAuditMapList();
- List<VXAuditMap> xAuditMapList = new ArrayList<VXAuditMap>();
-
- @SuppressWarnings("unchecked")
- List<XXAuditMap> resultList = (List<XXAuditMap>)searchResources(searchCriteria,
- searchFields, sortFields, returnList);
-
- // Iterate over the result list and create the return list
- for (XXAuditMap gjXAuditMap : resultList) {
- @SuppressWarnings("unchecked")
- VXAuditMap vXAuditMap = populateViewBean((T)gjXAuditMap);
- xAuditMapList.add(vXAuditMap);
- }
-
- returnList.setVXAuditMaps(xAuditMapList);
- return returnList;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XCredentialStoreService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XCredentialStoreService.java b/security-admin/src/main/java/com/xasecure/service/XCredentialStoreService.java
deleted file mode 100644
index da7db11..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XCredentialStoreService.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-import com.xasecure.entity.*;
-import com.xasecure.view.*;
-
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Service;
-
-import com.xasecure.biz.*;
-import com.xasecure.entity.*;
-import com.xasecure.service.*;
-import com.xasecure.view.*;
-
-@Service
-@Scope("singleton")
-public class XCredentialStoreService extends XCredentialStoreServiceBase<XXCredentialStore, VXCredentialStore> {
-
- @Override
- protected void validateForCreate(VXCredentialStore vObj) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void validateForUpdate(VXCredentialStore vObj, XXCredentialStore mObj) {
- // TODO Auto-generated method stub
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XCredentialStoreServiceBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XCredentialStoreServiceBase.java b/security-admin/src/main/java/com/xasecure/service/XCredentialStoreServiceBase.java
deleted file mode 100644
index cb605c0..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XCredentialStoreServiceBase.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-/**
- *
- */
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-import com.xasecure.view.*;
-import com.xasecure.service.*;
-
-public abstract class XCredentialStoreServiceBase<T extends XXCredentialStore, V extends VXCredentialStore>
- extends AbstractBaseResourceService<T, V> {
- public static final String NAME = "XCredentialStore";
-
- public XCredentialStoreServiceBase() {
-
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected XXCredentialStore mapViewToEntityBean(VXCredentialStore vObj, XXCredentialStore mObj, int OPERATION_CONTEXT) {
- mObj.setName( vObj.getName());
- mObj.setDescription( vObj.getDescription());
- return mObj;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected VXCredentialStore mapEntityToViewBean(VXCredentialStore vObj, XXCredentialStore mObj) {
- vObj.setName( mObj.getName());
- vObj.setDescription( mObj.getDescription());
- return vObj;
- }
-
- /**
- * @param searchCriteria
- * @return
- */
- public VXCredentialStoreList searchXCredentialStores(SearchCriteria searchCriteria) {
- VXCredentialStoreList returnList = new VXCredentialStoreList();
- List<VXCredentialStore> xCredentialStoreList = new ArrayList<VXCredentialStore>();
-
- @SuppressWarnings("unchecked")
- List<XXCredentialStore> resultList = (List<XXCredentialStore>)searchResources(searchCriteria,
- searchFields, sortFields, returnList);
-
- // Iterate over the result list and create the return list
- for (XXCredentialStore gjXCredentialStore : resultList) {
- @SuppressWarnings("unchecked")
- VXCredentialStore vXCredentialStore = populateViewBean((T)gjXCredentialStore);
- xCredentialStoreList.add(vXCredentialStore);
- }
-
- returnList.setVXCredentialStores(xCredentialStoreList);
- return returnList;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XGroupGroupService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XGroupGroupService.java b/security-admin/src/main/java/com/xasecure/service/XGroupGroupService.java
deleted file mode 100644
index 420880a..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XGroupGroupService.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-import com.xasecure.entity.*;
-import com.xasecure.view.*;
-
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Service;
-
-import com.xasecure.biz.*;
-import com.xasecure.entity.*;
-import com.xasecure.service.*;
-import com.xasecure.view.*;
-
-@Service
-@Scope("singleton")
-public class XGroupGroupService extends XGroupGroupServiceBase<XXGroupGroup, VXGroupGroup> {
-
- @Override
- protected void validateForCreate(VXGroupGroup vObj) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void validateForUpdate(VXGroupGroup vObj, XXGroupGroup mObj) {
- // TODO Auto-generated method stub
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XGroupGroupServiceBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XGroupGroupServiceBase.java b/security-admin/src/main/java/com/xasecure/service/XGroupGroupServiceBase.java
deleted file mode 100644
index fd8c9ea..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XGroupGroupServiceBase.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-/**
- *
- */
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-import com.xasecure.view.*;
-import com.xasecure.service.*;
-
-public abstract class XGroupGroupServiceBase<T extends XXGroupGroup, V extends VXGroupGroup>
- extends AbstractBaseResourceService<T, V> {
- public static final String NAME = "XGroupGroup";
-
- public XGroupGroupServiceBase() {
-
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected XXGroupGroup mapViewToEntityBean(VXGroupGroup vObj, XXGroupGroup mObj, int OPERATION_CONTEXT) {
- mObj.setName( vObj.getName());
- mObj.setParentGroupId( vObj.getParentGroupId());
- mObj.setGroupId( vObj.getGroupId());
- return mObj;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected VXGroupGroup mapEntityToViewBean(VXGroupGroup vObj, XXGroupGroup mObj) {
- vObj.setName( mObj.getName());
- vObj.setParentGroupId( mObj.getParentGroupId());
- vObj.setGroupId( mObj.getGroupId());
- return vObj;
- }
-
- /**
- * @param searchCriteria
- * @return
- */
- public VXGroupGroupList searchXGroupGroups(SearchCriteria searchCriteria) {
- VXGroupGroupList returnList = new VXGroupGroupList();
- List<VXGroupGroup> xGroupGroupList = new ArrayList<VXGroupGroup>();
-
- @SuppressWarnings("unchecked")
- List<XXGroupGroup> resultList = (List<XXGroupGroup>)searchResources(searchCriteria,
- searchFields, sortFields, returnList);
-
- // Iterate over the result list and create the return list
- for (XXGroupGroup gjXGroupGroup : resultList) {
- @SuppressWarnings("unchecked")
- VXGroupGroup vXGroupGroup = populateViewBean((T)gjXGroupGroup);
- xGroupGroupList.add(vXGroupGroup);
- }
-
- returnList.setVXGroupGroups(xGroupGroupList);
- return returnList;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XGroupService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XGroupService.java b/security-admin/src/main/java/com/xasecure/service/XGroupService.java
deleted file mode 100644
index 73725dc..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XGroupService.java
+++ /dev/null
@@ -1,252 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-import com.xasecure.common.XACommonEnums;
-import com.xasecure.common.MessageEnums;
-import com.xasecure.common.PropertiesUtil;
-import com.xasecure.common.SearchField;
-import com.xasecure.common.SortField;
-import com.xasecure.common.SortField.SORT_ORDER;
-import com.xasecure.common.StringUtil;
-import com.xasecure.entity.*;
-import com.xasecure.view.*;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Service;
-
-import com.xasecure.biz.*;
-import com.xasecure.common.AppConstants;
-import com.xasecure.common.view.VTrxLogAttr;
-import com.xasecure.db.XADaoManager;
-import com.xasecure.entity.*;
-import com.xasecure.service.*;
-import com.xasecure.util.XAEnumUtil;
-import com.xasecure.view.*;
-
-@Service
-@Scope("singleton")
-public class XGroupService extends XGroupServiceBase<XXGroup, VXGroup> {
-
- public static Long createdByUserId = 1L;
-
- @Autowired
- XADaoManager xADaoManager;
-
- @Autowired
- XAEnumUtil xaEnumUtil;
-
- @Autowired
- StringUtil stringUtil;
-
- static HashMap<String, VTrxLogAttr> trxLogAttrs = new HashMap<String, VTrxLogAttr>();
- static {
- trxLogAttrs.put("name", new VTrxLogAttr("name", "Group Name", false));
- trxLogAttrs.put("description", new VTrxLogAttr("description", "Group Description", false));
- }
-
- public XGroupService() {
- searchFields.add(new SearchField("name", "obj.name",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
- searchFields.add(new SearchField("groupSource", "obj.groupSource",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL));
- createdByUserId = new Long(PropertiesUtil.getIntProperty(
- "xa.xuser.createdByUserId", 1));
-
- sortFields.add(new SortField("name", "obj.name",true,SortField.SORT_ORDER.ASC));
- }
-
- @Override
- protected void validateForCreate(VXGroup vObj) {
- XXGroup xxGroup = xADaoManager.getXXGroup().findByGroupName(
- vObj.getName());
- if (xxGroup != null) {
- throw restErrorUtil.createRESTException("XGroup already exists",
- MessageEnums.ERROR_DUPLICATE_OBJECT);
- }
-
- }
-
- @Override
- protected void validateForUpdate(VXGroup vObj, XXGroup mObj) {
- if (!vObj.getName().equalsIgnoreCase(mObj.getName())) {
- validateForCreate(vObj);
- }
- }
-
- public VXGroup getGroupByGroupName(String groupName) {
- XXGroup xxGroup = xADaoManager.getXXGroup().findByGroupName(groupName);
-
- if (xxGroup == null) {
- throw restErrorUtil.createRESTException(
- groupName + " is Not Found", MessageEnums.DATA_NOT_FOUND);
- }
- return super.populateViewBean(xxGroup);
- }
-
- public VXGroup createXGroupWithOutLogin(VXGroup vxGroup) {
- XXGroup xxGroup = xADaoManager.getXXGroup().findByGroupName(
- vxGroup.getName());
- boolean groupExists = true;
-
- if (xxGroup == null) {
- xxGroup = new XXGroup();
- groupExists = false;
- }
-
- xxGroup = mapViewToEntityBean(vxGroup, xxGroup, 0);
- XXPortalUser xXPortalUser = xADaoManager.getXXPortalUser().getById(createdByUserId);
- if (xXPortalUser != null) {
- xxGroup.setAddedByUserId(createdByUserId);
- xxGroup.setUpdatedByUserId(createdByUserId);
- }
- if (groupExists) {
- xxGroup = getDao().update(xxGroup);
- } else {
- xxGroup = getDao().create(xxGroup);
- }
- vxGroup = postCreate(xxGroup);
- return vxGroup;
- }
-
- public VXGroup readResourceWithOutLogin(Long id) {
- XXGroup resource = getDao().getById(id);
- if (resource == null) {
- // Returns code 400 with DATA_NOT_FOUND as the error message
- throw restErrorUtil.createRESTException(getResourceName()
- + " not found", MessageEnums.DATA_NOT_FOUND, id, null,
- "preRead: " + id + " not found.");
- }
-
- VXGroup view = populateViewBean(resource);
- if(view!=null){
- view.setGroupSource(resource.getGroupSource());
- }
- return view;
- }
-
- public List<XXTrxLog> getTransactionLog(VXGroup vResource, String action){
- return getTransactionLog(vResource, null, action);
- }
-
- public List<XXTrxLog> getTransactionLog(VXGroup vObj, XXGroup mObj, String action){
- if(vObj == null && (action == null || !action.equalsIgnoreCase("update"))){
- return null;
- }
-
- List<XXTrxLog> trxLogList = new ArrayList<XXTrxLog>();
- try {
-
- Field nameField = vObj.getClass().getDeclaredField("name");
- nameField.setAccessible(true);
- String objectName = ""+nameField.get(vObj);
- Field[] fields = vObj.getClass().getDeclaredFields();
-
- for(Field field : fields){
- field.setAccessible(true);
- String fieldName = field.getName();
- if(!trxLogAttrs.containsKey(fieldName)){
- continue;
- }
-
- VTrxLogAttr vTrxLogAttr = trxLogAttrs.get(fieldName);
-
- XXTrxLog xTrxLog = new XXTrxLog();
- xTrxLog.setAttributeName(vTrxLogAttr.getAttribUserFriendlyName());
-
- String value = null;
- boolean isEnum = vTrxLogAttr.isEnum();
- if(isEnum){
- String enumName = XXGroup.getEnumName(fieldName);
- int enumValue = field.get(vObj) == null ? 0 : Integer.parseInt(""+field.get(vObj));
- value = xaEnumUtil.getLabel(enumName, enumValue);
- } else {
- value = ""+field.get(vObj);
- }
-
- if(action.equalsIgnoreCase("create")){
- if(stringUtil.isEmpty(value)){
- continue;
- }
- xTrxLog.setNewValue(value);
- } else if(action.equalsIgnoreCase("delete")){
- xTrxLog.setPreviousValue(value);
- } else if(action.equalsIgnoreCase("update")){
- String oldValue = null;
- Field[] mFields = mObj.getClass().getDeclaredFields();
- for(Field mField : mFields){
- mField.setAccessible(true);
- String mFieldName = mField.getName();
- if(fieldName.equalsIgnoreCase(mFieldName)){
- if(isEnum){
- String enumName = XXAsset.getEnumName(mFieldName);
- int enumValue = mField.get(mObj) == null ? 0 : Integer.parseInt(""+mField.get(mObj));
- oldValue = xaEnumUtil.getLabel(enumName, enumValue);
- } else {
- oldValue = mField.get(mObj)+"";
- }
- break;
- }
- }
- if(value.equalsIgnoreCase(oldValue)){
- continue;
- }
- xTrxLog.setPreviousValue(oldValue);
- xTrxLog.setNewValue(value);
- }
-
- xTrxLog.setAction(action);
- xTrxLog.setObjectClassType(AppConstants.CLASS_TYPE_XA_GROUP);
- xTrxLog.setObjectId(vObj.getId());
- xTrxLog.setObjectName(objectName);
- trxLogList.add(xTrxLog);
-
- }
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (NoSuchFieldException e) {
- e.printStackTrace();
- } catch (SecurityException e) {
- e.printStackTrace();
- }
-
- return trxLogList;
- }
-
- @Override
- protected XXGroup mapViewToEntityBean(VXGroup vObj, XXGroup mObj, int OPERATION_CONTEXT) {
- super.mapViewToEntityBean(vObj, mObj, OPERATION_CONTEXT);
- return mObj;
- }
-
- @Override
- protected VXGroup mapEntityToViewBean(VXGroup vObj, XXGroup mObj) {
- super.mapEntityToViewBean(vObj, mObj);
- return vObj;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XGroupServiceBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XGroupServiceBase.java b/security-admin/src/main/java/com/xasecure/service/XGroupServiceBase.java
deleted file mode 100644
index fcd21d6..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XGroupServiceBase.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-/**
- *
- */
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-import com.xasecure.view.*;
-import com.xasecure.service.*;
-
-public abstract class XGroupServiceBase<T extends XXGroup, V extends VXGroup>
- extends AbstractBaseResourceService<T, V> {
- public static final String NAME = "XGroup";
-
- public XGroupServiceBase() {
-
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected XXGroup mapViewToEntityBean(VXGroup vObj, XXGroup mObj, int OPERATION_CONTEXT) {
- mObj.setName( vObj.getName());
- mObj.setDescription( vObj.getDescription());
- mObj.setGroupType( vObj.getGroupType());
- mObj.setCredStoreId( vObj.getCredStoreId());
- return mObj;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected VXGroup mapEntityToViewBean(VXGroup vObj, XXGroup mObj) {
- vObj.setName( mObj.getName());
- vObj.setDescription( mObj.getDescription());
- vObj.setGroupType( mObj.getGroupType());
- vObj.setCredStoreId( mObj.getCredStoreId());
- return vObj;
- }
-
- /**
- * @param searchCriteria
- * @return
- */
- public VXGroupList searchXGroups(SearchCriteria searchCriteria) {
- VXGroupList returnList = new VXGroupList();
- List<VXGroup> xGroupList = new ArrayList<VXGroup>();
-
- @SuppressWarnings("unchecked")
- List<XXGroup> resultList = (List<XXGroup>)searchResources(searchCriteria,
- searchFields, sortFields, returnList);
-
- // Iterate over the result list and create the return list
- for (XXGroup gjXGroup : resultList) {
- @SuppressWarnings("unchecked")
- VXGroup vXGroup = populateViewBean((T)gjXGroup);
- xGroupList.add(vXGroup);
- }
-
- returnList.setVXGroups(xGroupList);
- return returnList;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XGroupUserService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XGroupUserService.java b/security-admin/src/main/java/com/xasecure/service/XGroupUserService.java
deleted file mode 100644
index 31e9f81..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XGroupUserService.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-import com.xasecure.common.XACommonEnums;
-import com.xasecure.common.MessageEnums;
-import com.xasecure.common.PropertiesUtil;
-import com.xasecure.common.SearchField;
-import com.xasecure.entity.XXPortalUser;
-import com.xasecure.entity.XXGroup;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Service;
-
-import com.xasecure.common.AppConstants;
-import com.xasecure.common.view.VTrxLogAttr;
-import com.xasecure.db.XADaoManager;
-import com.xasecure.entity.*;
-import com.xasecure.util.XAEnumUtil;
-import com.xasecure.view.*;
-
-@Service
-@Scope("singleton")
-public class XGroupUserService extends
- XGroupUserServiceBase<XXGroupUser, VXGroupUser> {
-
- public static Long createdByUserId = 1L;
-
- @Autowired
- XADaoManager xADaoManager;
-
- @Autowired
- XAEnumUtil xaEnumUtil;
-
- static HashMap<String, VTrxLogAttr> trxLogAttrs = new HashMap<String, VTrxLogAttr>();
- static {
- trxLogAttrs.put("parentGroupId", new VTrxLogAttr("parentGroupId", "Group Name", false));
- }
-
-
- public XGroupUserService() {
- searchFields.add(new SearchField("xUserId", "obj.userId",
- SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
- searchFields.add(new SearchField("xGroupId", "obj.parentGroupId",
- SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
- createdByUserId = new Long(PropertiesUtil.getIntProperty(
- "xa.xuser.createdByUserId", 1));
-
- }
-
- @Override
- protected void validateForCreate(VXGroupUser vObj) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void validateForUpdate(VXGroupUser vObj, XXGroupUser mObj) {
- // TODO Auto-generated method stub
-
- }
-
- public VXGroupUser createXGroupUserWithOutLogin(VXGroupUser vxGroupUser) {
- XXGroupUser xxGroupUser = new XXGroupUser();
- XXGroup xGroup = daoManager.getXXGroup().findByGroupName(vxGroupUser.getName());
- vxGroupUser.setParentGroupId(xGroup.getId());
- xxGroupUser = mapViewToEntityBean(vxGroupUser, xxGroupUser, 0);
- XXPortalUser xXPortalUser = xADaoManager.getXXPortalUser().getById(createdByUserId);
- if (xXPortalUser != null) {
- xxGroupUser.setAddedByUserId(createdByUserId);
- xxGroupUser.setUpdatedByUserId(createdByUserId);
- }
- xxGroupUser = getDao().create(xxGroupUser);
- vxGroupUser = postCreate(xxGroupUser);
- return vxGroupUser;
- }
-
- public VXGroupUser readResourceWithOutLogin(Long id) {
- XXGroupUser resource = getDao().getById(id);
- if (resource == null) {
- // Returns code 400 with DATA_NOT_FOUND as the error message
- throw restErrorUtil.createRESTException(getResourceName()
- + " not found", MessageEnums.DATA_NOT_FOUND, id, null,
- "preRead: " + id + " not found.");
- }
-
- VXGroupUser view = populateViewBean(resource);
- return view;
- }
-
- public List<XXTrxLog> getTransactionLog(VXGroupUser vXGroupUser, String action){
- return getTransactionLog(vXGroupUser, null, action);
- }
-
- public List<XXTrxLog> getTransactionLog(VXGroupUser vObj, XXGroupUser mObj, String action){
-// if(vObj == null && (action == null || !action.equalsIgnoreCase("update"))){
-// return null;
-// }
-
- Long groupId = vObj.getParentGroupId();
- XXGroup xGroup = xADaoManager.getXXGroup().getById(groupId);
- String groupName = xGroup.getName();
-
- Long userId = vObj.getUserId();
- XXUser xUser = xADaoManager.getXXUser().getById(userId);
- String userName = xUser.getName();
-
- List<XXTrxLog> trxLogList = new ArrayList<XXTrxLog>();
- Field[] fields = vObj.getClass().getDeclaredFields();
-
- try {
- for(Field field : fields){
- field.setAccessible(true);
- String fieldName = field.getName();
- if(!trxLogAttrs.containsKey(fieldName)){
- continue;
- }
-
- VTrxLogAttr vTrxLogAttr = trxLogAttrs.get(fieldName);
-
- XXTrxLog xTrxLog = new XXTrxLog();
- xTrxLog.setAttributeName(vTrxLogAttr.getAttribUserFriendlyName());
-
- String value = null;
- boolean isEnum = vTrxLogAttr.isEnum();
- if(isEnum){
- String enumName = XXAsset.getEnumName(fieldName);
- int enumValue = field.get(vObj) == null ? 0 : Integer.parseInt(""+field.get(vObj));
- value = xaEnumUtil.getLabel(enumName, enumValue);
- } else {
- value = ""+field.get(vObj);
- XXGroup xXGroup = xADaoManager.getXXGroup().getById(Long.parseLong(value));
- value = xXGroup.getName();
- }
-
- if(action.equalsIgnoreCase("create")){
- xTrxLog.setNewValue(value);
- } else if(action.equalsIgnoreCase("delete")){
- xTrxLog.setPreviousValue(value);
- } else if(action.equalsIgnoreCase("update")){
- // No Change.
- xTrxLog.setNewValue(value);
- xTrxLog.setPreviousValue(value);
- }
-
- xTrxLog.setAction(action);
-
- xTrxLog.setObjectClassType(AppConstants.CLASS_TYPE_XA_GROUP_USER);
- xTrxLog.setObjectId(vObj.getId());
- xTrxLog.setObjectName(userName);
-
- xTrxLog.setParentObjectClassType(AppConstants.CLASS_TYPE_XA_GROUP);
- xTrxLog.setParentObjectId(groupId);
- xTrxLog.setParentObjectName(groupName);
-
- trxLogList.add(xTrxLog);
-
- }
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (SecurityException e) {
- e.printStackTrace();
- }
-
- return trxLogList;
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XGroupUserServiceBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XGroupUserServiceBase.java b/security-admin/src/main/java/com/xasecure/service/XGroupUserServiceBase.java
deleted file mode 100644
index 76ffa82..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XGroupUserServiceBase.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-/**
- *
- */
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-import com.xasecure.view.*;
-import com.xasecure.service.*;
-
-public abstract class XGroupUserServiceBase<T extends XXGroupUser, V extends VXGroupUser>
- extends AbstractBaseResourceService<T, V> {
- public static final String NAME = "XGroupUser";
-
- public XGroupUserServiceBase() {
-
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected XXGroupUser mapViewToEntityBean(VXGroupUser vObj, XXGroupUser mObj, int OPERATION_CONTEXT) {
- mObj.setName( vObj.getName());
- mObj.setParentGroupId( vObj.getParentGroupId());
- mObj.setUserId( vObj.getUserId());
- return mObj;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected VXGroupUser mapEntityToViewBean(VXGroupUser vObj, XXGroupUser mObj) {
- vObj.setName( mObj.getName());
- vObj.setParentGroupId( mObj.getParentGroupId());
- vObj.setUserId( mObj.getUserId());
- return vObj;
- }
-
- /**
- * @param searchCriteria
- * @return
- */
- public VXGroupUserList searchXGroupUsers(SearchCriteria searchCriteria) {
- VXGroupUserList returnList = new VXGroupUserList();
- List<VXGroupUser> xGroupUserList = new ArrayList<VXGroupUser>();
-
- @SuppressWarnings("unchecked")
- List<XXGroupUser> resultList = (List<XXGroupUser>)searchResources(searchCriteria,
- searchFields, sortFields, returnList);
-
- // Iterate over the result list and create the return list
- for (XXGroupUser gjXGroupUser : resultList) {
- @SuppressWarnings("unchecked")
- VXGroupUser vXGroupUser = populateViewBean((T)gjXGroupUser);
- xGroupUserList.add(vXGroupUser);
- }
-
- returnList.setVXGroupUsers(xGroupUserList);
- return returnList;
- }
-
-}
[30/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/com/xasecure/hadoop/client/config/HadoopConfigHolder.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/com/xasecure/hadoop/client/config/HadoopConfigHolder.java b/lookup-client/src/main/java/com/xasecure/hadoop/client/config/HadoopConfigHolder.java
deleted file mode 100644
index b1bd62b..0000000
--- a/lookup-client/src/main/java/com/xasecure/hadoop/client/config/HadoopConfigHolder.java
+++ /dev/null
@@ -1,361 +0,0 @@
-/*
- * 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 com.xasecure.hadoop.client.config;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.HashMap;
-import java.util.Properties;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import com.xasecure.hadoop.client.exceptions.HadoopException;
-
-public class HadoopConfigHolder {
- private static final Log LOG = LogFactory.getLog(HadoopConfigHolder.class) ;
- public static final String GLOBAL_LOGIN_PARAM_PROP_FILE = "hadoop-login.properties" ;
- public static final String DEFAULT_DATASOURCE_PARAM_PROP_FILE = "datasource.properties" ;
- public static final String RESOURCEMAP_PROP_FILE = "resourcenamemap.properties" ;
- public static final String DEFAULT_RESOURCE_NAME = "core-site.xml" ;
- public static final String XASECURE_SECTION_NAME = "xalogin.xml" ;
- public static final String XASECURE_LOGIN_USER_NAME_PROP = "username" ;
- public static final String XASECURE_LOGIN_KEYTAB_FILE_PROP = "keytabfile" ;
- public static final String XASECURE_LOGIN_PASSWORD = "password" ;
- public static final String HADOOP_SECURITY_AUTHENTICATION = "hadoop.security.authentication";
- public static final String HADOOP_SECURITY_AUTHENTICATION_METHOD = "kerberos";
- public static final String HADOOP_RPC_PROTECTION = "hadoop.rpc.protection";
-
-
- private static boolean initialized = false ;
- private static HashMap<String,HashMap<String,Properties>> dataSource2ResourceListMap = new HashMap<String,HashMap<String,Properties>>() ;
- private static Properties globalLoginProp = new Properties() ;
- private static HashMap<String,HadoopConfigHolder> dataSource2HadoopConfigHolder = new HashMap<String,HadoopConfigHolder>() ;
- private static Properties resourcemapProperties = null ;
-
-
- private String datasourceName ;
- private String userName ;
- private String keyTabFile ;
- private String password ;
- private boolean isKerberosAuth ;
-
- private HadoopClassLoader classLoader ;
- private HashMap<String,String> connectionProperties;
-
- public static HadoopConfigHolder getInstance(String aDatasourceName) {
- HadoopConfigHolder ret = dataSource2HadoopConfigHolder.get(aDatasourceName) ;
- if (ret == null) {
- synchronized(HadoopConfigHolder.class) {
- HadoopConfigHolder temp = ret ;
- if (temp == null) {
- ret = new HadoopConfigHolder(aDatasourceName) ;
- dataSource2HadoopConfigHolder.put(aDatasourceName, ret) ;
- }
- }
- }
- return ret ;
- }
-
- public static HadoopConfigHolder getInstance(String aDatasourceName, HashMap<String,String> connectionProperties) {
- HadoopConfigHolder ret = dataSource2HadoopConfigHolder.get(aDatasourceName) ;
- if (ret == null) {
- synchronized(HadoopConfigHolder.class) {
- HadoopConfigHolder temp = ret ;
- if (temp == null) {
- ret = new HadoopConfigHolder(aDatasourceName,connectionProperties) ;
- dataSource2HadoopConfigHolder.put(aDatasourceName, ret) ;
- }
- }
- }
- else {
- if (connectionProperties !=null && !connectionProperties.equals(ret.connectionProperties)) {
- ret = new HadoopConfigHolder(aDatasourceName,connectionProperties) ;
- dataSource2HadoopConfigHolder.remove(aDatasourceName) ;
- dataSource2HadoopConfigHolder.put(aDatasourceName, ret) ;
- }
- }
- return ret ;
- }
-
-
-
- private HadoopConfigHolder(String aDatasourceName) {
- datasourceName = aDatasourceName;
- if ( ! initialized ) {
- init() ;
- }
- initLoginInfo();
- initClassLoader() ;
- }
-
- private HadoopConfigHolder(String aDatasourceName, HashMap<String,String> connectionProperties) {
- datasourceName = aDatasourceName;
- this.connectionProperties = connectionProperties ;
- initConnectionProp() ;
- initLoginInfo();
- initClassLoader() ;
- }
-
- private void initConnectionProp() {
- for(String key : connectionProperties.keySet()) {
-
- String resourceName = getResourceName(key) ;
-
- if (resourceName == null) {
- resourceName = XASECURE_SECTION_NAME ;
- }
- String val = connectionProperties.get(key) ;
- addConfiguration(datasourceName, resourceName, key, val );
- }
- }
-
- private String getResourceName(String key) {
-
- if (resourcemapProperties == null) {
- initResourceMap();
- }
-
- if (resourcemapProperties != null) {
- return resourcemapProperties.getProperty(key);
- }
- else {
- return null;
- }
- }
-
- public static void initResourceMap() {
- if (resourcemapProperties == null) {
- resourcemapProperties = new Properties() ;
- InputStream in = HadoopConfigHolder.class.getClassLoader().getResourceAsStream(RESOURCEMAP_PROP_FILE) ;
- if (in != null) {
- try {
- resourcemapProperties.load(in);
- } catch (IOException e) {
- throw new HadoopException("Unable to load resource map properties from [" + RESOURCEMAP_PROP_FILE + "]", e);
- }
- }
- else {
- throw new HadoopException("Unable to locate resource map properties from [" + RESOURCEMAP_PROP_FILE + "] in the class path.");
- }
- }
- }
-
-
-
- private static synchronized void init() {
-
- if (initialized) {
- return ;
- }
-
- try {
- InputStream in = HadoopConfigHolder.class.getClassLoader().getResourceAsStream(DEFAULT_DATASOURCE_PARAM_PROP_FILE) ;
- if (in != null) {
- Properties prop = new Properties() ;
- try {
- prop.load(in) ;
- } catch (IOException e) {
- throw new HadoopException("Unable to get configuration information for Hadoop environments", e);
- }
- finally {
- try {
- in.close();
- } catch (IOException e) {
- // Ignored exception when the stream is closed.
- }
- }
-
- if (prop.size() == 0)
- return ;
-
- for(Object keyobj : prop.keySet()) {
- String key = (String)keyobj;
- String val = prop.getProperty(key) ;
-
- int dotLocatedAt = key.indexOf(".") ;
-
- if (dotLocatedAt == -1) {
- continue ;
- }
-
- String dataSource = key.substring(0,dotLocatedAt) ;
-
- String propKey = key.substring(dotLocatedAt+1) ;
- int resourceFoundAt = propKey.indexOf(".") ;
- if (resourceFoundAt > -1) {
- String resourceName = propKey.substring(0, resourceFoundAt) + ".xml" ;
- propKey = propKey.substring(resourceFoundAt+1) ;
- addConfiguration(dataSource, resourceName, propKey, val) ;
- }
-
- }
- }
-
- in = HadoopConfigHolder.class.getClassLoader().getResourceAsStream(GLOBAL_LOGIN_PARAM_PROP_FILE) ;
- if (in != null) {
- Properties tempLoginProp = new Properties() ;
- try {
- tempLoginProp.load(in) ;
- } catch (IOException e) {
- throw new HadoopException("Unable to get login configuration information for Hadoop environments from file: [" + GLOBAL_LOGIN_PARAM_PROP_FILE + "]", e);
- }
- finally {
- try {
- in.close();
- } catch (IOException e) {
- // Ignored exception when the stream is closed.
- }
- }
- globalLoginProp = tempLoginProp ;
- }
- }
- finally {
- initialized = true ;
- }
- }
-
-
- private void initLoginInfo() {
- Properties prop = this.getXASecureSection() ;
- if (prop != null) {
- userName = prop.getProperty(XASECURE_LOGIN_USER_NAME_PROP) ;
- keyTabFile = prop.getProperty(XASECURE_LOGIN_KEYTAB_FILE_PROP) ;
- password = prop.getProperty(XASECURE_LOGIN_PASSWORD) ;
-
- if ( getHadoopSecurityAuthentication() != null) {
- isKerberosAuth = ( getHadoopSecurityAuthentication().equalsIgnoreCase(HADOOP_SECURITY_AUTHENTICATION_METHOD));
- }
- else {
- isKerberosAuth = (userName != null) && (userName.indexOf("@") > -1) ;
- }
-
- }
- }
-
- private void initClassLoader() {
- classLoader = new HadoopClassLoader(this) ;
- }
-
-
- public Properties getXASecureSection() {
- Properties prop = this.getProperties(XASECURE_SECTION_NAME) ;
- if (prop == null) {
- prop = globalLoginProp ;
- }
- return prop ;
- }
-
-
-
- private static void addConfiguration(String dataSource, String resourceName, String propertyName, String value) {
-
- if (dataSource == null || dataSource.isEmpty()) {
- return ;
- }
-
- if (propertyName == null || propertyName.isEmpty()) {
- return ;
- }
-
- if (resourceName == null) {
- resourceName = DEFAULT_RESOURCE_NAME ;
- }
-
-
- HashMap<String,Properties> resourceName2PropertiesMap = dataSource2ResourceListMap.get(dataSource) ;
-
- if (resourceName2PropertiesMap == null) {
- resourceName2PropertiesMap = new HashMap<String,Properties>() ;
- dataSource2ResourceListMap.put(dataSource, resourceName2PropertiesMap) ;
- }
-
- Properties prop = resourceName2PropertiesMap.get(resourceName) ;
- if (prop == null) {
- prop = new Properties() ;
- resourceName2PropertiesMap.put(resourceName, prop) ;
- }
- if (value == null) {
- prop.remove(propertyName) ;
- }
- else {
- prop.put(propertyName, value) ;
- }
- }
-
-
- public String getDatasourceName() {
- return datasourceName ;
- }
-
- public boolean hasResourceExists(String aResourceName) {
- HashMap<String,Properties> resourceName2PropertiesMap = dataSource2ResourceListMap.get(datasourceName) ;
- return (resourceName2PropertiesMap != null && resourceName2PropertiesMap.containsKey(aResourceName)) ;
- }
-
- public Properties getProperties(String aResourceName) {
- Properties ret = null ;
- HashMap<String,Properties> resourceName2PropertiesMap = dataSource2ResourceListMap.get(datasourceName) ;
- if (resourceName2PropertiesMap != null) {
- ret = resourceName2PropertiesMap.get(aResourceName) ;
- }
- return ret ;
- }
-
- public String getHadoopSecurityAuthentication() {
- Properties repoParam = null ;
- String ret = null;
-
- HashMap<String,Properties> resourceName2PropertiesMap = dataSource2ResourceListMap.get(this.getDatasourceName()) ;
-
- if ( resourceName2PropertiesMap != null) {
- repoParam=resourceName2PropertiesMap.get(DEFAULT_RESOURCE_NAME);
- }
-
- if ( repoParam != null ) {
- ret = (String)repoParam.get(HADOOP_SECURITY_AUTHENTICATION);
- }
- return ret;
- }
-
- public String getUserName() {
- return userName;
- }
-
- public String getKeyTabFile() {
- return keyTabFile;
- }
-
- public String getPassword() {
- return password;
- }
-
- public HadoopClassLoader getClassLoader() {
- return classLoader;
- }
-
- public boolean isKerberosAuthentication() {
- return isKerberosAuth;
- }
-
-
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/com/xasecure/hadoop/client/exceptions/HadoopException.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/com/xasecure/hadoop/client/exceptions/HadoopException.java b/lookup-client/src/main/java/com/xasecure/hadoop/client/exceptions/HadoopException.java
deleted file mode 100644
index 3cb838e..0000000
--- a/lookup-client/src/main/java/com/xasecure/hadoop/client/exceptions/HadoopException.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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 com.xasecure.hadoop.client.exceptions;
-
-import java.util.HashMap;
-
-public class HadoopException extends RuntimeException {
-
- private static final long serialVersionUID = 8872734935128535649L;
-
- public HashMap<String, Object> responseData;
-
- public HadoopException() {
- super();
- // TODO Auto-generated constructor stub
- }
-
- public HadoopException(String message, Throwable cause) {
- super(message, cause);
- // TODO Auto-generated constructor stub
- }
-
- public HadoopException(String message) {
- super(message);
- // TODO Auto-generated constructor stub
- }
-
- public HadoopException(Throwable cause) {
- super(cause);
- // TODO Auto-generated constructor stub
- }
-
- public void generateResponseDataMap(boolean connectivityStatus,
- String message, String description, Long objectId, String fieldName) {
- responseData = new HashMap<String, Object>();
- responseData.put("connectivityStatus", connectivityStatus);
- responseData.put("message", message);
- responseData.put("description", description);
- responseData.put("objectId", objectId);
- responseData.put("fieldName", fieldName);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/com/xasecure/hbase/client/HBaseClient.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/com/xasecure/hbase/client/HBaseClient.java b/lookup-client/src/main/java/com/xasecure/hbase/client/HBaseClient.java
deleted file mode 100644
index c1d18d7..0000000
--- a/lookup-client/src/main/java/com/xasecure/hbase/client/HBaseClient.java
+++ /dev/null
@@ -1,403 +0,0 @@
-/*
- * 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 com.xasecure.hbase.client;
-
-import java.io.IOException;
-import java.security.PrivilegedAction;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map.Entry;
-
-import javax.security.auth.Subject;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.hbase.HBaseConfiguration;
-import org.apache.hadoop.hbase.HColumnDescriptor;
-import org.apache.hadoop.hbase.HTableDescriptor;
-import org.apache.hadoop.hbase.MasterNotRunningException;
-import org.apache.hadoop.hbase.ZooKeeperConnectionException;
-import org.apache.hadoop.hbase.client.HBaseAdmin;
-
-import com.google.protobuf.ServiceException;
-import com.xasecure.hadoop.client.config.BaseClient;
-import com.xasecure.hadoop.client.exceptions.HadoopException;
-
-public class HBaseClient extends BaseClient {
-
- private static final Log LOG = LogFactory.getLog(HBaseClient.class) ;
-
- private Subject subj = null ;
-
- public HBaseClient(String dataSource) {
- super(dataSource) ;
- }
-
- public HBaseClient(String dataSource,HashMap<String,String> connectionProp) {
- super(dataSource, addDefaultHBaseProp(connectionProp)) ;
- }
-
- //TODO: temporary solution - to be added to the UI for HBase
- private static HashMap<String,String> addDefaultHBaseProp(HashMap<String,String> connectionProp) {
- if (connectionProp != null) {
- String param = "zookeeper.znode.parent" ;
- String unsecuredPath = "/hbase-unsecure" ;
- String authParam = "hadoop.security.authorization" ;
-
- String ret = connectionProp.get(param) ;
- LOG.info("HBase connection has [" + param + "] with value [" + ret + "]");
- if (ret == null) {
- ret = connectionProp.get(authParam) ;
- LOG.info("HBase connection has [" + authParam + "] with value [" + ret + "]");
- if (ret != null && ret.trim().equalsIgnoreCase("false")) {
- LOG.info("HBase connection is resetting [" + param + "] with value [" + unsecuredPath + "]");
- connectionProp.put(param, unsecuredPath) ;
- }
- }
- }
- return connectionProp;
- }
-
- public static HashMap<String, Object> testConnection(String dataSource,
- HashMap<String, String> connectionProperties) {
-
- HashMap<String, Object> responseData = new HashMap<String, Object>();
- final String errMsg = " You can still save the repository and start creating "
- + "policies, but you would not be able to use autocomplete for "
- + "resource names. Check xa_portal.log for more info.";
- boolean connectivityStatus = false;
-
- HBaseClient connectionObj = new HBaseClient(dataSource,
- connectionProperties);
- if (connectionObj != null) {
- connectivityStatus = connectionObj.getHBaseStatus();
- }
-
- if (connectivityStatus) {
- String successMsg = "TestConnection Successful";
- generateResponseDataMap(connectivityStatus, successMsg, successMsg,
- null, null, responseData);
- } else {
- String failureMsg = "Unable to retrieve any databases using given parameters.";
- generateResponseDataMap(connectivityStatus, failureMsg, failureMsg
- + errMsg, null, null, responseData);
- }
- return responseData;
- }
-
- public boolean getHBaseStatus() {
- boolean hbaseStatus = false;
- subj = getLoginSubject();
- final String errMsg = " You can still save the repository and start creating "
- + "policies, but you would not be able to use autocomplete for "
- + "resource names. Check xa_portal.log for more info.";
- if (subj != null) {
- ClassLoader prevCl = Thread.currentThread().getContextClassLoader() ;
- try {
- Thread.currentThread().setContextClassLoader(getConfigHolder().getClassLoader());
-
- hbaseStatus = Subject.doAs(subj, new PrivilegedAction<Boolean>() {
- @Override
- public Boolean run() {
- Boolean hbaseStatus1 = false;
- try {
- LOG.info("getHBaseStatus: creating default Hbase configuration");
- Configuration conf = HBaseConfiguration.create() ;
- LOG.info("getHBaseStatus: setting config values from client");
- setClientConfigValues(conf);
- LOG.info("getHBaseStatus: checking HbaseAvailability with the new config");
- HBaseAdmin.checkHBaseAvailable(conf);
- LOG.info("getHBaseStatus: no exception: HbaseAvailability true");
- hbaseStatus1 = true;
- } catch (ZooKeeperConnectionException zce) {
- String msgDesc = "getHBaseStatus: Unable to connect to `ZooKeeper` "
- + "using given config parameters.";
- HadoopException hdpException = new HadoopException(msgDesc, zce);
- hdpException.generateResponseDataMap(false, getMessage(zce),
- msgDesc + errMsg, null, null);
- throw hdpException;
-
- } catch (MasterNotRunningException mnre) {
- String msgDesc = "getHBaseStatus: Looks like `Master` is not running, "
- + "so couldn't check that running HBase is available or not, "
- + "Please try again later.";
- HadoopException hdpException = new HadoopException(
- msgDesc, mnre);
- hdpException.generateResponseDataMap(false,
- getMessage(mnre), msgDesc + errMsg,
- null, null);
- throw hdpException;
-
- } catch (ServiceException se) {
- String msgDesc = "getHBaseStatus: Unable to check availability of "
- + "Hbase environment [" + getConfigHolder().getDatasourceName() + "].";
- HadoopException hdpException = new HadoopException(msgDesc, se);
- hdpException.generateResponseDataMap(false, getMessage(se),
- msgDesc + errMsg, null, null);
- throw hdpException;
-
- } catch(IOException io) {
- String msgDesc = "getHBaseStatus: Unable to check availability of"
- + " Hbase environment [" + getConfigHolder().getDatasourceName() + "].";
- HadoopException hdpException = new HadoopException(msgDesc, io);
- hdpException.generateResponseDataMap(false, getMessage(io),
- msgDesc + errMsg, null, null);
- throw hdpException;
-
- } catch (Throwable e) {
- String msgDesc = "getHBaseStatus: Unable to check availability of"
- + " Hbase environment [" + getConfigHolder().getDatasourceName() + "].";
- LOG.error(msgDesc);
- hbaseStatus1 = false;
- HadoopException hdpException = new HadoopException(msgDesc, e);
- hdpException.generateResponseDataMap(false, getMessage(e),
- msgDesc + errMsg, null, null);
- throw hdpException;
- }
- return hbaseStatus1;
- }
- }) ;
- } catch (SecurityException se) {
- String msgDesc = "getHBaseStatus: Unable to connect to HBase Server instance, "
- + "current thread might not be able set the context ClassLoader.";
- HadoopException hdpException = new HadoopException(msgDesc, se);
- hdpException.generateResponseDataMap(false, getMessage(se),
- msgDesc + errMsg, null, null);
- throw hdpException;
- } finally {
- Thread.currentThread().setContextClassLoader(prevCl);
- }
- } else {
- LOG.error("getHBaseStatus: secure login not done, subject is null");
- }
-
- return hbaseStatus;
- }
-
- private void setClientConfigValues(Configuration conf) {
- if (this.connectionProperties == null) return;
- Iterator<Entry<String, String>> i = this.connectionProperties.entrySet().iterator();
- while (i.hasNext()) {
- Entry<String, String> e = i.next();
- String v = conf.get(e.getKey());
- if (v != null && !v.equalsIgnoreCase(e.getValue())) {
- conf.set(e.getKey(), e.getValue());
- }
- }
- }
-
- public List<String> getTableList(final String tableNameMatching) {
- List<String> ret = null ;
- final String errMsg = " You can still save the repository and start creating "
- + "policies, but you would not be able to use autocomplete for "
- + "resource names. Check xa_portal.log for more info.";
-
- subj = getLoginSubject();
-
- if (subj != null) {
- ClassLoader prevCl = Thread.currentThread().getContextClassLoader() ;
- try {
- Thread.currentThread().setContextClassLoader(getConfigHolder().getClassLoader());
-
- ret = Subject.doAs(subj, new PrivilegedAction<List<String>>() {
-
- @Override
- public List<String> run() {
-
- List<String> tableList = new ArrayList<String>() ;
- HBaseAdmin admin = null ;
- try {
-
- Configuration conf = HBaseConfiguration.create() ;
- admin = new HBaseAdmin(conf) ;
- for (HTableDescriptor htd : admin.listTables(tableNameMatching)) {
- tableList.add(htd.getNameAsString()) ;
- }
- } catch (ZooKeeperConnectionException zce) {
- String msgDesc = "getTableList: Unable to connect to `ZooKeeper` "
- + "using given config parameters.";
- HadoopException hdpException = new HadoopException(msgDesc, zce);
- hdpException.generateResponseDataMap(false, getMessage(zce),
- msgDesc + errMsg, null, null);
- throw hdpException;
-
- } catch (MasterNotRunningException mnre) {
- String msgDesc = "getTableList: Looks like `Master` is not running, "
- + "so couldn't check that running HBase is available or not, "
- + "Please try again later.";
- HadoopException hdpException = new HadoopException(
- msgDesc, mnre);
- hdpException.generateResponseDataMap(false,
- getMessage(mnre), msgDesc + errMsg,
- null, null);
- throw hdpException;
-
- } catch(IOException io) {
- String msgDesc = "Unable to get HBase table List for [repository:"
- + getConfigHolder().getDatasourceName() + ",table-match:"
- + tableNameMatching + "].";
- HadoopException hdpException = new HadoopException(msgDesc, io);
- hdpException.generateResponseDataMap(false, getMessage(io),
- msgDesc + errMsg, null, null);
- throw hdpException;
- } catch (Throwable e) {
- String msgDesc = "Unable to get HBase table List for [repository:"
- + getConfigHolder().getDatasourceName() + ",table-match:"
- + tableNameMatching + "].";
- LOG.error(msgDesc);
- HadoopException hdpException = new HadoopException(msgDesc, e);
- hdpException.generateResponseDataMap(false, getMessage(e),
- msgDesc + errMsg, null, null);
- throw hdpException;
- }
- finally {
- if (admin != null) {
- try {
- admin.close() ;
- } catch (IOException e) {
- LOG.error("Unable to close HBase connection [" + getConfigHolder().getDatasourceName() + "]", e);
- }
- }
- }
- return tableList ;
- }
-
- }) ;
- }
- finally {
- Thread.currentThread().setContextClassLoader(prevCl);
- }
- }
- return ret ;
- }
-
-
- public List<String> getColumnFamilyList(final String tableName, final String columnFamilyMatching) {
- List<String> ret = null ;
- final String errMsg = " You can still save the repository and start creating "
- + "policies, but you would not be able to use autocomplete for "
- + "resource names. Check xa_portal.log for more info.";
-
- subj = getLoginSubject();
- if (subj != null) {
- ClassLoader prevCl = Thread.currentThread().getContextClassLoader() ;
- try {
- Thread.currentThread().setContextClassLoader(getConfigHolder().getClassLoader());
-
- ret = Subject.doAs(subj, new PrivilegedAction<List<String>>() {
-
- @Override
- public List<String> run() {
-
- List<String> colfList = new ArrayList<String>() ;
- HBaseAdmin admin = null ;
- try {
- Configuration conf = HBaseConfiguration.create();
- admin = new HBaseAdmin(conf) ;
- HTableDescriptor htd = admin.getTableDescriptor(tableName.getBytes()) ;
- if (htd != null) {
- for (HColumnDescriptor hcd : htd.getColumnFamilies()) {
- String colf = hcd.getNameAsString() ;
- if (colf.matches(columnFamilyMatching)) {
- if (!colfList.contains(colf)) {
- colfList.add(colf) ;
- }
- }
- }
- }
- } catch (ZooKeeperConnectionException zce) {
- String msgDesc = "getColumnFamilyList: Unable to connect to `ZooKeeper` "
- + "using given config parameters.";
- HadoopException hdpException = new HadoopException(msgDesc, zce);
- hdpException.generateResponseDataMap(false, getMessage(zce),
- msgDesc + errMsg, null, null);
- throw hdpException;
-
- } catch (MasterNotRunningException mnre) {
- String msgDesc = "getColumnFamilyList: Looks like `Master` is not running, "
- + "so couldn't check that running HBase is available or not, "
- + "Please try again later.";
- HadoopException hdpException = new HadoopException(
- msgDesc, mnre);
- hdpException.generateResponseDataMap(false,
- getMessage(mnre), msgDesc + errMsg,
- null, null);
- throw hdpException;
-
- } catch(IOException io) {
- String msgDesc = "getColumnFamilyList: Unable to get HBase ColumnFamilyList for "
- + "[repository:" +getConfigHolder().getDatasourceName() + ",table:" + tableName
- + ", table-match:" + columnFamilyMatching + "], "
- + "current thread might not be able set the context ClassLoader.";
- HadoopException hdpException = new HadoopException(msgDesc, io);
- hdpException.generateResponseDataMap(false, getMessage(io),
- msgDesc + errMsg, null, null);
- throw hdpException;
- } catch (SecurityException se) {
- String msgDesc = "getColumnFamilyList: Unable to get HBase ColumnFamilyList for "
- + "[repository:" +getConfigHolder().getDatasourceName() + ",table:" + tableName
- + ", table-match:" + columnFamilyMatching + "], "
- + "current thread might not be able set the context ClassLoader.";
- HadoopException hdpException = new HadoopException(msgDesc, se);
- hdpException.generateResponseDataMap(false, getMessage(se),
- msgDesc + errMsg, null, null);
- throw hdpException;
-
- } catch (Throwable e) {
- String msgDesc = "getColumnFamilyList: Unable to get HBase ColumnFamilyList for "
- + "[repository:" +getConfigHolder().getDatasourceName() + ",table:" + tableName
- + ", table-match:" + columnFamilyMatching + "], "
- + "current thread might not be able set the context ClassLoader.";
- LOG.error(msgDesc);
- HadoopException hdpException = new HadoopException(msgDesc, e);
- hdpException.generateResponseDataMap(false, getMessage(e),
- msgDesc + errMsg, null, null);
- throw hdpException;
- }
- finally {
- if (admin != null) {
- try {
- admin.close() ;
- } catch (IOException e) {
- LOG.error("Unable to close HBase connection [" + getConfigHolder().getDatasourceName() + "]", e);
- }
- }
- }
- return colfList ;
- }
-
- }) ;
- } catch (SecurityException se) {
- String msgDesc = "getColumnFamilyList: Unable to connect to HBase Server instance, "
- + "current thread might not be able set the context ClassLoader.";
- HadoopException hdpException = new HadoopException(msgDesc, se);
- hdpException.generateResponseDataMap(false, getMessage(se),
- msgDesc + errMsg, null, null);
- throw hdpException;
- } finally {
- Thread.currentThread().setContextClassLoader(prevCl);
- }
- }
- return ret ;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/com/xasecure/hbase/client/HBaseClientTester.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/com/xasecure/hbase/client/HBaseClientTester.java b/lookup-client/src/main/java/com/xasecure/hbase/client/HBaseClientTester.java
deleted file mode 100644
index 84f06b6..0000000
--- a/lookup-client/src/main/java/com/xasecure/hbase/client/HBaseClientTester.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * 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 com.xasecure.hbase.client;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Properties;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-public class HBaseClientTester {
-
- private static final Log LOG = LogFactory.getLog(HBaseClientTester.class) ;
-
- public static void main(String[] args) throws Throwable {
-
- HBaseClient hc = null;
-
- if (args.length <= 2) {
- System.err.println("USAGE: java " + HBaseClientTester.class.getName() + " dataSourceName propertyFile <tableName> <columnFamilyName>");
- System.exit(1);
- }
-
- LOG.info("Starting ...");
-
- Properties conf = new Properties();
-
- conf.load(HBaseClientTester.class.getClassLoader().getResourceAsStream(args[1]));
-
- HashMap<String, String> prop = new HashMap<String, String>();
- for (Object key : conf.keySet()) {
- Object val = conf.get(key);
- prop.put((String) key, (String) val);
- }
-
- hc = new HBaseClient(args[0], prop);
-
- if (args.length == 3) {
- List<String> dbList = hc.getTableList(args[2]);
- if (dbList.size() == 0) {
- System.out.println("No tables found with db filter [" + args[2] + "]");
- } else {
- for (String str : dbList) {
- System.out.println("table: " + str);
- }
- }
- } else if (args.length == 4) {
- List<String> tableList = hc.getColumnFamilyList(args[2], args[3]);
- if (tableList.size() == 0) {
- System.out.println("No column families found under table [" + args[2] + "] with columnfamily filter [" + args[3] + "]");
- } else {
- for (String str : tableList) {
- System.out.println("ColumnFamily: " + str);
- }
- }
- }
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/com/xasecure/hive/client/HiveClient.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/com/xasecure/hive/client/HiveClient.java b/lookup-client/src/main/java/com/xasecure/hive/client/HiveClient.java
deleted file mode 100644
index ce586a5..0000000
--- a/lookup-client/src/main/java/com/xasecure/hive/client/HiveClient.java
+++ /dev/null
@@ -1,511 +0,0 @@
-/*
- * 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 com.xasecure.hive.client;
-
-import java.io.Closeable;
-import java.security.PrivilegedAction;
-import java.sql.Connection;
-import java.sql.Driver;
-import java.sql.DriverManager;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.SQLTimeoutException;
-import java.sql.Statement;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Properties;
-
-import javax.security.auth.Subject;
-
-import org.apache.commons.io.FilenameUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import com.xasecure.hadoop.client.config.BaseClient;
-import com.xasecure.hadoop.client.exceptions.HadoopException;
-
-public class HiveClient extends BaseClient implements Closeable {
-
- private static final Log LOG = LogFactory.getLog(HiveClient.class) ;
-
- Connection con = null ;
- boolean isKerberosAuth=false;
-
-
- public HiveClient(String dataSource) {
- super(dataSource) ;
- initHive() ;
- }
-
- public HiveClient(String dataSource,HashMap<String,String> connectionProp) {
- super(dataSource,connectionProp) ;
- initHive() ;
- }
-
- public void initHive() {
- isKerberosAuth = getConfigHolder().isKerberosAuthentication();
- if (isKerberosAuth) {
- LOG.info("Secured Mode: JDBC Connection done with preAuthenticated Subject");
- Subject.doAs(getLoginSubject(), new PrivilegedAction<Object>() {
- public Object run() {
- initConnection();
- return null;
- }
- }) ;
- }
- else {
- LOG.info("Since Password is NOT provided, Trying to use UnSecure client with username and password");
- final String userName = getConfigHolder().getUserName() ;
- final String password = getConfigHolder().getPassword() ;
- Subject.doAs(getLoginSubject(), new PrivilegedAction<Object>() {
- public Object run() {
- initConnection(userName,password);
- return null;
- }
- }) ;
- }
- }
-
- public List<String> getDatabaseList(String databaseMatching){
- final String dbMatching=databaseMatching;
- List<String> dblist = Subject.doAs(getLoginSubject(), new PrivilegedAction<List<String>>() {
- public List<String> run() {
- return getDBList(dbMatching);
- }
- }) ;
- return dblist;
- }
-
- private List<String> getDBList(String databaseMatching) {
- List<String> ret = new ArrayList<String>() ;
- String errMsg = " You can still save the repository and start creating "
- + "policies, but you would not be able to use autocomplete for "
- + "resource names. Check xa_portal.log for more info.";
- if (con != null) {
- Statement stat = null ;
- ResultSet rs = null ;
- String sql = "show databases" ;
- if (databaseMatching != null && ! databaseMatching.isEmpty()) {
- sql = sql + " like \"" + databaseMatching + "\"" ;
- }
- try {
- stat = con.createStatement() ;
- rs = stat.executeQuery(sql) ;
- while (rs.next()) {
- ret.add(rs.getString(1)) ;
- }
- } catch (SQLTimeoutException sqlt) {
- String msgDesc = "Time Out, Unable to execute SQL [" + sql
- + "].";
- HadoopException hdpException = new HadoopException(msgDesc,
- sqlt);
- hdpException.generateResponseDataMap(false, getMessage(sqlt),
- msgDesc + errMsg, null, null);
- throw hdpException;
- } catch (SQLException sqle) {
- String msgDesc = "Unable to execute SQL [" + sql + "].";
- HadoopException hdpException = new HadoopException(msgDesc,
- sqle);
- hdpException.generateResponseDataMap(false, getMessage(sqle),
- msgDesc + errMsg, null, null);
- throw hdpException;
- } finally {
- close(rs) ;
- close(stat) ;
- }
-
- }
- return ret ;
- }
-
- public List<String> getTableList(String database, String tableNameMatching){
- final String db=database;
- final String tblNameMatching=tableNameMatching;
- List<String> tableList = Subject.doAs(getLoginSubject(), new PrivilegedAction<List<String>>() {
- public List<String> run() {
- return getTblList(db,tblNameMatching);
- }
- }) ;
- return tableList;
- }
-
- public List<String> getTblList(String database, String tableNameMatching) {
- List<String> ret = new ArrayList<String>() ;
- String errMsg = " You can still save the repository and start creating "
- + "policies, but you would not be able to use autocomplete for "
- + "resource names. Check xa_portal.log for more info.";
- if (con != null) {
- Statement stat = null ;
- ResultSet rs = null ;
-
- String sql = null ;
-
- try {
- sql = "use " + database;
-
- try {
- stat = con.createStatement() ;
- stat.execute(sql) ;
- }
- finally {
- close(stat) ;
- }
-
- sql = "show tables " ;
- if (tableNameMatching != null && ! tableNameMatching.isEmpty()) {
- sql = sql + " like \"" + tableNameMatching + "\"" ;
- }
- stat = con.createStatement() ;
- rs = stat.executeQuery(sql) ;
- while (rs.next()) {
- ret.add(rs.getString(1)) ;
- }
- } catch (SQLTimeoutException sqlt) {
- String msgDesc = "Time Out, Unable to execute SQL [" + sql
- + "].";
- HadoopException hdpException = new HadoopException(msgDesc,
- sqlt);
- hdpException.generateResponseDataMap(false, getMessage(sqlt),
- msgDesc + errMsg, null, null);
- throw hdpException;
- } catch (SQLException sqle) {
- String msgDesc = "Unable to execute SQL [" + sql + "].";
- HadoopException hdpException = new HadoopException(msgDesc,
- sqle);
- hdpException.generateResponseDataMap(false, getMessage(sqle),
- msgDesc + errMsg, null, null);
- throw hdpException;
- } finally {
- close(rs) ;
- close(stat) ;
- }
-
- }
- return ret ;
- }
-
- public List<String> getViewList(String database, String viewNameMatching) {
- List<String> ret = null ;
- return ret ;
- }
-
- public List<String> getUDFList(String database, String udfMatching) {
- List<String> ret = null ;
- return ret ;
- }
-
- public List<String> getColumnList(String database, String tableName, String columnNameMatching) {
- final String db=database;
- final String tblName=tableName;
- final String clmNameMatching=columnNameMatching;
- List<String> columnList = Subject.doAs(getLoginSubject(), new PrivilegedAction<List<String>>() {
- public List<String> run() {
- return getClmList(db,tblName,clmNameMatching);
- }
- }) ;
- return columnList;
- }
-
- public List<String> getClmList(String database, String tableName, String columnNameMatching) {
- List<String> ret = new ArrayList<String>() ;
- String errMsg = " You can still save the repository and start creating "
- + "policies, but you would not be able to use autocomplete for "
- + "resource names. Check xa_portal.log for more info.";
- if (con != null) {
-
- String columnNameMatchingRegEx = null ;
-
- if (columnNameMatching != null && ! columnNameMatching.isEmpty()) {
- columnNameMatchingRegEx = columnNameMatching ;
- }
-
- Statement stat = null ;
- ResultSet rs = null ;
-
- String sql = null ;
-
- try {
- sql = "use " + database;
-
- try {
- stat = con.createStatement() ;
- stat.execute(sql) ;
- }
- finally {
- close(stat) ;
- }
-
- sql = "describe " + tableName ;
- stat = con.createStatement() ;
- rs = stat.executeQuery(sql) ;
- while (rs.next()) {
- String columnName = rs.getString(1) ;
- if (columnNameMatchingRegEx == null) {
- ret.add(columnName) ;
- }
- else if (FilenameUtils.wildcardMatch(columnName,columnNameMatchingRegEx)) {
- ret.add(columnName) ;
- }
- }
- } catch (SQLTimeoutException sqlt) {
- String msgDesc = "Time Out, Unable to execute SQL [" + sql
- + "].";
- HadoopException hdpException = new HadoopException(msgDesc,
- sqlt);
- hdpException.generateResponseDataMap(false, getMessage(sqlt),
- msgDesc + errMsg, null, null);
- throw hdpException;
- } catch (SQLException sqle) {
- String msgDesc = "Unable to execute SQL [" + sql + "].";
- HadoopException hdpException = new HadoopException(msgDesc,
- sqle);
- hdpException.generateResponseDataMap(false, getMessage(sqle),
- msgDesc + errMsg, null, null);
- throw hdpException;
- } finally {
- close(rs) ;
- close(stat) ;
- }
-
- }
- return ret ;
- }
-
-
- public void close() {
- Subject.doAs(getLoginSubject(), new PrivilegedAction<Void>(){
- public Void run() {
- close(con) ;
- return null;
- }
- });
- }
-
- private void close(Statement aStat) {
- try {
- if (aStat != null) {
- aStat.close();
- }
- } catch (SQLException e) {
- LOG.error("Unable to close SQL statement", e);
- }
- }
-
- private void close(ResultSet aResultSet) {
- try {
- if (aResultSet != null) {
- aResultSet.close();
- }
- } catch (SQLException e) {
- LOG.error("Unable to close ResultSet", e);
- }
- }
-
- private void close(Connection aCon) {
- try {
- if (aCon != null) {
- aCon.close();
- }
- } catch (SQLException e) {
- LOG.error("Unable to close SQL Connection", e);
- }
- }
-
- private void initConnection() {
- initConnection(null,null) ;
- }
-
-
- private void initConnection(String userName, String password) {
-
- Properties prop = getConfigHolder().getXASecureSection() ;
- String driverClassName = prop.getProperty("jdbc.driverClassName") ;
- String url = prop.getProperty("jdbc.url") ;
- String errMsg = " You can still save the repository and start creating "
- + "policies, but you would not be able to use autocomplete for "
- + "resource names. Check xa_portal.log for more info.";
-
- if (driverClassName != null) {
- try {
- Driver driver = (Driver)Class.forName(driverClassName).newInstance() ;
- DriverManager.registerDriver(driver);
- } catch (SQLException e) {
- String msgDesc = "initConnection: Caught SQLException while registering "
- + "Hive driver, so Unable to connect to Hive Thrift Server instance.";
- HadoopException hdpException = new HadoopException(msgDesc, e);
- hdpException.generateResponseDataMap(false, getMessage(e),
- msgDesc + errMsg, null, null);
- throw hdpException;
- } catch (IllegalAccessException ilae) {
- String msgDesc = "initConnection: Class or its nullary constructor might not accessible."
- + "So unable to initiate connection to hive thrift server instance.";
- HadoopException hdpException = new HadoopException(msgDesc, ilae);
- hdpException.generateResponseDataMap(false, getMessage(ilae),
- msgDesc + errMsg, null, null);
- throw hdpException;
- } catch (InstantiationException ie) {
- String msgDesc = "initConnection: Class may not have its nullary constructor or "
- + "may be the instantiation fails for some other reason."
- + "So unable to initiate connection to hive thrift server instance.";
- HadoopException hdpException = new HadoopException(msgDesc, ie);
- hdpException.generateResponseDataMap(false, getMessage(ie),
- msgDesc + errMsg, null, null);
- throw hdpException;
-
- } catch (ExceptionInInitializerError eie) {
- String msgDesc = "initConnection: Got ExceptionInInitializerError, "
- + "The initialization provoked by this method fails."
- + "So unable to initiate connection to hive thrift server instance.";
- HadoopException hdpException = new HadoopException(msgDesc, eie);
- hdpException.generateResponseDataMap(false, getMessage(eie),
- msgDesc + errMsg, null, null);
- throw hdpException;
- } catch (SecurityException se) {
- String msgDesc = "initConnection: unable to initiate connection to hive thrift server instance,"
- + " The caller's class loader is not the same as or an ancestor "
- + "of the class loader for the current class and invocation of "
- + "s.checkPackageAccess() denies access to the package of this class.";
- HadoopException hdpException = new HadoopException(msgDesc, se);
- hdpException.generateResponseDataMap(false, getMessage(se),
- msgDesc + errMsg, null, null);
- throw hdpException;
- } catch (Throwable t) {
- String msgDesc = "initConnection: Unable to connect to Hive Thrift Server instance, "
- + "please provide valid value of field : {jdbc.driverClassName}.";
- HadoopException hdpException = new HadoopException(msgDesc, t);
- hdpException.generateResponseDataMap(false, getMessage(t),
- msgDesc + errMsg, null, "jdbc.driverClassName");
- throw hdpException;
- }
- }
-
- try {
-
- if (userName == null && password == null) {
- con = DriverManager.getConnection(url) ;
- }
- else {
- con = DriverManager.getConnection(url, userName, password) ;
- }
-
- } catch (SQLException e) {
- String msgDesc = "Unable to connect to Hive Thrift Server instance.";
- HadoopException hdpException = new HadoopException(msgDesc, e);
- hdpException.generateResponseDataMap(false, getMessage(e), msgDesc
- + errMsg, null, null);
- throw hdpException;
- } catch (SecurityException se) {
- String msgDesc = "Unable to connect to Hive Thrift Server instance.";
- HadoopException hdpException = new HadoopException(msgDesc, se);
- hdpException.generateResponseDataMap(false, getMessage(se), msgDesc
- + errMsg, null, null);
- throw hdpException;
- }
- }
-
-
- public static void main(String[] args) {
-
- HiveClient hc = null ;
-
- if (args.length == 0) {
- System.err.println("USAGE: java " + HiveClient.class.getName() + " dataSourceName <databaseName> <tableName> <columnName>") ;
- System.exit(1) ;
- }
-
- try {
- hc = new HiveClient(args[0]) ;
-
- if (args.length == 2) {
- List<String> dbList = hc.getDatabaseList(args[1]) ;
- if (dbList.size() == 0) {
- System.out.println("No database found with db filter [" + args[1] + "]") ;
- }
- else {
- for (String str : dbList ) {
- System.out.println("database: " + str ) ;
- }
- }
- }
- else if (args.length == 3) {
- List<String> tableList = hc.getTableList(args[1], args[2]) ;
- if (tableList.size() == 0) {
- System.out.println("No tables found under database[" + args[1] + "] with table filter [" + args[2] + "]") ;
- }
- else {
- for(String str : tableList) {
- System.out.println("Table: " + str) ;
- }
- }
- }
- else if (args.length == 4) {
- List<String> columnList = hc.getColumnList(args[1], args[2], args[3]) ;
- if (columnList.size() == 0) {
- System.out.println("No columns found for db:" + args[1] + ", table: [" + args[2] + "], with column filter [" + args[3] + "]") ;
- }
- else {
- for (String str : columnList ) {
- System.out.println("Column: " + str) ;
- }
- }
- }
-
- }
- finally {
- if (hc != null) {
- hc.close();
- }
- }
- }
-
- public static HashMap<String, Object> testConnection(String dataSource,
- HashMap<String, String> connectionProperties) {
-
- HashMap<String, Object> responseData = new HashMap<String, Object>();
- boolean connectivityStatus = false;
- String errMsg = " You can still save the repository and start creating "
- + "policies, but you would not be able to use autocomplete for "
- + "resource names. Check xa_portal.log for more info.";
-
- HiveClient connectionObj = new HiveClient(dataSource,
- connectionProperties);
- if (connectionObj != null) {
-
- List<String> testResult = connectionObj.getDatabaseList("*");
- if (testResult != null && testResult.size() != 0) {
- connectivityStatus = true;
- }
- }
- if (connectivityStatus) {
- String successMsg = "TestConnection Successful";
- generateResponseDataMap(connectivityStatus, successMsg, successMsg,
- null, null, responseData);
- } else {
- String failureMsg = "Unable to retrieve any databases using given parameters.";
- generateResponseDataMap(connectivityStatus, failureMsg, failureMsg + errMsg,
- null, null, responseData);
- }
-
- connectionObj.close();
- return responseData;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/com/xasecure/hive/client/HiveClientTester.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/com/xasecure/hive/client/HiveClientTester.java b/lookup-client/src/main/java/com/xasecure/hive/client/HiveClientTester.java
deleted file mode 100644
index bf390f5..0000000
--- a/lookup-client/src/main/java/com/xasecure/hive/client/HiveClientTester.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * 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 com.xasecure.hive.client;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Properties;
-
-public class HiveClientTester {
-
- public static void main(String[] args) throws Throwable {
-
- HiveClient hc = null ;
-
- if (args.length <= 2) {
- System.err.println("USAGE: java " + HiveClientTester.class.getName() + " dataSourceName propertyFile <databaseName> <tableName> <columnName>") ;
- System.exit(1) ;
- }
-
-
- try {
-
- Properties conf = new Properties() ;
- conf.load(HiveClientTester.class.getClassLoader().getResourceAsStream(args[1]));
-
- HashMap<String,String> prop = new HashMap<String,String>() ;
- for(Object key : conf.keySet()) {
- Object val = conf.get(key) ;
- prop.put((String)key, (String)val) ;
- }
-
-
- hc = new HiveClient(args[0], prop) ;
-
-
- if (args.length == 3) {
- List<String> dbList = hc.getDatabaseList(args[2]) ;
- if (dbList.size() == 0) {
- System.out.println("No database found with db filter [" + args[2] + "]") ;
- }
- else {
- for (String str : dbList ) {
- System.out.println("database: " + str ) ;
- }
- }
- }
- else if (args.length == 4) {
- List<String> tableList = hc.getTableList(args[2], args[3]) ;
- if (tableList.size() == 0) {
- System.out.println("No tables found under database[" + args[2] + "] with table filter [" + args[3] + "]") ;
- }
- else {
- for(String str : tableList) {
- System.out.println("Table: " + str) ;
- }
- }
- }
- else if (args.length == 5) {
- List<String> columnList = hc.getColumnList(args[2], args[3], args[4]) ;
- if (columnList.size() == 0) {
- System.out.println("No columns found for db:" + args[2] + ", table: [" + args[3] + "], with column filter [" + args[4] + "]") ;
- }
- else {
- for (String str : columnList ) {
- System.out.println("Column: " + str) ;
- }
- }
- }
-
- }
- finally {
- if (hc != null) {
- hc.close();
- }
- }
-
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/com/xasecure/knox/client/KnoxClient.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/com/xasecure/knox/client/KnoxClient.java b/lookup-client/src/main/java/com/xasecure/knox/client/KnoxClient.java
deleted file mode 100644
index e9825de..0000000
--- a/lookup-client/src/main/java/com/xasecure/knox/client/KnoxClient.java
+++ /dev/null
@@ -1,387 +0,0 @@
-/**
- * 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 com.xasecure.knox.client;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.Callable;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.codehaus.jackson.JsonNode;
-import org.codehaus.jackson.map.ObjectMapper;
-
-import com.sun.jersey.api.client.Client;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.WebResource;
-import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
-import com.xasecure.hadoop.client.config.BaseClient;
-import com.xasecure.hadoop.client.exceptions.HadoopException;
-
-public class KnoxClient {
-
- private static final String EXPECTED_MIME_TYPE = "application/json";
- private static final Log LOG = LogFactory.getLog(KnoxClient.class);
-
- private String knoxUrl;
- private String userName;
- private String password;
-
- /*
- Sample curl calls to Knox to discover topologies
- curl -ivk -u admin:admin-password https://localhost:8443/gateway/admin/api/v1/topologies
- curl -ivk -u admin:admin-password https://localhost:8443/gateway/admin/api/v1/topologies/admin
- */
-
- public KnoxClient(String knoxUrl, String userName, String password) {
- LOG.debug("Constructed KnoxClient with knoxUrl: " + knoxUrl +
- ", userName: " + userName);
- this.knoxUrl = knoxUrl;
- this.userName = userName;
- this.password = password;
- }
-
- public List<String> getTopologyList(String topologyNameMatching) {
-
- // sample URI: https://hdp.example.com:8443/gateway/admin/api/v1/topologies
- LOG.debug("Getting Knox topology list for topologyNameMatching : " +
- topologyNameMatching);
- List<String> topologyList = new ArrayList<String>();
- String errMsg = " You can still save the repository and start creating "
- + "policies, but you would not be able to use autocomplete for "
- + "resource names. Check xa_portal.log for more info.";
- if ( topologyNameMatching == null || topologyNameMatching.trim().isEmpty()) {
- topologyNameMatching = "";
- }
- try {
-
- Client client = null;
- ClientResponse response = null;
-
- try {
- client = Client.create();;
-
- client.addFilter(new HTTPBasicAuthFilter(userName, password));
- WebResource webResource = client.resource(knoxUrl);
- response = webResource.accept(EXPECTED_MIME_TYPE)
- .get(ClientResponse.class);
- LOG.debug("Knox topology list response: " + response);
- if (response != null) {
-
- if (response.getStatus() == 200) {
- String jsonString = response.getEntity(String.class);
- LOG.debug("Knox topology list response JSON string: "+ jsonString);
-
- ObjectMapper objectMapper = new ObjectMapper();
-
- JsonNode rootNode = objectMapper.readTree(jsonString);
- JsonNode topologyNode = rootNode.findValue("topology");
- if (topologyNode == null) {
- return topologyList;
- }
- Iterator<JsonNode> elements = topologyNode.getElements();
- while (elements.hasNext()) {
- JsonNode element = elements.next();
- String topologyName = element.get("name").getValueAsText();
- LOG.debug("Found Knox topologyName: " + topologyName);
- if (topologyName.startsWith(topologyNameMatching)) {
- topologyList.add(topologyName);
- }
- }
- } else {
- LOG.error("Got invalid REST response from: "+ knoxUrl + ", responsStatus: " + response.getStatus());
- }
-
- } else {
- String msgDesc = "Unable to get a valid response for "
- + "isFileChanged() call for KnoxUrl : [" + knoxUrl
- + "] - got null response.";
- LOG.error(msgDesc);
- HadoopException hdpException = new HadoopException(msgDesc);
- hdpException.generateResponseDataMap(false, msgDesc,
- msgDesc + errMsg, null, null);
- throw hdpException;
- }
-
- } finally {
- if (response != null) {
- response.close();
- }
- if (client != null) {
- client.destroy();
- }
- }
- } catch (HadoopException he) {
- throw he;
- } catch (Throwable t) {
- String msgDesc = "Exception on REST call to KnoxUrl : " + knoxUrl + ".";
- HadoopException hdpException = new HadoopException(msgDesc, t);
- LOG.error(msgDesc, t);
-
- hdpException.generateResponseDataMap(false,
- BaseClient.getMessage(t), msgDesc + errMsg, null, null);
- throw hdpException;
- } finally {
- }
- return topologyList;
- }
-
-
- public List<String> getServiceList(String topologyName, String serviceNameMatching) {
-
- // sample URI: .../admin/api/v1/topologies/<topologyName>
-
- List<String> serviceList = new ArrayList<String>();
- String errMsg = " You can still save the repository and start creating "
- + "policies, but you would not be able to use autocomplete for "
- + "resource names. Check xa_portal.log for more info.";
- if ( serviceNameMatching == null || serviceNameMatching.trim().isEmpty()) {
- serviceNameMatching = "";
- }
- try {
-
- Client client = null;
- ClientResponse response = null;
-
- try {
- client = Client.create();;
-
- client.addFilter(new HTTPBasicAuthFilter(userName, password));
-
- WebResource webResource = client.resource(knoxUrl + "/" + topologyName);
-
- response = webResource.accept(EXPECTED_MIME_TYPE)
- .get(ClientResponse.class);
- LOG.debug("Knox service lookup response: " + response);
- if (response != null) {
-
- if (response.getStatus() == 200) {
- String jsonString = response.getEntity(String.class);
- LOG.debug("Knox service look up response JSON string: " + jsonString);
-
- ObjectMapper objectMapper = new ObjectMapper();
-
- JsonNode rootNode = objectMapper.readTree(jsonString);
- JsonNode topologyNode = rootNode.findValue("topology");
- JsonNode servicesNode = topologyNode.get("services");
- Iterator<JsonNode> services = servicesNode.getElements();
- while (services.hasNext()) {
- JsonNode service = services.next();
- String serviceName = service.get("role").getValueAsText();
- LOG.debug("Knox serviceName: " + serviceName);
- if (serviceName.startsWith(serviceNameMatching)) {
- serviceList.add(serviceName);
- }
- }
- } else {
- LOG.error("Got invalid REST response from: "+ knoxUrl + ", responsStatus: " + response.getStatus());
- }
-
- } else {
- String msgDesc = "Unable to get a valid response for "
- + "isFileChanged() call for KnoxUrl : [" + knoxUrl
- + "] - got null response.";
- LOG.error(msgDesc);
- HadoopException hdpException = new HadoopException(msgDesc);
- hdpException.generateResponseDataMap(false, msgDesc,
- msgDesc + errMsg, null, null);
- throw hdpException;
- }
-
- } finally {
- if (response != null) {
- response.close();
- }
- if (client != null) {
- client.destroy();
- }
- }
- } catch (HadoopException he) {
- throw he;
- } catch (Throwable t) {
- String msgDesc = "Exception on REST call to KnoxUrl : " + knoxUrl + ".";
- HadoopException hdpException = new HadoopException(msgDesc, t);
- LOG.error(msgDesc, t);
-
- hdpException.generateResponseDataMap(false,
- BaseClient.getMessage(t), msgDesc + errMsg, null, null);
- throw hdpException;
-
- } finally {
- }
- return serviceList;
- }
-
- public static void main(String[] args) {
-
- KnoxClient knoxClient = null;
-
- if (args.length != 3) {
- System.err.println("USAGE: java " + KnoxClient.class.getName()
- + " knoxUrl userName password [sslConfigFileName]");
- System.exit(1);
- }
-
- try {
- knoxClient = new KnoxClient(args[0], args[1], args[2]);
- List<String> topologyList = knoxClient.getTopologyList("");
- if ((topologyList == null) || topologyList.isEmpty()) {
- System.out.println("No knox topologies found");
- } else {
- for (String topology : topologyList) {
- System.out.println("Found Topology: " + topology);
- List<String> serviceList = knoxClient.getServiceList(topology, "");
- if ((serviceList == null) || serviceList.isEmpty()) {
- System.out.println("No services found for knox topology: " + topology);
- } else {
- for (String service : serviceList) {
- System.out.println(" Found service for topology: " + service +", " + topology);
- }
- }
- }
- }
- } finally {
- }
- }
-
- public static HashMap<String, Object> testConnection(String dataSource,
- HashMap<String, String> connectionProperties) {
-
- List<String> strList = new ArrayList<String>();
- String errMsg = " You can still save the repository and start creating "
- + "policies, but you would not be able to use autocomplete for "
- + "resource names. Check xa_portal.log for more info.";
- boolean connectivityStatus = false;
- HashMap<String, Object> responseData = new HashMap<String, Object>();
-
- KnoxClient knoxClient = getKnoxClient(dataSource, connectionProperties);
- strList = getKnoxResources(knoxClient, "", null);
-
- if (strList != null && (strList.size() != 0)) {
- connectivityStatus = true;
- }
-
- if (connectivityStatus) {
- String successMsg = "TestConnection Successful";
- BaseClient.generateResponseDataMap(connectivityStatus, successMsg, successMsg,
- null, null, responseData);
- } else {
- String failureMsg = "Unable to retrieve any topologies/services using given parameters.";
- BaseClient.generateResponseDataMap(connectivityStatus, failureMsg, failureMsg + errMsg,
- null, null, responseData);
- }
-
- return responseData;
- }
-
- public static KnoxClient getKnoxClient(String dataSourceName,
- Map<String, String> configMap) {
- KnoxClient knoxClient = null;
- LOG.debug("Getting knoxClient for datasource: " + dataSourceName
- + "configMap: " + configMap);
- String errMsg = " You can still save the repository and start creating "
- + "policies, but you would not be able to use autocomplete for "
- + "resource names. Check xa_portal.log for more info.";
- if (configMap == null || configMap.isEmpty()) {
- String msgDesc = "Could not connect as Connection ConfigMap is empty.";
- LOG.error(msgDesc);
- HadoopException hdpException = new HadoopException(msgDesc);
- hdpException.generateResponseDataMap(false, msgDesc, msgDesc + errMsg, null,
- null);
- throw hdpException;
- } else {
- String knoxUrl = configMap.get("knox.url");
- String knoxAdminUser = configMap.get("username");
- String knoxAdminPassword = configMap.get("password");
- knoxClient = new KnoxClient(knoxUrl, knoxAdminUser,
- knoxAdminPassword);
- }
- return knoxClient;
- }
-
- public static List<String> getKnoxResources(final KnoxClient knoxClient,
- String topologyName, String serviceName) {
-
- List<String> resultList = new ArrayList<String>();
- String errMsg = " You can still save the repository and start creating "
- + "policies, but you would not be able to use autocomplete for "
- + "resource names. Check xa_portal.log for more info.";
-
- try {
- if (knoxClient == null) {
- // LOG.error("Unable to get knox resources: knoxClient is null");
- // return new ArrayList<String>();
- String msgDesc = "Unable to get knox resources: knoxClient is null.";
- LOG.error(msgDesc);
- HadoopException hdpException = new HadoopException(msgDesc);
- hdpException.generateResponseDataMap(false, msgDesc, msgDesc + errMsg,
- null, null);
- throw hdpException;
- }
-
- final Callable<List<String>> callableObj;
- if (serviceName != null) {
- final String finalServiceNameMatching = serviceName.trim();
- final String finalTopologyName = topologyName;
- callableObj = new Callable<List<String>>() {
- @Override
- public List<String> call() {
- return knoxClient.getServiceList(finalTopologyName,
- finalServiceNameMatching);
- }
- };
-
- } else {
- final String finalTopologyNameMatching = (topologyName == null) ? ""
- : topologyName.trim();
- callableObj = new Callable<List<String>>() {
- @Override
- public List<String> call() {
- return knoxClient
- .getTopologyList(finalTopologyNameMatching);
- }
- };
- }
- resultList = timedTask(callableObj, 5, TimeUnit.SECONDS);
-
- } catch (HadoopException he) {
- throw he;
- } catch (Exception e) {
- String msgDesc = "Unable to get knox resources.";
- LOG.error(msgDesc, e);
- HadoopException hdpException = new HadoopException(msgDesc);
-
- hdpException.generateResponseDataMap(false,
- BaseClient.getMessage(e), msgDesc + errMsg, null, null);
- throw hdpException;
- }
-
- return resultList;
- }
-
- public static <T> T timedTask(Callable<T> callableObj, long timeout,
- TimeUnit timeUnit) throws Exception {
- return callableObj.call();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/com/xasecure/knox/client/KnoxClientTest.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/com/xasecure/knox/client/KnoxClientTest.java b/lookup-client/src/main/java/com/xasecure/knox/client/KnoxClientTest.java
deleted file mode 100644
index 3ba3e76..0000000
--- a/lookup-client/src/main/java/com/xasecure/knox/client/KnoxClientTest.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/**
- * 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 com.xasecure.knox.client;
-
-public class KnoxClientTest {
-
-
- /*
- Sample curl calls to knox REST API to discover topologies
- curl -ivk -u admin:admin-password https://localhost:8443/gateway/admin/api/v1/topologies
- curl -ivk -u admin:admin-password https://localhost:8443/gateway/admin/api/v1/topologies/admin
- */
-
- public static void main(String[] args) {
- System.out.println(System.getProperty("java.class.path"));
- System.setProperty("javax.net.ssl.trustStore", "/tmp/cacertswithknox)");
- String[] testArgs = {
- "https://localhost:8443/gateway/admin/api/v1/topologies",
- "admin",
- "admin-password"
- };
- KnoxClient.main(testArgs);
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/com/xasecure/knox/client/XaSecureConstants.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/com/xasecure/knox/client/XaSecureConstants.java b/lookup-client/src/main/java/com/xasecure/knox/client/XaSecureConstants.java
deleted file mode 100644
index 191bebb..0000000
--- a/lookup-client/src/main/java/com/xasecure/knox/client/XaSecureConstants.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/**
- * 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 com.xasecure.knox.client;
-
-public class XaSecureConstants {
-
- // xasecure 2-way ssl configuration
-
- public static final String XASECURE_KNOX_CLIENT_KEY_FILE = "xasecure.knoxclient.ssl.keystore";
- public static final String XASECURE_KNOX_CLIENT_KEY_FILE_PASSWORD = "xasecure.knoxclien.tssl.keystore.password";
- public static final String XASECURE_KNOX_CLIENT_KEY_FILE_TYPE = "xasecure.knoxclient.ssl.keystore.type";
-
- public static final String XASECURE_KNOX_CLIENT_KEY_FILE_TYPE_DEFAULT = "jks";
-
- public static final String XASECURE_KNOX_CLIENT_TRUSTSTORE_FILE = "xasecure.knoxclient.ssl.truststore";
- public static final String XASECURE_KNOX_CLIENT_TRUSTSTORE_FILE_PASSWORD = "xasecure.knoxclient.ssl.truststore.password";
- public static final String XASECURE_KNOX_CLIENT_TRUSTSTORE_FILE_TYPE = "xasecure.knoxclient.ssl.truststore.type";
-
- public static final String XASECURE_KNOX_CLIENT_TRUSTSTORE_FILE_TYPE_DEFAULT = "jks";
-
-
- public static final String XASECURE_SSL_KEYMANAGER_ALGO_TYPE = "SunX509" ;
- public static final String XASECURE_SSL_TRUSTMANAGER_ALGO_TYPE = "SunX509" ;
- public static final String XASECURE_SSL_CONTEXT_ALGO_TYPE = "SSL" ;
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/com/xasecure/storm/client/StormClient.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/com/xasecure/storm/client/StormClient.java b/lookup-client/src/main/java/com/xasecure/storm/client/StormClient.java
deleted file mode 100644
index f1c7449..0000000
--- a/lookup-client/src/main/java/com/xasecure/storm/client/StormClient.java
+++ /dev/null
@@ -1,395 +0,0 @@
-/*
- * 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 com.xasecure.storm.client;
-
-import java.io.IOException;
-import java.security.PrivilegedAction;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.security.auth.Subject;
-import javax.security.auth.login.AppConfigurationEntry;
-import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag;
-import javax.security.auth.login.LoginContext;
-import javax.security.auth.login.LoginException;
-
-import org.apache.commons.io.FilenameUtils;
-import org.apache.hadoop.security.KrbPasswordSaverLoginModule;
-import org.apache.hadoop.security.authentication.util.KerberosUtil;
-import org.apache.log4j.Logger;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.sun.jersey.api.client.Client;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.WebResource;
-import com.xasecure.hadoop.client.config.BaseClient;
-import com.xasecure.hadoop.client.exceptions.HadoopException;
-import com.xasecure.storm.client.json.model.Topology;
-import com.xasecure.storm.client.json.model.TopologyListResponse;
-
-public class StormClient {
-
- public static final Logger LOG = Logger.getLogger(StormClient.class) ;
-
- private static final String EXPECTED_MIME_TYPE = "application/json";
-
- private static final String TOPOLOGY_LIST_API_ENDPOINT = "/api/v1/topology/summary" ;
-
-
- String stormUIUrl;
- String userName;
- String password;
-
- public StormClient(String aStormUIUrl, String aUserName, String aPassword) {
-
- this.stormUIUrl = aStormUIUrl;
- this.userName = aUserName ;
- this.password = aPassword;
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Storm Client is build with url [" + aStormUIUrl + "] user: [" + aUserName + "], password: [" + "" + "]");
- }
-
- }
-
- public List<String> getTopologyList(final String topologyNameMatching) {
-
- LOG.debug("Getting Storm topology list for topologyNameMatching : " +
- topologyNameMatching);
- final String errMsg = " You can still save the repository and start creating "
- + "policies, but you would not be able to use autocomplete for "
- + "resource names. Check xa_portal.log for more info.";
-
- List<String> ret = new ArrayList<String>();
-
- PrivilegedAction<ArrayList<String>> topologyListGetter = new PrivilegedAction<ArrayList<String>>() {
- @Override
- public ArrayList<String> run() {
-
- ArrayList<String> lret = new ArrayList<String>();
-
- String url = stormUIUrl + TOPOLOGY_LIST_API_ENDPOINT ;
-
- Client client = null ;
- ClientResponse response = null ;
-
- try {
- client = Client.create() ;
-
- WebResource webResource = client.resource(url);
-
- response = webResource.accept(EXPECTED_MIME_TYPE)
- .get(ClientResponse.class);
-
- LOG.debug("getTopologyList():calling " + url);
-
- if (response != null) {
- LOG.debug("getTopologyList():response.getStatus()= " + response.getStatus());
- if (response.getStatus() == 200) {
- String jsonString = response.getEntity(String.class);
- Gson gson = new GsonBuilder().setPrettyPrinting().create();
- TopologyListResponse topologyListResponse = gson.fromJson(jsonString, TopologyListResponse.class);
- if (topologyListResponse != null) {
- if (topologyListResponse.getTopologyList() != null) {
- for(Topology topology : topologyListResponse.getTopologyList()) {
- String toplogyName = topology.getName() ;
- LOG.debug("getTopologyList():Found topology " + toplogyName);
- LOG.debug("getTopologyList():topology Name=[" + topology.getName() + "], topologyNameMatching=[" + topologyNameMatching + "]");
- if (toplogyName != null) {
- if (topologyNameMatching == null || topologyNameMatching.isEmpty() || FilenameUtils.wildcardMatch(topology.getName(), topologyNameMatching + "*")) {
- LOG.debug("getTopologyList():Adding topology " + toplogyName);
- lret.add(toplogyName) ;
- }
- }
- }
- }
- }
- } else{
- LOG.info("getTopologyList():response.getStatus()= " + response.getStatus() + " for URL " + url + ", so returning null list");
- String jsonString = response.getEntity(String.class);
- LOG.info(jsonString);
- lret = null;
- }
- } else {
- String msgDesc = "Unable to get a valid response for "
- + "expected mime type : [" + EXPECTED_MIME_TYPE
- + "] URL : " + url + " - got null response.";
- LOG.error(msgDesc);
- HadoopException hdpException = new HadoopException(msgDesc);
- hdpException.generateResponseDataMap(false, msgDesc,
- msgDesc + errMsg, null, null);
- throw hdpException;
- }
- } catch (HadoopException he) {
- throw he;
- } catch (Throwable t) {
- String msgDesc = "Exception while getting Storm TopologyList."
- + " URL : " + url;
- HadoopException hdpException = new HadoopException(msgDesc,
- t);
- LOG.error(msgDesc, t);
-
- hdpException.generateResponseDataMap(false,
- BaseClient.getMessage(t), msgDesc + errMsg, null,
- null);
- throw hdpException;
-
- } finally {
- if (response != null) {
- response.close();
- }
-
- if (client != null) {
- client.destroy();
- }
-
- }
- return lret ;
- }
- } ;
-
- try {
- ret = executeUnderKerberos(this.userName, this.password, topologyListGetter) ;
- } catch (IOException e) {
- LOG.error("Unable to get Topology list from [" + stormUIUrl + "]", e) ;
- }
-
- return ret;
- }
-
- public static <T> T executeUnderKerberos(String userName, String password,
- PrivilegedAction<T> action) throws IOException {
-
- final String errMsg = " You can still save the repository and start creating "
- + "policies, but you would not be able to use autocomplete for "
- + "resource names. Check xa_portal.log for more info.";
- class MySecureClientLoginConfiguration extends
- javax.security.auth.login.Configuration {
-
- private String userName;
- private String password ;
-
- MySecureClientLoginConfiguration(String aUserName,
- String password) {
- this.userName = aUserName;
- this.password = password;
- }
-
- @Override
- public AppConfigurationEntry[] getAppConfigurationEntry(
- String appName) {
-
- Map<String, String> kerberosOptions = new HashMap<String, String>();
- kerberosOptions.put("principal", this.userName);
- kerberosOptions.put("debug", "true");
- kerberosOptions.put("useKeyTab", "false");
- kerberosOptions.put(KrbPasswordSaverLoginModule.USERNAME_PARAM, this.userName);
- kerberosOptions.put(KrbPasswordSaverLoginModule.PASSWORD_PARAM, this.password);
- kerberosOptions.put("doNotPrompt", "false");
- kerberosOptions.put("useFirstPass", "true");
- kerberosOptions.put("tryFirstPass", "false");
- kerberosOptions.put("storeKey", "true");
- kerberosOptions.put("refreshKrb5Config", "true");
-
- AppConfigurationEntry KEYTAB_KERBEROS_LOGIN = null;
- AppConfigurationEntry KERBEROS_PWD_SAVER = null;
- try {
- KEYTAB_KERBEROS_LOGIN = new AppConfigurationEntry(
- KerberosUtil.getKrb5LoginModuleName(),
- AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
- kerberosOptions);
- KERBEROS_PWD_SAVER = new AppConfigurationEntry(KrbPasswordSaverLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, kerberosOptions);
-
- } catch (IllegalArgumentException e) {
- String msgDesc = "executeUnderKerberos: Exception while getting Storm TopologyList.";
- HadoopException hdpException = new HadoopException(msgDesc,
- e);
- LOG.error(msgDesc, e);
-
- hdpException.generateResponseDataMap(false,
- BaseClient.getMessage(e), msgDesc + errMsg, null,
- null);
- throw hdpException;
- }
-
- LOG.debug("getAppConfigurationEntry():" + kerberosOptions.get("principal"));
-
- return new AppConfigurationEntry[] { KERBEROS_PWD_SAVER, KEYTAB_KERBEROS_LOGIN };
- }
-
- };
-
- T ret = null;
-
- Subject subject = null;
- LoginContext loginContext = null;
-
- try {
- subject = new Subject();
- LOG.debug("executeUnderKerberos():user=" + userName + ",pass=");
- LOG.debug("executeUnderKerberos():Creating config..");
- MySecureClientLoginConfiguration loginConf = new MySecureClientLoginConfiguration(
- userName, password);
- LOG.debug("executeUnderKerberos():Creating Context..");
- loginContext = new LoginContext("hadoop-keytab-kerberos", subject,
- null, loginConf);
-
- LOG.debug("executeUnderKerberos():Logging in..");
- loginContext.login();
-
- Subject loginSubj = loginContext.getSubject();
-
- if (loginSubj != null) {
- ret = Subject.doAs(loginSubj, action);
- }
- } catch (LoginException le) {
- String msgDesc = "executeUnderKerberos: Login failure using given"
- + " configuration parameters, username : `" + userName + "`.";
- HadoopException hdpException = new HadoopException(msgDesc, le);
- LOG.error(msgDesc, le);
-
- hdpException.generateResponseDataMap(false,
- BaseClient.getMessage(le), msgDesc + errMsg, null, null);
- throw hdpException;
- } catch (SecurityException se) {
- String msgDesc = "executeUnderKerberos: Exception while getting Storm TopologyList.";
- HadoopException hdpException = new HadoopException(msgDesc, se);
- LOG.error(msgDesc, se);
-
- hdpException.generateResponseDataMap(false,
- BaseClient.getMessage(se), msgDesc + errMsg, null, null);
- throw hdpException;
-
- } finally {
- if (loginContext != null) {
- if (subject != null) {
- try {
- loginContext.logout();
- } catch (LoginException e) {
- throw new IOException("logout failure", e);
- }
- }
- }
- }
-
- return ret;
- }
-
- public static HashMap<String, Object> testConnection(String dataSource,
- HashMap<String, String> connectionProperties) {
-
- List<String> strList = new ArrayList<String>();
- String errMsg = " You can still save the repository and start creating "
- + "policies, but you would not be able to use autocomplete for "
- + "resource names. Check xa_portal.log for more info.";
- boolean connectivityStatus = false;
- HashMap<String, Object> responseData = new HashMap<String, Object>();
-
- StormClient stormClient = getStormClient(dataSource,
- connectionProperties);
- strList = getStormResources(stormClient, "");
-
- if (strList != null) {
- connectivityStatus = true;
- }
-
- if (connectivityStatus) {
- String successMsg = "TestConnection Successful";
- BaseClient.generateResponseDataMap(connectivityStatus, successMsg,
- successMsg, null, null, responseData);
- } else {
- String failureMsg = "Unable to retrieve any topologies using given parameters.";
- BaseClient.generateResponseDataMap(connectivityStatus, failureMsg,
- failureMsg + errMsg, null, null, responseData);
- }
-
- return responseData;
- }
-
- public static StormClient getStormClient(String dataSourceName,
- Map<String, String> configMap) {
- StormClient stormClient = null;
- LOG.debug("Getting StormClient for datasource: " + dataSourceName
- + "configMap: " + configMap);
- String errMsg = " You can still save the repository and start creating "
- + "policies, but you would not be able to use autocomplete for "
- + "resource names. Check xa_portal.log for more info.";
- if (configMap == null || configMap.isEmpty()) {
- String msgDesc = "Could not connect as Connection ConfigMap is empty.";
- LOG.error(msgDesc);
- HadoopException hdpException = new HadoopException(msgDesc);
- hdpException.generateResponseDataMap(false, msgDesc, msgDesc
- + errMsg, null, null);
- throw hdpException;
- } else {
- String stormUrl = configMap.get("nimbus.url");
- String stormAdminUser = configMap.get("username");
- String stormAdminPassword = configMap.get("password");
- stormClient = new StormClient(stormUrl, stormAdminUser,
- stormAdminPassword);
- }
- return stormClient;
- }
-
- public static List<String> getStormResources(final StormClient stormClient,
- String topologyName) {
-
- List<String> resultList = new ArrayList<String>();
- String errMsg = " You can still save the repository and start creating "
- + "policies, but you would not be able to use autocomplete for "
- + "resource names. Check xa_portal.log for more info.";
-
- try {
- if (stormClient == null) {
- String msgDesc = "Unable to get Storm resources: StormClient is null.";
- LOG.error(msgDesc);
- HadoopException hdpException = new HadoopException(msgDesc);
- hdpException.generateResponseDataMap(false, msgDesc, msgDesc
- + errMsg, null, null);
- throw hdpException;
- }
-
- if (topologyName != null) {
- String finalTopologyNameMatching = (topologyName == null) ? ""
- : topologyName.trim();
- resultList = stormClient
- .getTopologyList(finalTopologyNameMatching);
- if (resultList != null) {
- LOG.debug("Returning list of " + resultList.size() + " topologies");
- }
- }
- } catch (HadoopException he) {
- throw he;
- } catch (Exception e) {
- String msgDesc = "getStormResources: Unable to get Storm resources.";
- LOG.error(msgDesc, e);
- HadoopException hdpException = new HadoopException(msgDesc);
-
- hdpException.generateResponseDataMap(false,
- BaseClient.getMessage(e), msgDesc + errMsg, null, null);
- throw hdpException;
- }
- return resultList;
- }
-
-}
[18/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/rest/AssetREST.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/rest/AssetREST.java b/security-admin/src/main/java/com/xasecure/rest/AssetREST.java
deleted file mode 100644
index 2662409..0000000
--- a/security-admin/src/main/java/com/xasecure/rest/AssetREST.java
+++ /dev/null
@@ -1,655 +0,0 @@
-/*
- * 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 com.xasecure.rest;
-
-import java.io.File;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.Encoded;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Scope;
-import org.springframework.security.access.prepost.PreAuthorize;
-import org.springframework.stereotype.Component;
-import org.springframework.transaction.annotation.Propagation;
-import org.springframework.transaction.annotation.Transactional;
-
-import com.xasecure.biz.AssetMgr;
-import com.xasecure.biz.XABizUtil;
-import com.xasecure.common.PropertiesUtil;
-import com.xasecure.common.RESTErrorUtil;
-import com.xasecure.common.SearchCriteria;
-import com.xasecure.common.StringUtil;
-import com.xasecure.common.XACommonEnums;
-import com.xasecure.common.XASearchUtil;
-import com.xasecure.common.annotation.XAAnnotationClassName;
-import com.xasecure.common.annotation.XAAnnotationJSMgrName;
-import com.xasecure.service.AbstractBaseResourceService;
-import com.xasecure.service.XAccessAuditService;
-import com.xasecure.service.XAgentService;
-import com.xasecure.service.XAssetService;
-import com.xasecure.service.XCredentialStoreService;
-import com.xasecure.service.XPolicyExportAuditService;
-import com.xasecure.service.XPolicyService;
-import com.xasecure.service.XResourceService;
-import com.xasecure.service.XTrxLogService;
-import com.xasecure.view.VXAccessAuditList;
-import com.xasecure.view.VXAsset;
-import com.xasecure.view.VXAssetList;
-import com.xasecure.view.VXCredentialStore;
-import com.xasecure.view.VXCredentialStoreList;
-import com.xasecure.view.VXLong;
-import com.xasecure.view.VXPermMap;
-import com.xasecure.view.VXPolicy;
-import com.xasecure.view.VXPolicyExportAuditList;
-import com.xasecure.view.VXResource;
-import com.xasecure.view.VXResourceList;
-import com.xasecure.view.VXResponse;
-import com.xasecure.view.VXString;
-import com.xasecure.view.VXStringList;
-import com.xasecure.view.VXTrxLogList;
-
-@Path("assets")
-@Component
-@Scope("request")
-@XAAnnotationJSMgrName("AssetMgr")
-@Transactional(propagation = Propagation.REQUIRES_NEW)
-public class AssetREST {
- static Logger logger = Logger.getLogger(AssetREST.class);
-
- @Autowired
- XASearchUtil searchUtil;
-
- @Autowired
- AssetMgr assetMgr;
-
- @Autowired
- XAssetService xAssetService;
-
- @Autowired
- XResourceService xResourceService;
-
- @Autowired
- XPolicyService xPolicyService;
-
- @Autowired
- XCredentialStoreService xCredentialStoreService;
-
- @Autowired
- XAgentService xAgentService;
-
- @Autowired
- RESTErrorUtil restErrorUtil;
-
- @Autowired
- XPolicyExportAuditService xPolicyExportAudits;
-
- @Autowired
- XTrxLogService xTrxLogService;
-
- @Autowired
- XABizUtil msBizUtil;
-
- @Autowired
- XAccessAuditService xAccessAuditService;
-
- @GET
- @Path("/assets/{id}")
- @Produces({ "application/xml", "application/json" })
- public VXAsset getXAsset(@PathParam("id") Long id) {
- return assetMgr.getXAsset(id);
- }
-
- @POST
- @Path("/assets")
- @Produces({ "application/xml", "application/json" })
- public VXAsset createXAsset(VXAsset vXAsset) {
- return assetMgr.createXAsset(vXAsset);
- }
-
- @PUT
- @Path("/assets/{id}")
- @Produces({ "application/xml", "application/json" })
- public VXAsset updateXAsset(VXAsset vXAsset) {
- return assetMgr.updateXAsset(vXAsset);
- }
-
- @DELETE
- @Path("/assets/{id}")
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
- @XAAnnotationClassName(class_name = VXAsset.class)
- public void deleteXAsset(@PathParam("id") Long id,
- @Context HttpServletRequest request) {
- boolean force = true;
- assetMgr.deleteXAsset(id, force);
- }
-
- @POST
- @Path("/assets/testConfig")
- @Produces({ "application/xml", "application/json" })
- public VXResponse testConfig(VXAsset vXAsset) {
- return assetMgr.testConfig(vXAsset);
- }
-
- @GET
- @Path("/assets")
- @Produces({ "application/xml", "application/json" })
- @SuppressWarnings("rawtypes")
- public VXAssetList searchXAssets(@Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xAssetService.sortFields);
-
- searchUtil.extractIntList(request, searchCriteria, "status", "status",
- "status");
- // searchUtil.extractStringList(request, searchCriteria, "status",
- // "status", "status", null, StringUtil.VALIDATION_TEXT);
- Object status = searchCriteria.getParamValue("status");
- if (status == null || ((Collection) status).size() == 0) {
- ArrayList<Integer> valueList = new ArrayList<Integer>();
- valueList.add(XACommonEnums.STATUS_DISABLED);
- valueList.add(XACommonEnums.STATUS_ENABLED);
- searchCriteria.addParam("status", valueList);
- }
- return assetMgr.searchXAssets(searchCriteria);
- }
-
- @GET
- @Path("/assets/count")
- @Produces({ "application/xml", "application/json" })
- public VXLong countXAssets(@Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xAssetService.sortFields);
-
- searchUtil.extractIntList(request, searchCriteria, "status", "status",
- "status");
- Object status = searchCriteria.getParamValue("status");
- if (status == null || ((Collection) status).size() == 0) {
- ArrayList<Integer> valueList = new ArrayList<Integer>();
- valueList.add(XACommonEnums.STATUS_DISABLED);
- valueList.add(XACommonEnums.STATUS_ENABLED);
- searchCriteria.addParam("status", valueList);
- }
- return assetMgr.getXAssetSearchCount(searchCriteria);
- }
-
- @GET
- @Path("/resources/{id}")
- @Produces({ "application/xml", "application/json" })
- public VXResource getXResource(@PathParam("id") Long id) {
- return assetMgr.getXResource(id);
- }
-
- @POST
- @Path("/resources")
- @Produces({ "application/xml", "application/json" })
- public VXResource createXResource(VXResource vXResource) {
- vXResource=assetMgr.createXResource(vXResource);
- return vXResource;
-
- }
-
- @PUT
- @Path("/resources/{id}")
- @Produces({ "application/xml", "application/json" })
- public VXResource updateXResource(VXResource vXResource) {
- return assetMgr.updateXResource(vXResource);
- }
-
- @DELETE
- @Path("/resources/{id}")
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
- @XAAnnotationClassName(class_name = VXResource.class)
- public void deleteXResource(@PathParam("id") Long id,
- @Context HttpServletRequest request) {
- boolean force = false;
- assetMgr.deleteXResource(id, force);
- }
-
- @GET
- @Path("/resources")
- @Produces({ "application/xml", "application/json" })
- public VXResourceList searchXResources(@Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xResourceService.sortFields);
- // searchUtil.extractStringList(request, searchCriteria, "name", "Name",
- // "name", null, StringUtil.VALIDATION_TEXT);
-
- searchUtil.extractString(request, searchCriteria, "name",
- "Resource Path", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "policyName",
- "Policy name", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "columns",
- "Column name", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "columnFamilies",
- "Column Family", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "tables",
- "Tables", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "udfs",
- "UDFs", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "databases",
- "Databases", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "groupName",
- "Group Name", StringUtil.VALIDATION_TEXT);
- searchUtil.extractInt(request, searchCriteria, "resourceType",
- "Resource Type");
- searchUtil.extractInt(request, searchCriteria, "assetType",
- "Asset Type");
- searchUtil.extractInt(request, searchCriteria, "isEncrypt",
- "Is Encrypt");
- searchUtil.extractInt(request, searchCriteria, "isRecursive",
- "Is Recursive");
- searchUtil.extractLong(request, searchCriteria, "assetId", "Asset Id");
- searchUtil.extractString(request, searchCriteria, "userName",
- "User Name", StringUtil.VALIDATION_TEXT);
-
- searchUtil.extractLongList(request, searchCriteria, "userId",
- "User Id", "userId");
- // searchUtil.extractLong(request, searchCriteria, "userId",
- // "User Id");
- // searchUtil.extractLong(request, searchCriteria, "groupId",
- // "Group Id");
- searchUtil.extractLongList(request, searchCriteria, "groupId",
- "Group Id", "groupId");
-
- searchUtil.extractString(request, searchCriteria, "topologies",
- "Topology Name", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "services",
- "Service Name", StringUtil.VALIDATION_TEXT);
-
- // searchUtil.extractIntList(request, searchCriteria, "status",
- // "status", "status");
-
- // SearchGroup outerGroup = new SearchGroup(SearchGroup.CONDITION.OR);
- // // Get the search fields for objectClassType and objectId
- // SearchField userId = null;
- // SearchField groupId = null;
- // SearchField resourceId = null;
- // List<SearchField> searchFields = xResourceService.searchFields;
- // for (SearchField searchField : searchFields) {
- // if (searchField.getClientFieldName().equals("userId") &&
- // request.getParameterValues("userId")!=null) {
- // userId = searchField;
- // } else if (searchField.getClientFieldName().equals("groupId") &&
- // request.getParameterValues("groupId")!=null) {
- // groupId = searchField;
- // }else if (searchField.getClientFieldName().equals("name") &&
- // request.getParameterValues("name")!=null) {
- // resourceId = searchField;
- // }
- // }
- // if (groupId != null || userId != null || resourceId != null) {
- // SearchGroup innerGroup = new SearchGroup(SearchGroup.CONDITION.AND);
- // SearchValue searchValue=null;
- // if(userId!=null){
- // searchValue = new SearchValue(userId,
- // searchCriteria.getParamValue("userId"));
- //
- // innerGroup.addValue(searchValue);
- // }
- // if(groupId!=null){
- // searchValue = new SearchValue(groupId,
- // searchCriteria.getParamValue("groupId"));
- // innerGroup.addValue(searchValue);
- // }
- // if(resourceId!=null){
- //
- // searchValue = new SearchValue(resourceId,
- // searchCriteria.getParamValue("name"));
- // innerGroup.addValue(searchValue);
- // }
- //
- // outerGroup.addSearchGroup(innerGroup);
- // searchUtil.addSearchGroup(searchCriteria, outerGroup);
- //
- // }
- searchCriteria.setDistinct(true);
-
- return assetMgr.searchXResources(searchCriteria);
- }
-
- @GET
- @Path("/hdfs/resources")
- @Produces({ "application/xml", "application/json" })
- public VXStringList pullHdfsResources(@Context HttpServletRequest request) {
- String dataSourceName = request.getParameter("dataSourceName");
- String baseDir = request.getParameter("baseDirectory");
- return assetMgr.getHdfsResources(dataSourceName, baseDir);
- }
-
- @GET
- @Path("/hive/resources")
- @Produces({ "application/xml", "application/json" })
- public VXStringList pullHiveResources(@Context HttpServletRequest request) {
- String dataSourceName = request.getParameter("dataSourceName");
- String databaseName = request.getParameter("databaseName");
- String tableName = request.getParameter("tableName");
- String columnName = request.getParameter("columnName");
- return assetMgr.getHiveResources(dataSourceName, databaseName,
- tableName, columnName);
- }
-
- @GET
- @Path("/hbase/resources")
- @Produces({ "application/xml", "application/json" })
- public VXStringList pullHBaseResources(@Context HttpServletRequest request) {
- String dataSourceName = request.getParameter("dataSourceName");
- String tableName = request.getParameter("tableName");
- String columnFamiles = request.getParameter("columnFamilies");
- return assetMgr.getHBaseResources(dataSourceName, tableName,
- columnFamiles);
- }
-
- @GET
- @Path("/knox/resources")
- @Produces({ "application/xml", "application/json" })
- public VXStringList pullKnoxResources(@Context HttpServletRequest request) {
- String dataSourceName = request.getParameter("dataSourceName");
- String topologyName = request.getParameter("topologyName");
- String serviceName = request.getParameter("serviceName");
- return assetMgr.getKnoxResources(dataSourceName, topologyName, serviceName);
- }
-
- @GET
- @Path("/storm/resources")
- @Produces({ "application/xml", "application/json" })
- public VXStringList pullStormResources(@Context HttpServletRequest request) {
- String dataSourceName = request.getParameter("dataSourceName");
- String topologyName = request.getParameter("topologyName");
- return assetMgr.getStormResources(dataSourceName, topologyName);
- }
-
- @GET
- @Path("/resources/count")
- @Produces({ "application/xml", "application/json" })
- public VXLong countXResources(@Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xResourceService.sortFields);
-
- return assetMgr.getXResourceSearchCount(searchCriteria);
- }
-
- @GET
- @Path("/credstores/{id}")
- @Produces({ "application/xml", "application/json" })
- public VXCredentialStore getXCredentialStore(@PathParam("id") Long id) {
- return assetMgr.getXCredentialStore(id);
- }
-
- @POST
- @Path("/credstores")
- @Produces({ "application/xml", "application/json" })
- public VXCredentialStore createXCredentialStore(
- VXCredentialStore vXCredentialStore) {
- return assetMgr.createXCredentialStore(vXCredentialStore);
- }
-
- @PUT
- @Path("/credstores")
- @Produces({ "application/xml", "application/json" })
- public VXCredentialStore updateXCredentialStore(
- VXCredentialStore vXCredentialStore) {
- return assetMgr.updateXCredentialStore(vXCredentialStore);
- }
-
- @DELETE
- @Path("/credstores/{id}")
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
- @XAAnnotationClassName(class_name = VXCredentialStore.class)
- public void deleteXCredentialStore(@PathParam("id") Long id,
- @Context HttpServletRequest request) {
- boolean force = false;
- assetMgr.deleteXCredentialStore(id, force);
- }
-
- @GET
- @Path("/credstores")
- @Produces({ "application/xml", "application/json" })
- public VXCredentialStoreList searchXCredentialStores(
- @Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xCredentialStoreService.sortFields);
- return assetMgr.searchXCredentialStores(searchCriteria);
- }
-
- @GET
- @Path("/credstores/count")
- @Produces({ "application/xml", "application/json" })
- public VXLong countXCredentialStores(@Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xCredentialStoreService.sortFields);
- return assetMgr.getXCredentialStoreSearchCount(searchCriteria);
- }
-
- @GET
- @Path("/resource/{id}")
- public Response getXResourceFile(@Context HttpServletRequest request,
- @PathParam("id") Long id) {
- String fileType = searchUtil.extractString(request,
- new SearchCriteria(), "fileType", "File type",
- StringUtil.VALIDATION_TEXT);
-
- File file = assetMgr.getXResourceFile(id, fileType);
- return Response
- .ok(file, MediaType.APPLICATION_OCTET_STREAM)
- .header("Content-Disposition",
- "attachment;filename=" + file.getName()).build();
- }
-
- @GET
- @Path("/policyList/{repository}")
- @Encoded
- public String getResourceJSON(@Context HttpServletRequest request,
- @PathParam("repository") String repository) {
-
- boolean httpEnabled = PropertiesUtil.getBooleanProperty("http.enabled",true);
- String epoch = request.getParameter("epoch");
-
- X509Certificate[] certchain = (X509Certificate[]) request.getAttribute(
- "javax.servlet.request.X509Certificate");
-
- String ipAddress = request.getHeader("X-FORWARDED-FOR");
- if (ipAddress == null) {
- ipAddress = request.getRemoteAddr();
- }
-
- boolean isSecure = request.isSecure();
-
- String policyCount = request.getParameter("policyCount");
- String agentId = request.getParameter("agentId");
-
-// File file = assetMgr.getLatestRepoPolicy(repository,
-// certchain, httpEnabled, epoch, ipAddress, isSecure, policyCount, agentId);
-
-
-// return Response
-// .ok(file, MediaType.APPLICATION_OCTET_STREAM)
-// .header("Content-Disposition",
-// "attachment;filename=" + file.getName()).build();
-
- String file = assetMgr.getLatestRepoPolicy(repository,
- certchain, httpEnabled, epoch, ipAddress, isSecure, policyCount, agentId);
-
- return file;
- }
-
- @GET
- @Path("/exportAudit")
- @Produces({ "application/xml", "application/json" })
- public VXPolicyExportAuditList searchXPolicyExportAudits(
- @Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xPolicyExportAudits.sortFields);
- searchUtil.extractString(request, searchCriteria, "agentId",
- "The XA agent id pulling the policies.",
- StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "clientIP",
- "The XA agent ip pulling the policies.",
- StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "repositoryName",
- "Repository name for which export was done.",
- StringUtil.VALIDATION_TEXT);
- searchUtil.extractInt(request, searchCriteria, "httpRetCode",
- "HTTP response code for exported policy.");
- searchUtil.extractDate(request, searchCriteria, "startDate",
- "Start date for search", null);
- searchUtil.extractDate(request, searchCriteria, "endDate",
- "End date for search", null);
- return assetMgr.searchXPolicyExportAudits(searchCriteria);
- }
-
- @GET
- @Path("/report")
- @Produces({ "application/xml", "application/json" })
- public VXTrxLogList getReportLogs(@Context HttpServletRequest request){
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xTrxLogService.sortFields);
- searchUtil.extractInt(request, searchCriteria, "objectClassType", "Class type for report.");
- searchUtil.extractString(request, searchCriteria, "attributeName",
- "Attribute Name", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "action",
- "CRUD Action Type", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "sessionId",
- "Session Id", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "owner",
- "Owner", StringUtil.VALIDATION_TEXT);
- searchUtil.extractDate(request, searchCriteria, "startDate", "Trasaction date since", "MM/dd/yyyy");
- searchUtil.extractDate(request, searchCriteria, "endDate", "Trasaction date till", "MM/dd/yyyy");
- return assetMgr.getReportLogs(searchCriteria);
- }
-
- @GET
- @Path("/report/{transactionId}")
- @Produces({ "application/xml", "application/json" })
- public VXTrxLogList getTransactionReport(@Context HttpServletRequest request,
- @PathParam("transactionId") String transactionId){
- return assetMgr.getTransactionReport(transactionId);
- }
-
- @GET
- @Path("/accessAudit")
- @Produces({ "application/xml", "application/json" })
- public VXAccessAuditList getAccessLogs(@Context HttpServletRequest request){
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xAccessAuditService.sortFields);
- searchUtil.extractString(request, searchCriteria, "accessType",
- "Access Type", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "aclEnforcer",
- "Access Type", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "agentId",
- "Access Type", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "repoName",
- "Access Type", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "sessionId",
- "Access Type", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "requestUser",
- "Access Type", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "requestData",
- "Access Type", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "resourcePath",
- "Access Type", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "clientIP",
- "Client IP", StringUtil.VALIDATION_TEXT);
-
- searchUtil.extractInt(request, searchCriteria, "auditType", "Audit Type");
- searchUtil.extractInt(request, searchCriteria, "accessResult", "Audit Type");
- searchUtil.extractInt(request, searchCriteria, "assetId", "Audit Type");
- searchUtil.extractLong(request, searchCriteria, "policyId", "Audit Type");
- searchUtil.extractInt(request, searchCriteria, "repoType", "Audit Type");
-
- searchUtil.extractDate(request, searchCriteria, "startDate",
- "startDate", "MM/dd/yyyy");
- searchUtil.extractDate(request, searchCriteria, "endDate", "endDate",
- "MM/dd/yyyy");
- return assetMgr.getAccessLogs(searchCriteria);
- }
-
- @POST
- @Path("/resources/grant")
- @Produces({ "application/xml", "application/json" })
- public VXPolicy grantPermission(@Context HttpServletRequest request,VXPolicy vXPolicy) {
- boolean httpEnabled = PropertiesUtil.getBooleanProperty("http.enabled",true);
- X509Certificate[] certchain = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
- String ipAddress = request.getHeader("X-FORWARDED-FOR");
- if (ipAddress == null) {
- ipAddress = request.getRemoteAddr();
- }
- boolean isSecure = request.isSecure();
- String repository=null;
- if(vXPolicy!=null){
- repository=vXPolicy.getRepositoryName();
- vXPolicy.setOwner(vXPolicy.getGrantor());
- vXPolicy.setUpdatedBy(vXPolicy.getGrantor());
- }
- boolean isValidAuthentication=assetMgr.isValidHttpsAuthentication(repository,certchain,httpEnabled,ipAddress,isSecure);
- if(isValidAuthentication){
- VXResource vXResource = xPolicyService.mapPublicToXAObject(vXPolicy,AbstractBaseResourceService.OPERATION_CREATE_CONTEXT);
- vXResource=assetMgr.grantXResource(vXResource,vXPolicy);
- vXResource.setPermMapList(xPolicyService.updatePermGroup(vXResource));
- xResourceService.updateResource(vXResource);
- vXPolicy=xPolicyService.mapXAToPublicObject(vXResource);
- vXPolicy.syncResponseWithJsonRequest();
- }
- return vXPolicy;
- }
-
- @POST
- @Path("/resources/revoke")
- @Produces({ "application/xml", "application/json" })
- public VXPolicy revokePermission(@Context HttpServletRequest request,VXPolicy vXPolicy) {
- boolean httpEnabled = PropertiesUtil.getBooleanProperty("http.enabled",true);
- X509Certificate[] certchain = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
- String ipAddress = request.getHeader("X-FORWARDED-FOR");
- if (ipAddress == null) {
- ipAddress = request.getRemoteAddr();
- }
- boolean isSecure = request.isSecure();
- String repository=null;
- if(vXPolicy!=null){
- repository=vXPolicy.getRepositoryName();
- vXPolicy.setOwner(vXPolicy.getGrantor());
- vXPolicy.setUpdatedBy(vXPolicy.getGrantor());
- }
- boolean isValidAuthentication=assetMgr.isValidHttpsAuthentication(repository,certchain,httpEnabled,ipAddress,isSecure);
- if(isValidAuthentication){
- VXResource vXResource = xPolicyService.mapPublicToXAObject(vXPolicy,AbstractBaseResourceService.OPERATION_CREATE_CONTEXT);
- vXResource=assetMgr.revokeXResource(vXResource);
- vXResource.setPermMapList(xPolicyService.updatePermGroup(vXResource));
- xResourceService.updateResource(vXResource);
- vXPolicy=xPolicyService.mapXAToPublicObject(vXResource);
- vXPolicy.syncResponseWithJsonRequest();
- }
- return vXPolicy;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/rest/PublicAPIs.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/rest/PublicAPIs.java b/security-admin/src/main/java/com/xasecure/rest/PublicAPIs.java
deleted file mode 100644
index 15e3ad8..0000000
--- a/security-admin/src/main/java/com/xasecure/rest/PublicAPIs.java
+++ /dev/null
@@ -1,319 +0,0 @@
-/*
- * 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 com.xasecure.rest;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Scope;
-import org.springframework.security.access.prepost.PreAuthorize;
-import org.springframework.stereotype.Component;
-import org.springframework.transaction.annotation.Propagation;
-import org.springframework.transaction.annotation.Transactional;
-
-import com.xasecure.biz.AssetMgr;
-import com.xasecure.common.AppConstants;
-import com.xasecure.common.MessageEnums;
-import com.xasecure.common.RESTErrorUtil;
-import com.xasecure.common.SearchCriteria;
-import com.xasecure.common.StringUtil;
-import com.xasecure.common.XACommonEnums;
-import com.xasecure.common.XAConstants;
-import com.xasecure.common.XASearchUtil;
-import com.xasecure.common.annotation.XAAnnotationClassName;
-import com.xasecure.common.annotation.XAAnnotationJSMgrName;
-import com.xasecure.db.XADaoManager;
-import com.xasecure.service.AbstractBaseResourceService;
-import com.xasecure.service.XPolicyService;
-import com.xasecure.service.XRepositoryService;
-import com.xasecure.service.XAssetService;
-import com.xasecure.service.XResourceService;
-import com.xasecure.view.VXAsset;
-import com.xasecure.view.VXAssetList;
-import com.xasecure.view.VXLong;
-import com.xasecure.view.VXPolicy;
-import com.xasecure.view.VXPolicyList;
-import com.xasecure.view.VXRepository;
-import com.xasecure.view.VXRepositoryList;
-import com.xasecure.view.VXResource;
-import com.xasecure.view.VXResourceList;
-import com.xasecure.view.VXResponse;
-
-@Path("public")
-@Component
-@Scope("request")
-@XAAnnotationJSMgrName("PublicMgr")
-@Transactional(propagation = Propagation.REQUIRES_NEW)
-public class PublicAPIs {
- static Logger logger = Logger.getLogger(PublicAPIs.class);
-
- @Autowired
- XASearchUtil searchUtil;
-
- @Autowired
- AssetMgr assetMgr;
-
- @Autowired
- XAssetService xAssetService;
-
- @Autowired
- RESTErrorUtil restErrorUtil;
-
- @Autowired
- XRepositoryService xRepositoryService;
-
- @Autowired
- XResourceService xResourceService;
-
- @Autowired
- XPolicyService xPolicyService;
-
- @Autowired
- StringUtil stringUtil;
-
- @Autowired
- XADaoManager xaDaoMgr;
-
- @GET
- @Path("/api/repository/{id}")
- @Produces({ "application/json", "application/xml" })
- public VXRepository getRepository(@PathParam("id") Long id) {
- VXAsset vXAsset = assetMgr.getXAsset(id);
- return xRepositoryService.mapXAToPublicObject(vXAsset);
- }
-
- @POST
- @Path("/api/repository/")
- @Produces({ "application/json", "application/xml" })
- public VXRepository createRepository(VXRepository vXRepository) {
- VXAsset vXAsset = xRepositoryService.mapPublicToXAObject(vXRepository);
- vXAsset = assetMgr.createXAsset(vXAsset);
- return xRepositoryService.mapXAToPublicObject(vXAsset);
- }
-
- @PUT
- @Path("/api/repository/{id}")
- @Produces({ "application/json", "application/xml" })
- public VXRepository updateRepository(VXRepository vXRepository,
- @PathParam("id") Long id) {
- vXRepository.setId(id);
- VXAsset vXAsset = xRepositoryService.mapPublicToXAObject(vXRepository);
- vXAsset = assetMgr.updateXAsset(vXAsset);
- return xRepositoryService.mapXAToPublicObject(vXAsset);
- }
-
- @DELETE
- @Path("/api/repository/{id}")
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
- @XAAnnotationClassName(class_name = VXAsset.class)
- public void deleteRepository(@PathParam("id") Long id,
- @Context HttpServletRequest request) {
-
- String forceStr = request.getParameter("force");
- boolean force = true;
- if (!stringUtil.isEmpty(forceStr)) {
- force = Boolean.parseBoolean(forceStr.trim());
- }
- assetMgr.deleteXAsset(id, force);
- }
-
- // @POST
- // @Path("/api/repository/testConfig")
- // @Produces({ "application/xml", "application/json" })
- public VXResponse testConfig(VXRepository vXRepository) {
- VXAsset vXAsset = xRepositoryService.mapPublicToXAObject(vXRepository);
- return assetMgr.testConfig(vXAsset);
- }
-
- @GET
- @Path("/api/repository/")
- @Produces({ "application/json", "application/xml" })
- public VXRepositoryList searchRepositories(
- @Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xAssetService.sortFields);
- searchUtil.extractString(request, searchCriteria, "name",
- "Repository Name", null);
- searchUtil.extractBoolean(request, searchCriteria, "status",
- "Activation Status");
- searchUtil.extractString(request, searchCriteria, "type",
- "Repository Type", null);
-
- searchCriteria = xRepositoryService.getMappedSearchParams(request,
- searchCriteria);
- VXAssetList vXAssetList = assetMgr.searchXAssets(searchCriteria);
-
- return xRepositoryService.mapToVXRepositoryList(vXAssetList);
- }
-
- @GET
- @Path("/api/repository/count")
- @Produces({ "application/json", "application/xml" })
- public VXLong countRepositories(@Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xAssetService.sortFields);
-
- ArrayList<Integer> valueList = new ArrayList<Integer>();
- valueList.add(XAConstants.STATUS_DISABLED);
- valueList.add(XAConstants.STATUS_ENABLED);
- searchCriteria.addParam("status", valueList);
-
- return assetMgr.getXAssetSearchCount(searchCriteria);
- }
-
- @GET
- @Path("/api/policy/{id}")
- @Produces({ "application/json", "application/xml" })
- public VXPolicy getPolicy(@PathParam("id") Long id) {
- VXResource vXResource = assetMgr.getXResource(id);
- return xPolicyService.mapXAToPublicObject(vXResource);
- }
-
- @POST
- @Path("/api/policy")
- @Produces({ "application/json", "application/xml" })
- public VXPolicy createPolicy(VXPolicy vXPolicy) {
- VXResource vXResource = xPolicyService.mapPublicToXAObject(vXPolicy,
- AbstractBaseResourceService.OPERATION_CREATE_CONTEXT);
- vXResource = assetMgr.createXResource(vXResource);
- vXResource.setPermMapList(xPolicyService.updatePermGroup(vXResource));
- return xPolicyService.mapXAToPublicObject(vXResource);
-
- }
-
- @PUT
- @Path("/api/policy/{id}")
- @Produces({ "application/json", "application/xml" })
- public VXPolicy updatePolicy(VXPolicy vXPolicy, @PathParam("id") Long id) {
- vXPolicy.setId(id);
- VXResource vXResource = xPolicyService.mapPublicToXAObject(vXPolicy,
- AbstractBaseResourceService.OPERATION_UPDATE_CONTEXT);
- vXResource = assetMgr.updateXResource(vXResource);
- vXResource.setPermMapList(xPolicyService.updatePermGroup(vXResource));
- return xPolicyService.mapXAToPublicObject(vXResource);
- }
-
- @DELETE
- @Path("/api/policy/{id}")
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
- @XAAnnotationClassName(class_name = VXResource.class)
- public void deletePolicy(@PathParam("id") Long id,
- @Context HttpServletRequest request) {
- String forceStr = request.getParameter("force");
- boolean force = true;
- if (!stringUtil.isEmpty(forceStr)) {
- force = Boolean.parseBoolean(forceStr.trim());
- }
- assetMgr.deleteXResource(id, force);
- }
-
- @GET
- @Path("/api/policy")
- @Produces({ "application/json", "application/xml" })
- public VXPolicyList searchPolicies(@Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xResourceService.sortFields);
-
- String resourceName = request.getParameter("resourceName");
- if (!stringUtil.isEmpty(resourceName)) {
- searchCriteria.getParamList().put("name", resourceName);
- }
- searchUtil.extractString(request, searchCriteria, "policyName",
- "Policy name", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "columns",
- "Column name", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "columnFamilies",
- "Column Family", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "tables", "Tables",
- StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "udfs", "UDFs",
- StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "databases",
- "Databases", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "groupName",
- "Group Name", StringUtil.VALIDATION_TEXT);
-
- String repositoryType = request.getParameter("repositoryType");
- if (!stringUtil.isEmpty(repositoryType)) {
- searchCriteria.getParamList().put("assetType",
- AppConstants.getEnumFor_AssetType(repositoryType));
- }
-
- String isRec = request.getParameter("isRecursive");
- if (isRec != null) {
- boolean isRecursiveBool = restErrorUtil.parseBoolean(isRec,
- "Invalid value for " + "isRecursive",
- MessageEnums.INVALID_INPUT_DATA, null, "isRecursive");
- int isRecursive = (isRecursiveBool == true) ? XAConstants.BOOL_TRUE
- : XAConstants.BOOL_FALSE;
- searchCriteria.getParamList().put("isRecursive", isRecursive);
- }
-
- searchUtil.extractString(request, searchCriteria, "userName",
- "User Name", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "repositoryName",
- "Repository Name", StringUtil.VALIDATION_TEXT);
-
- String resStatus = request.getParameter("isEnabled");
- List<Integer> resList = new ArrayList<Integer>();
- if (stringUtil.isEmpty(resStatus)) {
- resList.add(XACommonEnums.STATUS_ENABLED);
- resList.add(XACommonEnums.STATUS_DISABLED);
- } else {
- boolean policyStatus = restErrorUtil.parseBoolean(resStatus,
- "Invalid value for " + "isEnabled",
- MessageEnums.INVALID_INPUT_DATA, null, "isEnabled");
- int policyStat = (policyStatus) ? XACommonEnums.STATUS_ENABLED
- : XACommonEnums.STATUS_DISABLED;
- resList.add(policyStat);
- }
- searchCriteria.getParamList().put("resourceStatus", resList);
-
- searchCriteria.setDistinct(true);
-
- VXResourceList vXResourceList = assetMgr
- .searchXResources(searchCriteria);
- return xPolicyService.mapToVXPolicyList(vXResourceList);
- }
-
- @GET
- @Path("/api/policy/count")
- @Produces({ "application/xml", "application/json" })
- public VXLong countPolicies(@Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xResourceService.sortFields);
-
-
- return assetMgr.getXResourceSearchCount(searchCriteria);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/rest/UserREST.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/rest/UserREST.java b/security-admin/src/main/java/com/xasecure/rest/UserREST.java
deleted file mode 100644
index 3bc6fef..0000000
--- a/security-admin/src/main/java/com/xasecure/rest/UserREST.java
+++ /dev/null
@@ -1,332 +0,0 @@
-/*
- * 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 com.xasecure.rest;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Context;
-
-import com.xasecure.biz.UserMgr;
-import com.xasecure.common.XAConstants;
-import com.xasecure.common.XAConfigUtil;
-import com.xasecure.common.MessageEnums;
-import com.xasecure.common.RESTErrorUtil;
-import com.xasecure.common.SearchCriteria;
-import com.xasecure.common.SearchUtil;
-import com.xasecure.common.StringUtil;
-import com.xasecure.entity.XXPortalUser;
-import com.xasecure.view.VXPasswordChange;
-import com.xasecure.view.VXResponse;
-import com.xasecure.view.VXStringList;
-import com.xasecure.view.VXPortalUser;
-import com.xasecure.view.VXPortalUserList;
-import com.xasecure.util.XARestUtil;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Scope;
-import org.springframework.security.access.prepost.PreAuthorize;
-import org.springframework.stereotype.Component;
-import org.springframework.transaction.annotation.Propagation;
-import org.springframework.transaction.annotation.Transactional;
-
-import com.xasecure.common.annotation.XAAnnotationClassName;
-import com.xasecure.common.annotation.XAAnnotationJSMgrName;
-import com.xasecure.common.annotation.XAAnnotationRestAPI;
-import com.xasecure.db.XADaoManager;
-
-
-@Path("users")
-@Component
-@Scope("request")
-@XAAnnotationJSMgrName("UserMgr")
-@Transactional(propagation = Propagation.REQUIRES_NEW)
-public class UserREST {
- static Logger logger = Logger.getLogger(UserREST.class);
-
- @Autowired
- StringUtil stringUtil;
-
- @Autowired
- XADaoManager daoManager;
-
- @Autowired
- XAConfigUtil configUtil;
-
- @Autowired
- RESTErrorUtil restErrorUtil;
-
- @Autowired
- SearchUtil searchUtil;
-
- @Autowired
- UserMgr userManager;
-
- @Autowired
- XARestUtil msRestUtil;
-
- /**
- * Implements the traditional search functionalities for UserProfile
- *
- * @param request
- * @return
- */
- @GET
- @Produces({ "application/xml", "application/json" })
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
- public VXPortalUserList searchUsers(@Context HttpServletRequest request) {
- String[] approvedSortByParams = new String[] { "requestDate",
- "approvedDate", "activationDate", "emailAddress", "firstName",
- "lastName" };
- @SuppressWarnings("deprecation")
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, approvedSortByParams);
-
- // userId
- searchUtil.extractLong(request, searchCriteria, "userId", "User Id");
-
- // loginId
- searchUtil.extractString(request, searchCriteria, "loginId",
- "Login Id", null);
-
- // emailAddress
- searchUtil.extractString(request, searchCriteria, "emailAddress",
- "Email Address", null);
-
- // firstName
- searchUtil.extractString(request, searchCriteria, "firstName",
- "First Name", StringUtil.VALIDATION_NAME);
-
- // lastName
- searchUtil.extractString(request, searchCriteria, "lastName",
- "Last Name", StringUtil.VALIDATION_NAME);
-
- // status
- searchUtil.extractEnum(request, searchCriteria, "status", "Status",
- "statusList", XAConstants.ActivationStatus_MAX);
-
- // publicScreenName
- searchUtil.extractString(request, searchCriteria, "publicScreenName",
- "Public Screen Name", StringUtil.VALIDATION_NAME);
- // roles
- searchUtil.extractStringList(request, searchCriteria, "role", "Role",
- "roleList", configUtil.getRoles(), StringUtil.VALIDATION_NAME);
-
- return userManager.searchUsers(searchCriteria);
- }
-
- /**
- * Return the VUserProfile for the given userId
- *
- * @param userId
- * @return
- */
- @GET
- @Path("{userId}")
- @Produces({ "application/xml", "application/json" })
- public VXPortalUser getUserProfileForUser(@PathParam("userId") Long userId) {
- try {
- VXPortalUser userProfile = userManager.getUserProfile(userId);
- if (userProfile != null) {
- if (logger.isDebugEnabled()) {
- logger.debug("getUserProfile() Found User userId=" + userId);
- }
- } else {
- logger.debug("getUserProfile() Not found userId=" + userId);
- }
- return userProfile;
- } catch (Throwable t) {
- logger.error("getUserProfile() no user session. error="
- + t.toString());
- }
- return null;
- }
-
- @POST
- @Consumes({ "application/json", "application/xml" })
- @Produces({ "application/xml", "application/json" })
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
- public VXPortalUser create(VXPortalUser userProfile,
- @Context HttpServletRequest servletRequest) {
- logger.info("create:" + userProfile.getEmailAddress());
-
- return userManager.createUser(userProfile);
- }
-
- // API to add user with default account
- @POST
- @Path("/default")
- @Consumes({ "application/json", "application/xml" })
- @Produces({ "application/xml", "application/json" })
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
- public VXPortalUser createDefaultAccountUser(VXPortalUser userProfile,
- @Context HttpServletRequest servletRequest) {
- logger.info("create:" + userProfile.getEmailAddress());
- return userManager.createDefaultAccountUser(userProfile);
- }
-
-
- @PUT
- @Consumes({ "application/json", "application/xml" })
- @Produces({ "application/xml", "application/json" })
- @XAAnnotationRestAPI(updates_classes = "VUserProfile")
- public VXPortalUser update(VXPortalUser userProfile,
- @Context HttpServletRequest servletRequest) {
- logger.info("update:" + userProfile.getEmailAddress());
- XXPortalUser gjUser = daoManager.getXXPortalUser().getById(userProfile.getId());
- userManager.checkAccess(gjUser);
- if (gjUser != null) {
- msRestUtil.validateVUserProfileForUpdate(gjUser, userProfile);
- gjUser = userManager.updateUser(userProfile);
- return userManager.mapXXPortalUserVXPortalUser(gjUser);
- } else {
- logger.info("update(): Invalid userId provided: userId="
- + userProfile.getId());
- throw restErrorUtil.createRESTException("serverMsg.userRestUser",
- MessageEnums.DATA_NOT_FOUND, null, null,
- userProfile.toString());
- }
- }
-
- @PUT
- @Path("/{userId}/roles")
- @Produces({ "application/xml", "application/json" })
- public VXResponse setUserRoles(@PathParam("userId") Long userId,
- VXStringList roleList) {
- userManager.checkAccess(userId);
- userManager.setUserRoles(userId, roleList.getVXStrings());
- VXResponse response = new VXResponse();
- response.setStatusCode(VXResponse.STATUS_SUCCESS);
- return response;
- }
-
- /**
- * Deactivate the user
- *
- * @param userId
- * @return
- */
- @POST
- @Path("{userId}/deactivate")
- @Produces({ "application/xml", "application/json" })
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
- @XAAnnotationClassName(class_name = VXPortalUser.class)
- public VXPortalUser deactivateUser(@PathParam("userId") Long userId) {
- XXPortalUser gjUser = daoManager.getXXPortalUser().getById(userId);
- if (gjUser == null) {
- logger.info("update(): Invalid userId provided: userId=" + userId);
- throw restErrorUtil.createRESTException("serverMsg.userRestUser",
- MessageEnums.DATA_NOT_FOUND, null, null, "" + userId);
- }
- return userManager.deactivateUser(gjUser);
- }
-
- /**
- * This method returns the VUserProfile for the current session
- *
- * @param request
- * @return
- */
- @GET
- @Path("/profile")
- @Produces({ "application/xml", "application/json" })
- public VXPortalUser getUserProfile(@Context HttpServletRequest request) {
- try {
- logger.debug("getUserProfile(). httpSessionId="
- + request.getSession().getId());
- VXPortalUser userProfile = userManager.getUserProfileByLoginId();
- return userProfile;
- } catch (Throwable t) {
- logger.error(
- "getUserProfile() no user session. error=" + t.toString(),
- t);
- }
- return null;
- }
-
- @GET
- @Path("/firstnames")
- @Produces({ "application/xml", "application/json" })
- public String suggestUserFirstName(@QueryParam("letters") String letters,
- @Context HttpServletRequest req) {
- return null;
- }
-
- /**
- * @param userId
- * @param changePassword
- * @return
- */
- @POST
- @Path("{userId}/passwordchange")
- @Produces({ "application/xml", "application/json" })
- public VXResponse changePassword(@PathParam("userId") Long userId,
- VXPasswordChange changePassword) {
- logger.info("changePassword:" + userId);
-
- XXPortalUser gjUser = daoManager.getXXPortalUser().getById(userId);
- if (gjUser == null) {
- logger.warn("SECURITY:changePassword(): Invalid userId provided: userId="
- + userId);
- throw restErrorUtil.createRESTException("serverMsg.userRestUser",
- MessageEnums.DATA_NOT_FOUND, null, null, "" + userId);
- }
-
- userManager.checkAccess(gjUser);
- changePassword.setId(userId);
- VXResponse ret = userManager.changePassword(changePassword);
- return ret;
- }
-
- /**
- *
- * @param userId
- * @param changeEmail
- * @return
- */
- @POST
- @Path("{userId}/emailchange")
- @Produces({ "application/xml", "application/json" })
- public VXPortalUser changeEmailAddress(@PathParam("userId") Long userId,
- VXPasswordChange changeEmail) {
- logger.info("changeEmail:" + userId);
-
- XXPortalUser gjUser = daoManager.getXXPortalUser().getById(userId);
- if (gjUser == null) {
- logger.warn("SECURITY:changeEmail(): Invalid userId provided: userId="
- + userId);
- throw restErrorUtil.createRESTException("serverMsg.userRestUser",
- MessageEnums.DATA_NOT_FOUND, null, null, "" + userId);
- }
-
- userManager.checkAccess(gjUser);
- changeEmail.setId(userId);
- VXPortalUser ret = userManager.changeEmailAddress(gjUser, changeEmail);
- return ret;
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/rest/XAuditREST.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/rest/XAuditREST.java b/security-admin/src/main/java/com/xasecure/rest/XAuditREST.java
deleted file mode 100644
index 9afacba..0000000
--- a/security-admin/src/main/java/com/xasecure/rest/XAuditREST.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * 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 com.xasecure.rest;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.*;
-
-import com.xasecure.common.SearchCriteria;
-import com.xasecure.common.SearchUtil;
-import com.xasecure.service.*;
-import com.xasecure.biz.*;
-import com.xasecure.view.*;
-
-import com.xasecure.rest.*;
-import com.xasecure.biz.*;
-import com.xasecure.common.annotation.XAAnnotationClassName;
-import com.xasecure.common.annotation.XAAnnotationJSMgrName;
-import com.xasecure.view.*;
-import com.xasecure.service.*;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Scope;
-import org.springframework.security.access.prepost.PreAuthorize;
-import org.springframework.stereotype.Component;
-import org.springframework.transaction.annotation.Propagation;
-import org.springframework.transaction.annotation.Transactional;
-
-@Path("xaudit")
-@Component
-@Scope("request")
-@XAAnnotationJSMgrName("XAuditMgr")
-@Transactional(propagation = Propagation.REQUIRES_NEW)
-public class XAuditREST {
- static Logger logger = Logger.getLogger(XAuditREST.class);
-
- @Autowired
- SearchUtil searchUtil;
-
- @Autowired
- XAuditMgr xAuditMgr;
-
- @Autowired
- XTrxLogService xTrxLogService;
-
- @Autowired
- XAccessAuditService xAccessAuditService;
- // Handle XTrxLog
- @GET
- @Path("/trx_log/{id}")
- @Produces({ "application/xml", "application/json" })
- public VXTrxLog getXTrxLog(
- @PathParam("id") Long id) {
- return xAuditMgr.getXTrxLog(id);
- }
-
- @POST
- @Path("/trx_log")
- @Produces({ "application/xml", "application/json" })
- public VXTrxLog createXTrxLog(VXTrxLog vXTrxLog) {
- return xAuditMgr.createXTrxLog(vXTrxLog);
- }
-
- @PUT
- @Path("/trx_log")
- @Produces({ "application/xml", "application/json" })
- public VXTrxLog updateXTrxLog(VXTrxLog vXTrxLog) {
- return xAuditMgr.updateXTrxLog(vXTrxLog);
- }
-
- @DELETE
- @Path("/trx_log/{id}")
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
- @XAAnnotationClassName(class_name = VXTrxLog.class)
- public void deleteXTrxLog(@PathParam("id") Long id,
- @Context HttpServletRequest request) {
- boolean force = false;
- xAuditMgr.deleteXTrxLog(id, force);
- }
-
- /**
- * Implements the traditional search functionalities for XTrxLogs
- *
- * @param request
- * @return
- */
- @GET
- @Path("/trx_log")
- @Produces({ "application/xml", "application/json" })
- public VXTrxLogList searchXTrxLogs(@Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xTrxLogService.sortFields);
- return xAuditMgr.searchXTrxLogs(searchCriteria);
- }
-
- @GET
- @Path("/trx_log/count")
- @Produces({ "application/xml", "application/json" })
- public VXLong countXTrxLogs(@Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xTrxLogService.sortFields);
-
- return xAuditMgr.getXTrxLogSearchCount(searchCriteria);
- }
-
-
- /**
- * Implements the traditional search functionalities for XAccessAudits
- *
- * @param request
- * @return
- */
- @GET
- @Path("/access_audit")
- @Produces({ "application/xml", "application/json" })
- public VXAccessAuditList searchXAccessAudits(@Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xAccessAuditService.sortFields);
- return xAuditMgr.searchXAccessAudits(searchCriteria);
- }
-
- @GET
- @Path("/access_audit/count")
- @Produces({ "application/xml", "application/json" })
- public VXLong countXAccessAudits(@Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xAccessAuditService.sortFields);
-
- return xAuditMgr.getXAccessAuditSearchCount(searchCriteria);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/rest/XUserREST.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/rest/XUserREST.java b/security-admin/src/main/java/com/xasecure/rest/XUserREST.java
deleted file mode 100644
index 8a4f875..0000000
--- a/security-admin/src/main/java/com/xasecure/rest/XUserREST.java
+++ /dev/null
@@ -1,594 +0,0 @@
-/*
- * 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 com.xasecure.rest;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.*;
-
-import com.xasecure.biz.SessionMgr;
-import com.xasecure.common.XAConstants;
-import com.xasecure.common.DateUtil;
-import com.xasecure.common.RESTErrorUtil;
-import com.xasecure.common.SearchCriteria;
-import com.xasecure.common.SearchField;
-import com.xasecure.common.SearchUtil;
-import com.xasecure.common.StringUtil;
-import com.xasecure.entity.XXAuthSession;
-import com.xasecure.service.AuthSessionService;
-import com.xasecure.view.*;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Scope;
-import org.springframework.security.access.prepost.PreAuthorize;
-import org.springframework.stereotype.Component;
-import org.springframework.transaction.annotation.Propagation;
-import org.springframework.transaction.annotation.Transactional;
-
-import com.xasecure.biz.*;
-import com.xasecure.common.annotation.XAAnnotationClassName;
-import com.xasecure.common.annotation.XAAnnotationJSMgrName;
-import com.xasecure.db.XADaoManager;
-import com.xasecure.service.*;
-import com.xasecure.view.*;
-
-@Path("xusers")
-@Component
-@Scope("request")
-@XAAnnotationJSMgrName("XUserMgr")
-@Transactional(propagation = Propagation.REQUIRES_NEW)
-public class XUserREST {
- static Logger logger = Logger.getLogger(XUserREST.class);
-
- @Autowired
- SearchUtil searchUtil;
-
- @Autowired
- XUserMgr xUserMgr;
-
- @Autowired
- XGroupService xGroupService;
-
- @Autowired
- XUserService xUserService;
-
- @Autowired
- XGroupUserService xGroupUserService;
-
- @Autowired
- XGroupGroupService xGroupGroupService;
-
- @Autowired
- XPermMapService xPermMapService;
-
- @Autowired
- XAuditMapService xAuditMapService;
-
- @Autowired
- RESTErrorUtil restErrorUtil;
-
- @Autowired
- XADaoManager xADaoManager;
-
- @Autowired
- SessionMgr sessionMgr;
-
- @Autowired
- AuthSessionService authSessionService;
-
- // Handle XGroup
- @GET
- @Path("/groups/{id}")
- @Produces({ "application/xml", "application/json" })
- public VXGroup getXGroup(@PathParam("id") Long id) {
- return xUserMgr.getXGroup(id);
- }
-
- @GET
- @Path("/secure/groups/{id}")
- @Produces({ "application/xml", "application/json" })
- public VXGroup secureGetXGroup(@PathParam("id") Long id) {
- return xUserMgr.getXGroup(id);
- }
-
- @POST
- @Path("/groups")
- @Produces({ "application/xml", "application/json" })
- public VXGroup createXGroup(VXGroup vXGroup) {
- return xUserMgr.createXGroupWithoutLogin(vXGroup);
- }
-
- @POST
- @Path("/secure/groups")
- @Produces({ "application/xml", "application/json" })
- public VXGroup secureCreateXGroup(VXGroup vXGroup) {
- return xUserMgr.createXGroup(vXGroup);
- }
-
- @PUT
- @Path("/groups")
- @Produces({ "application/xml", "application/json" })
- public VXGroup updateXGroup(VXGroup vXGroup) {
- return xUserMgr.updateXGroup(vXGroup);
- }
-
- @PUT
- @Path("/secure/groups/{id}")
- @Produces({ "application/xml", "application/json" })
- public VXGroup secureUpdateXGroup(VXGroup vXGroup) {
- return xUserMgr.updateXGroup(vXGroup);
- }
-
-
- @DELETE
- @Path("/groups/{id}")
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
- @XAAnnotationClassName(class_name = VXGroup.class)
- public void deleteXGroup(@PathParam("id") Long id,
- @Context HttpServletRequest request) {
- boolean force = true;
- xUserMgr.deleteXGroup(id, force);
- }
-
- /**
- * Implements the traditional search functionalities for XGroups
- *
- * @param request
- * @return
- */
- @GET
- @Path("/groups")
- @Produces({ "application/xml", "application/json" })
- public VXGroupList searchXGroups(@Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xGroupService.sortFields);
- searchUtil.extractString(request, searchCriteria, "name", "group name",
- StringUtil.VALIDATION_NAME);
- searchUtil.extractString(request, searchCriteria, "groupSource", "group source",
- StringUtil.VALIDATION_NAME);
- return xUserMgr.searchXGroups(searchCriteria);
- }
-
- @GET
- @Path("/groups/count")
- @Produces({ "application/xml", "application/json" })
- public VXLong countXGroups(@Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xGroupService.sortFields);
-
- return xUserMgr.getXGroupSearchCount(searchCriteria);
- }
-
- // Handle XUser
- @GET
- @Path("/users/{id}")
- @Produces({ "application/xml", "application/json" })
- public VXUser getXUser(@PathParam("id") Long id) {
- return xUserMgr.getXUser(id);
- }
-
- @GET
- @Path("/secure/users/{id}")
- @Produces({ "application/xml", "application/json" })
- public VXUser secureGetXUser(@PathParam("id") Long id) {
- return xUserMgr.getXUser(id);
- }
-
- @POST
- @Path("/users")
- @Produces({ "application/xml", "application/json" })
- public VXUser createXUser(VXUser vXUser) {
- return xUserMgr.createXUserWithOutLogin(vXUser);
- }
-
- @POST
- @Path("/secure/users")
- @Produces({ "application/xml", "application/json" })
- public VXUser secureCreateXUser(VXUser vXUser) {
- return xUserMgr.createXUser(vXUser);
- }
-
- @PUT
- @Path("/users")
- @Produces({ "application/xml", "application/json" })
- public VXUser updateXUser(VXUser vXUser) {
- return xUserMgr.updateXUser(vXUser);
- }
-
- @PUT
- @Path("/secure/users/{id}")
- @Produces({ "application/xml", "application/json" })
- public VXUser secureUpdateXUser(VXUser vXUser) {
- return xUserMgr.updateXUser(vXUser);
- }
-
- @DELETE
- @Path("/users/{id}")
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
- @XAAnnotationClassName(class_name = VXUser.class)
- public void deleteXUser(@PathParam("id") Long id,
- @Context HttpServletRequest request) {
- boolean force = true;
- xUserMgr.deleteXUser(id, force);
- }
-
- /**
- * Implements the traditional search functionalities for XUsers
- *
- * @param request
- * @return
- */
- @GET
- @Path("/users")
- @Produces({ "application/xml", "application/json" })
- public VXUserList searchXUsers(@Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xUserService.sortFields);
-
- searchUtil.extractString(request, searchCriteria, "name", "User name",
- StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "emailAddress", "Email Address",
- null);
- searchUtil.extractInt(request, searchCriteria, "userSource", "User Source");
- searchUtil.extractString(request, searchCriteria, "userRoleList", "User Role",
- null);
- return xUserMgr.searchXUsers(searchCriteria);
- }
-
- @GET
- @Path("/users/count")
- @Produces({ "application/xml", "application/json" })
- public VXLong countXUsers(@Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xUserService.sortFields);
-
- return xUserMgr.getXUserSearchCount(searchCriteria);
- }
-
- // Handle XGroupUser
- @GET
- @Path("/groupusers/{id}")
- @Produces({ "application/xml", "application/json" })
- public VXGroupUser getXGroupUser(@PathParam("id") Long id) {
- return xUserMgr.getXGroupUser(id);
- }
-
- @POST
- @Path("/groupusers")
- @Produces({ "application/xml", "application/json" })
- public VXGroupUser createXGroupUser(VXGroupUser vXGroupUser) {
- return xUserMgr.createXGroupUser(vXGroupUser);
- }
-
- @PUT
- @Path("/groupusers")
- @Produces({ "application/xml", "application/json" })
- public VXGroupUser updateXGroupUser(VXGroupUser vXGroupUser) {
- return xUserMgr.updateXGroupUser(vXGroupUser);
- }
-
- @DELETE
- @Path("/groupusers/{id}")
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
- @XAAnnotationClassName(class_name = VXGroupUser.class)
- public void deleteXGroupUser(@PathParam("id") Long id,
- @Context HttpServletRequest request) {
- boolean force = true;
- xUserMgr.deleteXGroupUser(id, force);
- }
-
- /**
- * Implements the traditional search functionalities for XGroupUsers
- *
- * @param request
- * @return
- */
- @GET
- @Path("/groupusers")
- @Produces({ "application/xml", "application/json" })
- public VXGroupUserList searchXGroupUsers(@Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xGroupUserService.sortFields);
- return xUserMgr.searchXGroupUsers(searchCriteria);
- }
-
- @GET
- @Path("/groupusers/count")
- @Produces({ "application/xml", "application/json" })
- public VXLong countXGroupUsers(@Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xGroupUserService.sortFields);
-
- return xUserMgr.getXGroupUserSearchCount(searchCriteria);
- }
-
- // Handle XGroupGroup
- @GET
- @Path("/groupgroups/{id}")
- @Produces({ "application/xml", "application/json" })
- public VXGroupGroup getXGroupGroup(@PathParam("id") Long id) {
- return xUserMgr.getXGroupGroup(id);
- }
-
- @POST
- @Path("/groupgroups")
- @Produces({ "application/xml", "application/json" })
- public VXGroupGroup createXGroupGroup(VXGroupGroup vXGroupGroup) {
- return xUserMgr.createXGroupGroup(vXGroupGroup);
- }
-
- @PUT
- @Path("/groupgroups")
- @Produces({ "application/xml", "application/json" })
- public VXGroupGroup updateXGroupGroup(VXGroupGroup vXGroupGroup) {
- return xUserMgr.updateXGroupGroup(vXGroupGroup);
- }
-
- @DELETE
- @Path("/groupgroups/{id}")
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
- @XAAnnotationClassName(class_name = VXGroupGroup.class)
- public void deleteXGroupGroup(@PathParam("id") Long id,
- @Context HttpServletRequest request) {
- boolean force = false;
- xUserMgr.deleteXGroupGroup(id, force);
- }
-
- /**
- * Implements the traditional search functionalities for XGroupGroups
- *
- * @param request
- * @return
- */
- @GET
- @Path("/groupgroups")
- @Produces({ "application/xml", "application/json" })
- public VXGroupGroupList searchXGroupGroups(
- @Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xGroupGroupService.sortFields);
- return xUserMgr.searchXGroupGroups(searchCriteria);
- }
-
- @GET
- @Path("/groupgroups/count")
- @Produces({ "application/xml", "application/json" })
- public VXLong countXGroupGroups(@Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xGroupGroupService.sortFields);
-
- return xUserMgr.getXGroupGroupSearchCount(searchCriteria);
- }
-
- // Handle XPermMap
- @GET
- @Path("/permmaps/{id}")
- @Produces({ "application/xml", "application/json" })
- public VXPermMap getXPermMap(@PathParam("id") Long id) {
- return xUserMgr.getXPermMap(id);
- }
-
- @POST
- @Path("/permmaps")
- @Produces({ "application/xml", "application/json" })
- public VXPermMap createXPermMap(VXPermMap vXPermMap) {
- return xUserMgr.createXPermMap(vXPermMap);
- }
-
- @PUT
- @Path("/permmaps")
- @Produces({ "application/xml", "application/json" })
- public VXPermMap updateXPermMap(VXPermMap vXPermMap) {
- return xUserMgr.updateXPermMap(vXPermMap);
- }
-
- @DELETE
- @Path("/permmaps/{id}")
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
- @XAAnnotationClassName(class_name = VXPermMap.class)
- public void deleteXPermMap(@PathParam("id") Long id,
- @Context HttpServletRequest request) {
- boolean force = false;
- xUserMgr.deleteXPermMap(id, force);
- }
-
- /**
- * Implements the traditional search functionalities for XPermMaps
- *
- * @param request
- * @return
- */
- @GET
- @Path("/permmaps")
- @Produces({ "application/xml", "application/json" })
- public VXPermMapList searchXPermMaps(@Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xPermMapService.sortFields);
- return xUserMgr.searchXPermMaps(searchCriteria);
- }
-
- @GET
- @Path("/permmaps/count")
- @Produces({ "application/xml", "application/json" })
- public VXLong countXPermMaps(@Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xPermMapService.sortFields);
-
- return xUserMgr.getXPermMapSearchCount(searchCriteria);
- }
-
- // Handle XAuditMap
- @GET
- @Path("/auditmaps/{id}")
- @Produces({ "application/xml", "application/json" })
- public VXAuditMap getXAuditMap(@PathParam("id") Long id) {
- return xUserMgr.getXAuditMap(id);
- }
-
- @POST
- @Path("/auditmaps")
- @Produces({ "application/xml", "application/json" })
- public VXAuditMap createXAuditMap(VXAuditMap vXAuditMap) {
- return xUserMgr.createXAuditMap(vXAuditMap);
- }
-
- @PUT
- @Path("/auditmaps")
- @Produces({ "application/xml", "application/json" })
- public VXAuditMap updateXAuditMap(VXAuditMap vXAuditMap) {
- return xUserMgr.updateXAuditMap(vXAuditMap);
- }
-
- @DELETE
- @Path("/auditmaps/{id}")
- @PreAuthorize("hasRole('ROLE_SYS_ADMIN')")
- @XAAnnotationClassName(class_name = VXAuditMap.class)
- public void deleteXAuditMap(@PathParam("id") Long id,
- @Context HttpServletRequest request) {
- boolean force = false;
- xUserMgr.deleteXAuditMap(id, force);
- }
-
- /**
- * Implements the traditional search functionalities for XAuditMaps
- *
- * @param request
- * @return
- */
- @GET
- @Path("/auditmaps")
- @Produces({ "application/xml", "application/json" })
- public VXAuditMapList searchXAuditMaps(@Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xAuditMapService.sortFields);
- return xUserMgr.searchXAuditMaps(searchCriteria);
- }
-
- @GET
- @Path("/auditmaps/count")
- @Produces({ "application/xml", "application/json" })
- public VXLong countXAuditMaps(@Context HttpServletRequest request) {
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, xAuditMapService.sortFields);
-
- return xUserMgr.getXAuditMapSearchCount(searchCriteria);
- }
-
- // Handle XUser
- @GET
- @Path("/users/userName/{userName}")
- @Produces({ "application/xml", "application/json" })
- public VXUser getXUserByUserName(@Context HttpServletRequest request,
- @PathParam("userName") String userName) {
- return xUserMgr.getXUserByUserName(userName);
- }
-
- @GET
- @Path("/groups/groupName/{groupName}")
- @Produces({ "application/xml", "application/json" })
- public VXGroup getXGroupByGroupName(@Context HttpServletRequest request,
- @PathParam("groupName") String groupName) {
- return xGroupService.getGroupByGroupName(groupName);
- }
-
- @DELETE
- @Path("/users/userName/{userName}")
- public void deleteXUserByUserName(@PathParam("userName") String userName,
- @Context HttpServletRequest request) {
- boolean force = true;
- VXUser vxUser = xUserService.getXUserByUserName(userName);
- xUserMgr.deleteXUser(vxUser.getId(), force);
- }
-
- @DELETE
- @Path("/groups/groupName/{groupName}")
- public void deleteXGroupByGroupName(
- @PathParam("groupName") String groupName,
- @Context HttpServletRequest request) {
- boolean force = true;
- VXGroup vxGroup = xGroupService.getGroupByGroupName(groupName);
- xUserMgr.deleteXGroup(vxGroup.getId(), force);
- }
-
- // @POST
- // @Path("/group/{groupName}/user/{userName}")
- // @Produces({ "application/xml", "application/json" })
- // public void createXGroupAndXUser(@PathParam("groupName") String
- // groupName,
- // @PathParam("userName") String userName,
- // @Context HttpServletRequest request) {
- // xUserMgr.createXGroupAndXUser(groupName, userName);
- // }
- //
- @DELETE
- @Path("/group/{groupName}/user/{userName}")
- public void deleteXGroupAndXUser(@PathParam("groupName") String groupName,
- @PathParam("userName") String userName,
- @Context HttpServletRequest request) {
- xUserMgr.deleteXGroupAndXUser(groupName, userName);
- }
-
- @GET
- @Path("/{userId}/groups")
- @Produces({ "application/xml", "application/json" })
- public VXGroupList getXUserGroups(@Context HttpServletRequest request,
- @PathParam("userId") Long id){
- return xUserMgr.getXUserGroups(id);
- }
-
- @GET
- @Path("/{groupId}/users")
- @Produces({ "application/xml", "application/json" })
- public VXUserList getXGroupUsers(@Context HttpServletRequest request,
- @PathParam("groupId") Long id){
- return xUserMgr.getXGroupUsers(id);
- }
-
- @GET
- @Path("/authSessions")
- @Produces({ "application/xml", "application/json" })
- public VXAuthSessionList getAuthSessions(@Context HttpServletRequest request){
- SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(
- request, authSessionService.AUTH_SESSION_SORT_FLDS);
- searchUtil.extractLong(request, searchCriteria, "id", "Auth Session Id");
- searchUtil.extractLong(request, searchCriteria, "userId", "User Id");
- searchUtil.extractInt(request, searchCriteria, "authStatus", "Auth Status");
- searchUtil.extractInt(request, searchCriteria, "authType", "Auth Type");
- searchUtil.extractInt(request, searchCriteria, "deviceType", "Device Type");
- searchUtil.extractString(request, searchCriteria, "firstName", "User First Name", StringUtil.VALIDATION_NAME);
- searchUtil.extractString(request, searchCriteria, "lastName", "User Last Name", StringUtil.VALIDATION_NAME);
- searchUtil.extractString(request, searchCriteria, "requestUserAgent", "User Agent", StringUtil.VALIDATION_TEXT);
- searchUtil.extractString(request, searchCriteria, "requestIP", "Request IP Address", StringUtil.VALIDATION_IP_ADDRESS);
- searchUtil.extractString(request, searchCriteria, "loginId", "Login ID", StringUtil.VALIDATION_TEXT);
- searchUtil.extractDate(request, searchCriteria, "startDate", "Start date for search", null);
- searchUtil.extractDate(request, searchCriteria, "endDate", "End date for search", null);
- return sessionMgr.searchAuthSessions(searchCriteria);
- }
-
- @GET
- @Path("/authSessions/info")
- @Produces({ "application/xml", "application/json" })
- public VXAuthSession getAuthSession(@Context HttpServletRequest request){
- String authSessionId = request.getParameter("extSessionId");
- return sessionMgr.getAuthSessionBySessionId(authSessionId);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/security/context/XAContextHolder.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/security/context/XAContextHolder.java b/security-admin/src/main/java/com/xasecure/security/context/XAContextHolder.java
deleted file mode 100644
index 8671a13..0000000
--- a/security-admin/src/main/java/com/xasecure/security/context/XAContextHolder.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * 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 com.xasecure.security.context;
-
-public class XAContextHolder {
-
- private static final ThreadLocal<XASecurityContext> securityContextThreadLocal = new ThreadLocal<XASecurityContext>();
-
- private XAContextHolder() {
-
- }
-
- public static XASecurityContext getSecurityContext(){
- return securityContextThreadLocal.get();
- }
-
- public static void setSecurityContext(XASecurityContext context){
- securityContextThreadLocal.set(context);
- }
-
- public static void resetSecurityContext(){
- securityContextThreadLocal.remove();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/security/context/XASecurityContext.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/security/context/XASecurityContext.java b/security-admin/src/main/java/com/xasecure/security/context/XASecurityContext.java
deleted file mode 100644
index 5cd8d5d..0000000
--- a/security-admin/src/main/java/com/xasecure/security/context/XASecurityContext.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * 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 com.xasecure.security.context;
-
-import java.io.Serializable;
-
-import com.xasecure.common.RequestContext;
-import com.xasecure.common.UserSessionBase;
-
-public class XASecurityContext implements Serializable{
- private static final long serialVersionUID = 1L;
- private UserSessionBase userSession;
- private RequestContext requestContext;
-
- public UserSessionBase getUserSession() {
- return userSession;
- }
-
- public void setUserSession(UserSessionBase userSession) {
- this.userSession = userSession;
- }
-
- /**
- * @return the requestContext
- */
- public RequestContext getRequestContext() {
- return requestContext;
- }
-
- /**
- * @param requestContext the requestContext to set
- */
- public void setRequestContext(RequestContext requestContext) {
- this.requestContext = requestContext;
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/security/handler/Permission.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/security/handler/Permission.java b/security-admin/src/main/java/com/xasecure/security/handler/Permission.java
deleted file mode 100644
index f9ab946..0000000
--- a/security-admin/src/main/java/com/xasecure/security/handler/Permission.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * 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 com.xasecure.security.handler;
-public class Permission {
-
- public static final String CREATE_PERMISSION = "CREATE";
- public static final String READ_PERMISSION = "READ";
- public static final String UPDATE_PERMISSION = "UPDATE";
- public static final String DELETE_PERMISSION = "DELETE";
-
- public enum permissionType {
- CREATE, READ, UPDATE, DELETE
- };
-
- public static permissionType getPermisson(Object in) {
- String permString = in.toString();
-
- if (CREATE_PERMISSION.equals(permString)) {
- return permissionType.CREATE;
- }
-
- if (READ_PERMISSION.equals(permString)) {
- return permissionType.READ;
- }
-
- if (UPDATE_PERMISSION.equals(permString)) {
- return permissionType.UPDATE;
- }
-
- if (DELETE_PERMISSION.equals(permString)) {
- return permissionType.DELETE;
- }
-
- return null;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/security/handler/XADomainObjectSecurityHandler.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/security/handler/XADomainObjectSecurityHandler.java b/security-admin/src/main/java/com/xasecure/security/handler/XADomainObjectSecurityHandler.java
deleted file mode 100644
index 97a8733..0000000
--- a/security-admin/src/main/java/com/xasecure/security/handler/XADomainObjectSecurityHandler.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * 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 com.xasecure.security.handler;
-
-/**
- *
- */
-
-import java.io.Serializable;
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import com.xasecure.biz.XABizUtil;
-import com.xasecure.common.ContextUtil;
-import com.xasecure.common.PropertiesUtil;
-import com.xasecure.common.UserSessionBase;
-import com.xasecure.db.XADaoManager;
-import com.xasecure.entity.XXDBBase;
-
-@Component
-public class XADomainObjectSecurityHandler {
-
- public static Logger logger = Logger
- .getLogger(XADomainObjectSecurityHandler.class);
-
- @Autowired
- public XADaoManager daoManager;
-
- @Autowired
- XABizUtil msBizUtil;
-
- boolean checkParentObject = false;
-
- public XADomainObjectSecurityHandler() {
- checkParentObject = PropertiesUtil.getBooleanProperty(
- "xa.db.access.filter.check.parentobject", checkParentObject);
- }
-
- /**
- * @return the daoManager
- */
- public XADaoManager getDaoManager() {
- return daoManager;
- }
-
- public <T extends XXDBBase> boolean hasAccess(T targetDomainObject,
- Permission.permissionType permission) {
- //TODO: Need to review this method and reimplement it properly
- return true;
- }
-
- public boolean hasAccess(String targetType, Serializable targetId,
- Permission.permissionType permission) {
- try {
- Class<?> clazz = Class.forName(targetType);
- Class<? extends XXDBBase> gjClazz = clazz.asSubclass(XXDBBase.class);
- return hasAccess(gjClazz, targetId, permission);
-
- } catch (ClassNotFoundException cfe) {
- logger.error("class not found:" + targetType, cfe);
- } catch (Exception e) {
- logger.error("Excepion targetType:" + targetType + " targetId:"
- + targetId, e);
- }
-
- return false;
- }
-
- public boolean hasAccess(Class<? extends XXDBBase> targetClass,
- Serializable targetId, Permission.permissionType permission) {
- try {
- Class<? extends XXDBBase> gjClazz = targetClass
- .asSubclass(XXDBBase.class);
- XXDBBase base = getDaoManager().getEntityManager().find(gjClazz,
- targetId);
- return hasAccess(base, permission);
-
- } catch (Exception e) {
- logger.error("Excepion targetType:" + targetClass + " targetId:"
- + targetId, e);
- }
-
- return false;
- }
-
- public boolean hasModeratorPermission() {
- UserSessionBase sess = ContextUtil.getCurrentUserSession();
- if (sess != null && sess.isUserAdmin()) {
- return true;
- }
- return false;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/security/listener/SpringEventListener.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/security/listener/SpringEventListener.java b/security-admin/src/main/java/com/xasecure/security/listener/SpringEventListener.java
deleted file mode 100644
index 5796eff..0000000
--- a/security-admin/src/main/java/com/xasecure/security/listener/SpringEventListener.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * 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 com.xasecure.security.listener;
-
-import com.xasecure.biz.SessionMgr;
-import com.xasecure.entity.XXAuthSession;
-
-import org.apache.log4j.Logger;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.ApplicationListener;
-import org.springframework.security.authentication.event.AbstractAuthenticationEvent;
-import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
-import org.springframework.security.authentication.event.AuthenticationFailureDisabledEvent;
-import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.web.authentication.WebAuthenticationDetails;
-
-
-public class SpringEventListener implements
- ApplicationListener<AbstractAuthenticationEvent> {
-
- static Logger logger = Logger.getLogger(SpringEventListener.class);
-
- @Autowired
- SessionMgr sessionMgr;
-
- @Override
- public void onApplicationEvent(AbstractAuthenticationEvent event) {
- try {
- if (event instanceof AuthenticationSuccessEvent) {
- process((AuthenticationSuccessEvent) event);
- } else if (event instanceof AuthenticationFailureBadCredentialsEvent) {
- process((AuthenticationFailureBadCredentialsEvent) event);
- } else if (event instanceof AuthenticationFailureDisabledEvent) {
- process((AuthenticationFailureDisabledEvent) event);
- } else {
- // igonre all other events
- }
-
- } catch (Exception e) {
- logger.error("Exception in Spring Event Listener.", e);
- }
- }
-
- protected void process(AuthenticationSuccessEvent authSuccessEvent) {
- Authentication auth = authSuccessEvent.getAuthentication();
- WebAuthenticationDetails details = (WebAuthenticationDetails) auth
- .getDetails();
- String remoteAddress = details != null ? details.getRemoteAddress()
- : "";
- String sessionId = details != null ? details.getSessionId() : "";
-
- logger.info("Login Successful:" + auth.getName() + " | Ip Address:"
- + remoteAddress + " | sessionId=" + sessionId);
-
- // success logins are processed further in
- // AKASecurityContextFormationFilter
- }
-
- protected void process(
- AuthenticationFailureBadCredentialsEvent authFailEvent) {
- Authentication auth = authFailEvent.getAuthentication();
- WebAuthenticationDetails details = (WebAuthenticationDetails) auth
- .getDetails();
- String remoteAddress = details != null ? details.getRemoteAddress()
- : "";
- String sessionId = details != null ? details.getSessionId() : "";
-
- logger.info("Login Unsuccessful:" + auth.getName() + " | Ip Address:"
- + remoteAddress + " | Bad Credentials");
-
- sessionMgr.processFailureLogin(
- XXAuthSession.AUTH_STATUS_WRONG_PASSWORD,
- XXAuthSession.AUTH_TYPE_PASSWORD, auth.getName(),
- remoteAddress, sessionId);
- }
-
- protected void process(AuthenticationFailureDisabledEvent authFailEvent) {
- Authentication auth = authFailEvent.getAuthentication();
- WebAuthenticationDetails details = (WebAuthenticationDetails) auth
- .getDetails();
- String remoteAddress = details != null ? details.getRemoteAddress()
- : "";
- String sessionId = details != null ? details.getSessionId() : "";
-
- logger.info("Login Unsuccessful:" + auth.getName() + " | Ip Address:"
- + remoteAddress);
-
- sessionMgr.processFailureLogin(XXAuthSession.AUTH_STATUS_DISABLED,
- XXAuthSession.AUTH_TYPE_PASSWORD, auth.getName(),
- remoteAddress, sessionId);
-
- }
-
-}
[49/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/provider/LocalFileLogBuffer.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/provider/LocalFileLogBuffer.java b/agents-audit/src/main/java/com/xasecure/audit/provider/LocalFileLogBuffer.java
deleted file mode 100644
index b96d555..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/provider/LocalFileLogBuffer.java
+++ /dev/null
@@ -1,687 +0,0 @@
-/*
- * 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 com.xasecure.audit.provider;
-
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileFilter;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.UnsupportedEncodingException;
-import java.io.Writer;
-import java.security.PrivilegedAction;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.TreeSet;
-
-import org.apache.hadoop.security.UserGroupInformation;
-
-
-public class LocalFileLogBuffer<T> implements LogBuffer<T> {
- private String mDirectory = null;
- private String mFile = null;
- private int mFlushIntervalSeconds = 1 * 60;
- private int mFileBufferSizeBytes = 8 * 1024;
- private String mEncoding = null;
- private boolean mIsAppend = true;
- private int mRolloverIntervalSeconds = 10 * 60;
- private String mArchiveDirectory = null;
- private int mArchiveFileCount = 10;
- private DebugTracer mLogger = null;
-
- private Writer mWriter = null;
- private String mBufferFilename = null;
- private long mNextRolloverTime = 0;
- private long mNextFlushTime = 0;
- private int mFileOpenRetryIntervalInMs = 60 * 1000;
- private long mNextFileOpenRetryTime = 0;
-
- private DestinationDispatcherThread<T> mDispatcherThread = null;
-
- public LocalFileLogBuffer(DebugTracer tracer) {
- mLogger = tracer;
- }
-
- public String getDirectory() {
- return mDirectory;
- }
-
- public void setDirectory(String directory) {
- mDirectory = directory;
- }
-
- public String getFile() {
- return mFile;
- }
-
- public void setFile(String file) {
- mFile = file;
- }
-
- public int getFileBufferSizeBytes() {
- return mFileBufferSizeBytes;
- }
-
- public void setFileBufferSizeBytes(int fileBufferSizeBytes) {
- mFileBufferSizeBytes = fileBufferSizeBytes;
- }
-
- public int getFlushIntervalSeconds() {
- return mFlushIntervalSeconds;
- }
-
- public void setFlushIntervalSeconds(int flushIntervalSeconds) {
- mFlushIntervalSeconds = flushIntervalSeconds;
- }
-
- public String getEncoding() {
- return mEncoding;
- }
-
- public void setEncoding(String encoding) {
- mEncoding = encoding;
- }
-
- public boolean getIsAppend() {
- return mIsAppend;
- }
-
- public void setIsAppend(boolean isAppend) {
- mIsAppend = isAppend;
- }
-
- public int getRolloverIntervalSeconds() {
- return mRolloverIntervalSeconds;
- }
-
- public void setRolloverIntervalSeconds(int rolloverIntervalSeconds) {
- mRolloverIntervalSeconds = rolloverIntervalSeconds;
- }
-
- public String getArchiveDirectory() {
- return mArchiveDirectory;
- }
-
- public void setArchiveDirectory(String archiveDirectory) {
- mArchiveDirectory = archiveDirectory;
- }
-
- public int getArchiveFileCount() {
- return mArchiveFileCount;
- }
-
- public void setArchiveFileCount(int archiveFileCount) {
- mArchiveFileCount = archiveFileCount;
- }
-
-
- @Override
- public void start(LogDestination<T> destination) {
- mLogger.debug("==> LocalFileLogBuffer.start()");
-
- mDispatcherThread = new DestinationDispatcherThread<T>(this, destination, mLogger);
-
- mDispatcherThread.start();
-
- mLogger.debug("<== LocalFileLogBuffer.start()");
- }
-
- @Override
- public void stop() {
- mLogger.debug("==> LocalFileLogBuffer.stop()");
-
- DestinationDispatcherThread<T> dispatcherThread = mDispatcherThread;
- mDispatcherThread = null;
-
- if(dispatcherThread != null && dispatcherThread.isAlive()) {
- dispatcherThread.stopThread();
-
- try {
- dispatcherThread.join();
- } catch (InterruptedException e) {
- mLogger.warn("LocalFileLogBuffer.stop(): failed in waiting for DispatcherThread", e);
- }
- }
-
- closeFile();
-
- mLogger.debug("<== LocalFileLogBuffer.stop()");
- }
-
- @Override
- public boolean isAvailable() {
- return mWriter != null;
- }
-
- @Override
- public boolean add(T log) {
- boolean ret = false;
-
- String msg = MiscUtil.stringify(log);
-
- if(msg.contains(MiscUtil.LINE_SEPARATOR)) {
- msg = msg.replace(MiscUtil.LINE_SEPARATOR, MiscUtil.ESCAPE_STR + MiscUtil.LINE_SEPARATOR);
- }
-
- synchronized(this) {
- checkFileStatus();
-
- Writer writer = mWriter;
-
- if(writer != null) {
- try {
- writer.write(msg + MiscUtil.LINE_SEPARATOR);
-
- if(mFileBufferSizeBytes == 0) {
- writer.flush();
- }
-
- ret = true;
- } catch(IOException excp) {
- mLogger.warn("LocalFileLogBuffer.add(): write failed", excp);
-
- closeFile();
- }
- }
- }
-
- return ret;
- }
-
- @Override
- public boolean isEmpty() {
- return mDispatcherThread == null || mDispatcherThread.isIdle();
- }
-
- private synchronized void openFile() {
- mLogger.debug("==> LocalFileLogBuffer.openFile()");
-
- long now = System.currentTimeMillis();
-
- closeFile();
-
- if(mNextFileOpenRetryTime <= now) {
- try {
- mNextRolloverTime = MiscUtil.getNextRolloverTime(mNextRolloverTime, (mRolloverIntervalSeconds * 1000L));
-
- long startTime = MiscUtil.getRolloverStartTime(mNextRolloverTime, (mRolloverIntervalSeconds * 1000L));
-
- mBufferFilename = MiscUtil.replaceTokens(mDirectory + File.separator + mFile, startTime);
-
- MiscUtil.createParents(new File(mBufferFilename));
-
- FileOutputStream ostream = null;
- try {
- ostream = new FileOutputStream(mBufferFilename, mIsAppend);
- } catch(Exception excp) {
- mLogger.warn("LocalFileLogBuffer.openFile(): failed to open file " + mBufferFilename, excp);
- }
-
- if(ostream != null) {
- mWriter = createWriter(ostream);
-
- if(mWriter != null) {
- mLogger.debug("LocalFileLogBuffer.openFile(): opened file " + mBufferFilename);
-
- mNextFlushTime = System.currentTimeMillis() + (mFlushIntervalSeconds * 1000L);
- } else {
- mLogger.warn("LocalFileLogBuffer.openFile(): failed to open file for write " + mBufferFilename);
-
- mBufferFilename = null;
- }
- }
- } finally {
- if(mWriter == null) {
- mNextFileOpenRetryTime = now + mFileOpenRetryIntervalInMs;
- }
- }
- }
-
- mLogger.debug("<== LocalFileLogBuffer.openFile()");
- }
-
- private synchronized void closeFile() {
- mLogger.debug("==> LocalFileLogBuffer.closeFile()");
-
- Writer writer = mWriter;
-
- mWriter = null;
-
- if(writer != null) {
- try {
- writer.flush();
- writer.close();
- } catch(IOException excp) {
- mLogger.warn("LocalFileLogBuffer: failed to close file " + mBufferFilename, excp);
- }
-
- if(mDispatcherThread != null) {
- mDispatcherThread.addLogfile(mBufferFilename);
- }
- }
-
- mLogger.debug("<== LocalFileLogBuffer.closeFile()");
- }
-
- private void rollover() {
- mLogger.debug("==> LocalFileLogBuffer.rollover()");
-
- closeFile();
-
- openFile();
-
- mLogger.debug("<== LocalFileLogBuffer.rollover()");
- }
-
- private void checkFileStatus() {
- long now = System.currentTimeMillis();
-
- if(now > mNextRolloverTime) {
- rollover();
- } else if(mWriter == null) {
- openFile();
- } else if(now > mNextFlushTime) {
- try {
- mNextFlushTime = now + (mFlushIntervalSeconds * 1000L);
-
- mWriter.flush();
- } catch (IOException excp) {
- mLogger.warn("LocalFileLogBuffer: failed to flush to file " + mBufferFilename, excp);
- }
- }
- }
-
- private Writer createWriter(OutputStream os ) {
- Writer writer = null;
-
- if(os != null) {
- if(mEncoding != null) {
- try {
- writer = new OutputStreamWriter(os, mEncoding);
- } catch(UnsupportedEncodingException excp) {
- mLogger.warn("LocalFileLogBuffer: failed to create output writer for file " + mBufferFilename, excp);
- }
- }
-
- if(writer == null) {
- writer = new OutputStreamWriter(os);
- }
-
- if(mFileBufferSizeBytes > 0 && writer != null) {
- writer = new BufferedWriter(writer, mFileBufferSizeBytes);
- }
- }
-
- return writer;
- }
-
- boolean isCurrentFilename(String filename) {
- return mBufferFilename != null && filename != null && filename.equals(mBufferFilename);
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
-
- sb.append("LocalFileLogBuffer {");
- sb.append("Directory=").append(mDirectory).append("; ");
- sb.append("File=").append(mFile).append("; ");
- sb.append("RolloverIntervaSeconds=").append(mRolloverIntervalSeconds).append("; ");
- sb.append("ArchiveDirectory=").append(mArchiveDirectory).append("; ");
- sb.append("ArchiveFileCount=").append(mArchiveFileCount);
- sb.append("}");
-
- return sb.toString();
- }
-
-}
-
-class DestinationDispatcherThread<T> extends Thread {
- private TreeSet<String> mCompletedLogfiles = new TreeSet<String>();
- private boolean mStopThread = false;
- private LocalFileLogBuffer<T> mFileLogBuffer = null;
- private LogDestination<T> mDestination = null;
- private DebugTracer mLogger = null;
-
- private String mCurrentLogfile = null;
- private BufferedReader mReader = null;
-
- public DestinationDispatcherThread(LocalFileLogBuffer<T> fileLogBuffer, LogDestination<T> destination, DebugTracer tracer) {
- super(DestinationDispatcherThread.class.getSimpleName() + "-" + System.currentTimeMillis());
-
- mLogger = tracer;
-
- mFileLogBuffer = fileLogBuffer;
- mDestination = destination;
-
- setDaemon(true);
- }
-
- public void addLogfile(String filename) {
- mLogger.debug("==> DestinationDispatcherThread.addLogfile(" + filename + ")");
-
- if(filename != null) {
- synchronized(mCompletedLogfiles) {
- mCompletedLogfiles.add(filename);
- mCompletedLogfiles.notify();
- }
- }
-
- mLogger.debug("<== DestinationDispatcherThread.addLogfile(" + filename + ")");
- }
-
- public void stopThread() {
- mStopThread = true;
- }
-
- public boolean isIdle() {
- synchronized(mCompletedLogfiles) {
- return mCompletedLogfiles.isEmpty() && mCurrentLogfile == null;
- }
- }
-
- @Override
- public void run() {
- UserGroupInformation loginUser = null;
-
- try {
- loginUser = UserGroupInformation.getLoginUser();
- } catch (IOException excp) {
- mLogger.error("DestinationDispatcherThread.run(): failed to get login user details. Audit files will not be sent to HDFS destination", excp);
- }
-
- if(loginUser == null) {
- mLogger.error("DestinationDispatcherThread.run(): failed to get login user. Audit files will not be sent to HDFS destination");
-
- return;
- }
-
- loginUser.doAs(new PrivilegedAction<Integer>() {
- @Override
- public Integer run() {
- doRun();
-
- return 0;
- }
- });
- }
-
- private void doRun() {
- init();
-
- mDestination.start();
-
- long pollIntervalInMs = 1000L;
-
- while(! mStopThread) {
- synchronized(mCompletedLogfiles) {
- while(mCompletedLogfiles.isEmpty() && !mStopThread) {
- try {
- mCompletedLogfiles.wait(pollIntervalInMs);
- } catch(InterruptedException excp) {
- throw new RuntimeException("DestinationDispatcherThread.run(): failed to wait for log file", excp);
- }
- }
-
- mCurrentLogfile = mCompletedLogfiles.pollFirst();
- }
-
- if(mCurrentLogfile != null) {
- sendCurrentFile();
- }
- }
-
- mDestination.stop();
- }
-
- private void init() {
- mLogger.debug("==> DestinationDispatcherThread.init()");
-
- String dirName = MiscUtil.replaceTokens(mFileLogBuffer.getDirectory(), 0);
-
- if(dirName != null) {
- File directory = new File(dirName);
-
- if(directory.exists() && directory.isDirectory()) {
- File[] files = directory.listFiles();
-
- if(files != null) {
- for(File file : files) {
- if(file.exists() && file.isFile() && file.canRead()) {
- String filename = file.getAbsolutePath();
- if(! mFileLogBuffer.isCurrentFilename(filename)) {
- addLogfile(filename);
- }
- }
- }
- }
- }
- }
-
- mLogger.debug("<== DestinationDispatcherThread.init()");
- }
-
- private boolean sendCurrentFile() {
- mLogger.debug("==> DestinationDispatcherThread.sendCurrentFile()");
-
- boolean ret = false;
-
- long destinationPollIntervalInMs = 1000L;
-
- openCurrentFile();
-
- while(!mStopThread) {
- String log = getNextStringifiedLog();
-
- if(log == null) { // reached end-of-file
- ret = true;
-
- break;
- }
-
- // loop until log is sent successfully
- while(!mStopThread && !mDestination.sendStringified(log)) {
- try {
- Thread.sleep(destinationPollIntervalInMs);
- } catch(InterruptedException excp) {
- throw new RuntimeException("LocalFileLogBuffer.sendCurrentFile(" + mCurrentLogfile + "): failed while waiting for destination to be available", excp);
- }
- }
- }
-
- closeCurrentFile();
-
- if(!mStopThread) {
- mDestination.flush();
- archiveCurrentFile();
- }
-
- mLogger.debug("<== DestinationDispatcherThread.sendCurrentFile()");
-
- return ret;
- }
-
- private String getNextStringifiedLog() {
- String log = null;
-
- if(mReader != null) {
- try {
- while(true) {
- String line = mReader.readLine();
-
- if(line == null) { // reached end-of-file
- break;
- }
-
- if(line.endsWith(MiscUtil.ESCAPE_STR)) {
- line = line.substring(0, line.length() - MiscUtil.ESCAPE_STR.length());
-
- if(log == null) {
- log = line;
- } else {
- log += MiscUtil.LINE_SEPARATOR;
- log += line;
- }
-
- continue;
- } else {
- if(log == null) {
- log = line;
- } else {
- log += line;
- }
- break;
- }
- }
- } catch (IOException excp) {
- mLogger.warn("getNextStringifiedLog.getNextLog(): failed to read from file " + mCurrentLogfile, excp);
- }
- }
-
- return log;
- }
-
- private void openCurrentFile() {
- mLogger.debug("==> openCurrentFile(" + mCurrentLogfile + ")");
-
- if(mCurrentLogfile != null) {
- try {
- FileInputStream inStr = new FileInputStream(mCurrentLogfile);
-
- InputStreamReader strReader = createReader(inStr);
-
- if(strReader != null) {
- mReader = new BufferedReader(strReader);
- }
- } catch(FileNotFoundException excp) {
- mLogger.warn("openNextFile(): error while opening file " + mCurrentLogfile, excp);
- }
- }
-
- mLogger.debug("<== openCurrentFile(" + mCurrentLogfile + ")");
- }
-
- private void closeCurrentFile() {
- mLogger.debug("==> closeCurrentFile(" + mCurrentLogfile + ")");
-
- if(mReader != null) {
- try {
- mReader.close();
- } catch(IOException excp) {
- // ignore
- }
- }
- mReader = null;
-
- mLogger.debug("<== closeCurrentFile(" + mCurrentLogfile + ")");
- }
-
- private void archiveCurrentFile() {
- if(mCurrentLogfile != null) {
- File logFile = new File(mCurrentLogfile);
- String archiveDirName = MiscUtil.replaceTokens(mFileLogBuffer.getArchiveDirectory(), 0);
- String archiveFilename = archiveDirName + File.separator +logFile.getName();
-
- try {
- if(logFile.exists()) {
- File archiveFile = new File(archiveFilename);
-
- MiscUtil.createParents(archiveFile);
-
- if(! logFile.renameTo(archiveFile)) {
- // TODO: renameTo() does not work in all cases. in case of failure, copy the file contents to the destination and delete the file
- mLogger.warn("archiving failed to move file: " + mCurrentLogfile + " ==> " + archiveFilename);
- }
-
- File archiveDir = new File(archiveDirName);
- File[] files = archiveDir.listFiles(new FileFilter() {
- @Override
- public boolean accept(File f) {
- return f.isFile();
- }
- });
-
- int numOfFilesToDelete = files == null ? 0 : (files.length - mFileLogBuffer.getArchiveFileCount());
-
- if(numOfFilesToDelete > 0) {
- Arrays.sort(files, new Comparator<File>() {
- @Override
- public int compare(File f1, File f2) {
- return (int)(f1.lastModified() - f2.lastModified());
- }
- });
-
- for(int i = 0; i < numOfFilesToDelete; i++) {
- if(! files[i].delete()) {
- mLogger.warn("archiving failed to delete file: " + files[i].getAbsolutePath());
- }
- }
- }
- }
- } catch(Exception excp) {
- mLogger.warn("archiveCurrentFile(): faile to move " + mCurrentLogfile + " to archive location " + archiveFilename, excp);
- }
- }
- mCurrentLogfile = null;
- }
-
- public InputStreamReader createReader(InputStream iStr) {
- InputStreamReader reader = null;
-
- if(iStr != null) {
- String encoding = mFileLogBuffer.getEncoding();
-
- if(encoding != null) {
- try {
- reader = new InputStreamReader(iStr, encoding);
- } catch(UnsupportedEncodingException excp) {
- mLogger.warn("createReader(): failed to create input reader.", excp);
- }
- }
-
- if(reader == null) {
- reader = new InputStreamReader(iStr);
- }
- }
-
- return reader;
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
-
- sb.append("DestinationDispatcherThread {");
- sb.append("ThreadName=").append(this.getName()).append("; ");
- sb.append("CompletedLogfiles.size()=").append(mCompletedLogfiles.size()).append("; ");
- sb.append("StopThread=").append(mStopThread).append("; ");
- sb.append("CurrentLogfile=").append(mCurrentLogfile);
- sb.append("}");
-
- return sb.toString();
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/provider/Log4jAuditProvider.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/provider/Log4jAuditProvider.java b/agents-audit/src/main/java/com/xasecure/audit/provider/Log4jAuditProvider.java
deleted file mode 100644
index 65d5a6f..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/provider/Log4jAuditProvider.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/**
- * 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 com.xasecure.audit.provider;
-
-import java.util.Properties;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.xasecure.audit.model.AuditEventBase;
-
-
-public class Log4jAuditProvider extends BaseAuditProvider {
-
- private static final Log LOG = LogFactory.getLog(Log4jAuditProvider.class);
- private static final Log AUDITLOG = LogFactory.getLog("xaaudit." + Log4jAuditProvider.class.getName());
-
- public static final String AUDIT_LOG4J_IS_ASYNC_PROP = "xasecure.audit.log4j.is.async";
- public static final String AUDIT_LOG4J_MAX_QUEUE_SIZE_PROP = "xasecure.audit.log4j.async.max.queue.size" ;
- public static final String AUDIT_LOG4J_MAX_FLUSH_INTERVAL_PROP = "xasecure.audit.log4j.async.max.flush.interval.ms";
-
- private Gson mGsonBuilder = null;
-
- public Log4jAuditProvider() {
- LOG.info("Log4jAuditProvider: creating..");
- }
-
- @Override
- public void init(Properties props) {
- LOG.info("Log4jAuditProvider.init()");
-
- super.init(props);
-
- try {
- mGsonBuilder = new GsonBuilder().setDateFormat("yyyyMMdd-HH:mm:ss.SSS-Z").create();
- } catch(Throwable excp) {
- LOG.warn("Log4jAuditProvider.init(): failed to create GsonBuilder object. events will be formated using toString(), instead of Json", excp);
- }
- }
-
- @Override
- public void log(AuditEventBase event) {
- if(! AUDITLOG.isInfoEnabled())
- return;
-
- if(event != null) {
- String eventStr = mGsonBuilder != null ? mGsonBuilder.toJson(event) : event.toString();
-
- AUDITLOG.info(eventStr);
- }
- }
-
- @Override
- public void start() {
- // intentionally left empty
- }
-
- @Override
- public void stop() {
- // intentionally left empty
- }
-
- @Override
- public void waitToComplete() {
- // intentionally left empty
- }
-
- @Override
- public boolean isFlushPending() {
- return false;
- }
-
- @Override
- public long getLastFlushTime() {
- return 0;
- }
-
- @Override
- public void flush() {
- // intentionally left empty
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/provider/Log4jTracer.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/provider/Log4jTracer.java b/agents-audit/src/main/java/com/xasecure/audit/provider/Log4jTracer.java
deleted file mode 100644
index 734ad8d..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/provider/Log4jTracer.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * 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 com.xasecure.audit.provider;
-
-import org.apache.commons.logging.Log;
-
-public class Log4jTracer implements DebugTracer {
- private Log mLogger = null;
-
- public Log4jTracer(Log logger) {
- mLogger = logger;
- }
-
- public void debug(String msg) {
- mLogger.debug(msg);
- }
-
- public void debug(String msg, Throwable excp) {
- mLogger.debug(msg, excp);
- }
-
- public void info(String msg) {
- mLogger.info(msg);
- }
-
- public void info(String msg, Throwable excp) {
- mLogger.info(msg, excp);
- }
-
- public void warn(String msg) {
- mLogger.warn(msg);
- }
-
- public void warn(String msg, Throwable excp) {
- mLogger.warn(msg, excp);
- }
-
- public void error(String msg) {
- mLogger.error(msg);
- }
-
- public void error(String msg, Throwable excp) {
- mLogger.error(msg, excp);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/provider/LogBuffer.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/provider/LogBuffer.java b/agents-audit/src/main/java/com/xasecure/audit/provider/LogBuffer.java
deleted file mode 100644
index d8ff10a..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/provider/LogBuffer.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * 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 com.xasecure.audit.provider;
-
-
-public interface LogBuffer<T> {
- public void start(LogDestination<T> destination);
-
- public void stop();
-
- boolean isAvailable();
-
- public boolean isEmpty();
-
- public boolean add(T log);
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/provider/LogDestination.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/provider/LogDestination.java b/agents-audit/src/main/java/com/xasecure/audit/provider/LogDestination.java
deleted file mode 100644
index 18c740e..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/provider/LogDestination.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * 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 com.xasecure.audit.provider;
-
-
-public interface LogDestination<T> {
- public void start();
-
- public void stop();
-
- boolean isAvailable();
-
- public boolean send(T log);
-
- public boolean sendStringified(String log);
-
- public boolean flush();
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/provider/MiscUtil.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/provider/MiscUtil.java b/agents-audit/src/main/java/com/xasecure/audit/provider/MiscUtil.java
deleted file mode 100644
index 872420e..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/provider/MiscUtil.java
+++ /dev/null
@@ -1,250 +0,0 @@
-/*
- * 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 com.xasecure.audit.provider;
-
-import java.io.File;
-import java.net.InetAddress;
-import java.rmi.dgc.VMID;
-import java.text.SimpleDateFormat;
-import java.util.UUID;
-
-import org.apache.log4j.helpers.LogLog;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-
-public class MiscUtil {
- public static final String TOKEN_START = "%";
- public static final String TOKEN_END = "%";
- public static final String TOKEN_HOSTNAME = "hostname";
- public static final String TOKEN_APP_TYPE = "app-type";
- public static final String TOKEN_JVM_INSTANCE = "jvm-instance";
- public static final String TOKEN_TIME = "time:";
- public static final String TOKEN_PROPERTY = "property:";
- public static final String TOKEN_ENV = "env:";
- public static final String ESCAPE_STR = "\\";
-
- static VMID sJvmID = new VMID();
-
- public static String LINE_SEPARATOR = System.getProperty("line.separator");
-
- private static Gson sGsonBuilder = null;
- private static String sApplicationType = null;
-
- static {
- try {
- sGsonBuilder = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss.SSS").create();
- } catch(Throwable excp) {
- LogLog.warn("failed to create GsonBuilder object. stringigy() will return obj.toString(), instead of Json", excp);
- }
- }
-
- public static String replaceTokens(String str, long time) {
- if(str == null) {
- return str;
- }
-
- if(time <= 0) {
- time = System.currentTimeMillis();
- }
-
- for(int startPos = 0; startPos < str.length(); ) {
- int tagStartPos = str.indexOf(TOKEN_START, startPos);
-
- if(tagStartPos == -1) {
- break;
- }
-
- int tagEndPos = str.indexOf(TOKEN_END, tagStartPos + TOKEN_START.length());
-
- if(tagEndPos == -1) {
- break;
- }
-
- String tag = str.substring(tagStartPos, tagEndPos+TOKEN_END.length());
- String token = tag.substring(TOKEN_START.length(), tag.lastIndexOf(TOKEN_END));
- String val = "";
-
- if(token != null) {
- if(token.equals(TOKEN_HOSTNAME)) {
- val = getHostname();
- } else if(token.equals(TOKEN_APP_TYPE)) {
- val = getApplicationType();
- } else if(token.equals(TOKEN_JVM_INSTANCE)) {
- val = getJvmInstanceId();
- } else if(token.startsWith(TOKEN_PROPERTY)) {
- String propertyName = token.substring(TOKEN_PROPERTY.length());
-
- val = getSystemProperty(propertyName);
- } else if(token.startsWith(TOKEN_ENV)) {
- String envName = token.substring(TOKEN_ENV.length());
-
- val = getEnv(envName);
- } else if(token.startsWith(TOKEN_TIME)) {
- String dtFormat = token.substring(TOKEN_TIME.length());
-
- val = getFormattedTime(time, dtFormat);
- }
- }
-
- if(val == null) {
- val = "";
- }
-
- str = str.substring(0, tagStartPos) + val + str.substring(tagEndPos + TOKEN_END.length());
- startPos = tagStartPos + val.length();
- }
-
- return str;
- }
-
- public static String getHostname() {
- String ret = null;
-
- try {
- ret = InetAddress.getLocalHost().getHostName();
- } catch (Exception excp) {
- LogLog.warn("getHostname()", excp);
- }
-
- return ret;
- }
-
- public static void setApplicationType(String applicationType) {
- sApplicationType = applicationType;
- }
-
- public static String getApplicationType() {
- return sApplicationType;
- }
-
- public static String getJvmInstanceId() {
- String ret = Integer.toString(Math.abs(sJvmID.toString().hashCode()));
-
- return ret;
- }
-
- public static String getSystemProperty(String propertyName) {
- String ret = null;
-
- try {
- ret = propertyName != null ? System.getProperty(propertyName) : null;
- } catch (Exception excp) {
- LogLog.warn("getSystemProperty(" + propertyName + ") failed", excp);
- }
-
- return ret;
- }
-
- public static String getEnv(String envName) {
- String ret = null;
-
- try {
- ret = envName != null ? System.getenv(envName) : null;
- } catch (Exception excp) {
- LogLog.warn("getenv(" + envName + ") failed", excp);
- }
-
- return ret;
- }
-
- public static String getFormattedTime(long time, String format) {
- String ret = null;
-
- try {
- SimpleDateFormat sdf = new SimpleDateFormat(format);
-
- ret = sdf.format(time);
- } catch (Exception excp) {
- LogLog.warn("SimpleDateFormat.format() failed: " + format, excp);
- }
-
- return ret;
- }
-
- public static void createParents(File file) {
- if(file != null) {
- String parentName = file.getParent();
-
- if (parentName != null) {
- File parentDir = new File(parentName);
-
- if(!parentDir.exists()) {
- if(! parentDir.mkdirs()) {
- LogLog.warn("createParents(): failed to create " + parentDir.getAbsolutePath());
- }
- }
- }
- }
- }
-
- public static long getNextRolloverTime(long lastRolloverTime, long interval) {
- long now = System.currentTimeMillis() / 1000 * 1000; // round to second
-
- if(lastRolloverTime <= 0) {
- // should this be set to the next multiple-of-the-interval from start of the day?
- return now + interval;
- } else if(lastRolloverTime <= now) {
- long nextRolloverTime = now + interval;
-
- // keep it at 'interval' boundary
- long trimInterval = (nextRolloverTime - lastRolloverTime) % interval;
-
- return nextRolloverTime - trimInterval;
- } else {
- return lastRolloverTime;
- }
- }
-
- public static long getRolloverStartTime(long nextRolloverTime, long interval) {
- return (nextRolloverTime <= interval) ? System.currentTimeMillis() : nextRolloverTime - interval;
- }
-
- public static int parseInteger(String str, int defValue) {
- int ret = defValue;
-
- if(str != null) {
- try {
- ret = Integer.parseInt(str);
- } catch(Exception excp) {
- // ignore
- }
- }
-
- return ret;
- }
-
- public static String generateUniqueId() {
- return UUID.randomUUID().toString();
- }
-
- public static <T> String stringify(T log) {
- String ret = null;
-
- if(log != null) {
- if(log instanceof String) {
- ret = (String)log;
- } else if(MiscUtil.sGsonBuilder != null) {
- ret = MiscUtil.sGsonBuilder.toJson(log);
- } else {
- ret = log.toString();
- }
- }
-
- return ret;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/provider/MultiDestAuditProvider.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/provider/MultiDestAuditProvider.java b/agents-audit/src/main/java/com/xasecure/audit/provider/MultiDestAuditProvider.java
deleted file mode 100644
index f1b908d..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/provider/MultiDestAuditProvider.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/**
- * 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 com.xasecure.audit.provider;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import com.xasecure.audit.model.AuditEventBase;
-import com.xasecure.audit.model.HBaseAuditEvent;
-import com.xasecure.audit.model.HdfsAuditEvent;
-import com.xasecure.audit.model.HiveAuditEvent;
-import com.xasecure.audit.model.KnoxAuditEvent;
-import com.xasecure.audit.model.StormAuditEvent;
-
-
-public class MultiDestAuditProvider extends BaseAuditProvider {
-
- private static final Log LOG = LogFactory.getLog(MultiDestAuditProvider.class);
-
- protected List<AuditProvider> mProviders = new ArrayList<AuditProvider>();
-
-
- public MultiDestAuditProvider() {
- LOG.info("MultiDestAuditProvider: creating..");
- }
-
- public MultiDestAuditProvider(AuditProvider provider) {
- addAuditProvider(provider);
- }
-
- @Override
- public void init(Properties props) {
- LOG.info("MultiDestAuditProvider.init()");
-
- super.init(props);
-
- for(AuditProvider provider : mProviders) {
- try {
- provider.init(props);
- } catch(Throwable excp) {
- LOG.info("MultiDestAuditProvider.init(): failed" + provider.getClass().getCanonicalName() + ")");
- }
- }
- }
-
- public void addAuditProvider(AuditProvider provider) {
- if(provider != null) {
- LOG.info("MultiDestAuditProvider.addAuditProvider(providerType=" + provider.getClass().getCanonicalName() + ")");
-
- mProviders.add(provider);
- }
- }
-
- public void addAuditProviders(List<AuditProvider> providers) {
- if(providers != null) {
- for(AuditProvider provider : providers) {
- addAuditProvider(provider);
- }
- }
- }
-
- @Override
- public void log(AuditEventBase event) {
- for(AuditProvider provider : mProviders) {
- try {
- provider.log(event);
- } catch(Throwable excp) {
- logFailedEvent(event, excp);
- }
- }
- }
-
- @Override
- public void start() {
- for(AuditProvider provider : mProviders) {
- try {
- provider.start();
- } catch(Throwable excp) {
- LOG.error("AsyncAuditProvider.start(): failed for provider { " + provider.getClass().getName() + " }", excp);
- }
- }
- }
-
- @Override
- public void stop() {
- for(AuditProvider provider : mProviders) {
- try {
- provider.stop();
- } catch(Throwable excp) {
- LOG.error("AsyncAuditProvider.stop(): failed for provider { " + provider.getClass().getName() + " }", excp);
- }
- }
- }
-
- @Override
- public void waitToComplete() {
- for(AuditProvider provider : mProviders) {
- try {
- provider.waitToComplete();
- } catch(Throwable excp) {
- LOG.error("AsyncAuditProvider.waitToComplete(): failed for provider { " + provider.getClass().getName() + " }", excp);
- }
- }
- }
-
- @Override
- public boolean isFlushPending() {
- for(AuditProvider provider : mProviders) {
- if(provider.isFlushPending()) {
- return true;
- }
- }
-
- return false;
- }
-
- @Override
- public long getLastFlushTime() {
- long lastFlushTime = 0;
- for(AuditProvider provider : mProviders) {
- long flushTime = provider.getLastFlushTime();
-
- if(flushTime != 0) {
- if(lastFlushTime == 0 || lastFlushTime > flushTime) {
- lastFlushTime = flushTime;
- }
- }
- }
-
- return lastFlushTime;
- }
-
- @Override
- public void flush() {
- for(AuditProvider provider : mProviders) {
- try {
- provider.flush();
- } catch(Throwable excp) {
- LOG.error("AsyncAuditProvider.flush(): failed for provider { " + provider.getClass().getName() + " }", excp);
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/provider/hdfs/HdfsAuditProvider.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/provider/hdfs/HdfsAuditProvider.java b/agents-audit/src/main/java/com/xasecure/audit/provider/hdfs/HdfsAuditProvider.java
deleted file mode 100644
index b6a50ab..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/provider/hdfs/HdfsAuditProvider.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * 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 com.xasecure.audit.provider.hdfs;
-
-import java.util.Map;
-import java.util.Properties;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import com.xasecure.audit.model.AuditEventBase;
-import com.xasecure.audit.provider.BaseAuditProvider;
-import com.xasecure.audit.provider.BufferedAuditProvider;
-import com.xasecure.audit.provider.DebugTracer;
-import com.xasecure.audit.provider.LocalFileLogBuffer;
-import com.xasecure.audit.provider.Log4jTracer;
-import com.xasecure.audit.provider.MiscUtil;
-
-public class HdfsAuditProvider extends BufferedAuditProvider {
- private static final Log LOG = LogFactory.getLog(HdfsAuditProvider.class);
-
- public static final String AUDIT_HDFS_IS_ASYNC_PROP = "xasecure.audit.hdfs.is.async";
- public static final String AUDIT_HDFS_MAX_QUEUE_SIZE_PROP = "xasecure.audit.hdfs.async.max.queue.size" ;
- public static final String AUDIT_HDFS_MAX_FLUSH_INTERVAL_PROP = "xasecure.audit.hdfs.async.max.flush.interval.ms";
-
- public HdfsAuditProvider() {
- }
-
- public void init(Properties props) {
- LOG.info("HdfsAuditProvider.init()");
-
- super.init(props);
-
- Map<String, String> hdfsProps = BaseAuditProvider.getPropertiesWithPrefix(props, "xasecure.audit.hdfs.config.");
-
- String encoding = hdfsProps.get("encoding");
-
- String hdfsDestinationDirectory = hdfsProps.get("destination.directory");
- String hdfsDestinationFile = hdfsProps.get("destination.file");
- int hdfsDestinationFlushIntervalSeconds = MiscUtil.parseInteger(hdfsProps.get("destination.flush.interval.seconds"), 15 * 60);
- int hdfsDestinationRolloverIntervalSeconds = MiscUtil.parseInteger(hdfsProps.get("destination.rollover.interval.seconds"), 24 * 60 * 60);
- int hdfsDestinationOpenRetryIntervalSeconds = MiscUtil.parseInteger(hdfsProps.get("destination.open.retry.interval.seconds"), 60);
-
- String localFileBufferDirectory = hdfsProps.get("local.buffer.directory");
- String localFileBufferFile = hdfsProps.get("local.buffer.file");
- int localFileBufferFlushIntervalSeconds = MiscUtil.parseInteger(hdfsProps.get("local.buffer.flush.interval.seconds"), 1 * 60);
- int localFileBufferFileBufferSizeBytes = MiscUtil.parseInteger(hdfsProps.get("local.buffer.file.buffer.size.bytes"), 8 * 1024);
- int localFileBufferRolloverIntervalSeconds = MiscUtil.parseInteger(hdfsProps.get("local.buffer.rollover.interval.seconds"), 10 * 60);
- String localFileBufferArchiveDirectory = hdfsProps.get("local.archive.directory");
- int localFileBufferArchiveFileCount = MiscUtil.parseInteger(hdfsProps.get("local.archive.max.file.count"), 10);
-
- DebugTracer tracer = new Log4jTracer(LOG);
-
- HdfsLogDestination<AuditEventBase> mHdfsDestination = new HdfsLogDestination<AuditEventBase>(tracer);
-
- mHdfsDestination.setDirectory(hdfsDestinationDirectory);
- mHdfsDestination.setFile(hdfsDestinationFile);
- mHdfsDestination.setFlushIntervalSeconds(hdfsDestinationFlushIntervalSeconds);
- mHdfsDestination.setEncoding(encoding);
- mHdfsDestination.setRolloverIntervalSeconds(hdfsDestinationRolloverIntervalSeconds);
- mHdfsDestination.setOpenRetryIntervalSeconds(hdfsDestinationOpenRetryIntervalSeconds);
-
- LocalFileLogBuffer<AuditEventBase> mLocalFileBuffer = new LocalFileLogBuffer<AuditEventBase>(tracer);
-
- mLocalFileBuffer.setDirectory(localFileBufferDirectory);
- mLocalFileBuffer.setFile(localFileBufferFile);
- mLocalFileBuffer.setFlushIntervalSeconds(localFileBufferFlushIntervalSeconds);
- mLocalFileBuffer.setFileBufferSizeBytes(localFileBufferFileBufferSizeBytes);
- mLocalFileBuffer.setEncoding(encoding);
- mLocalFileBuffer.setRolloverIntervalSeconds(localFileBufferRolloverIntervalSeconds);
- mLocalFileBuffer.setArchiveDirectory(localFileBufferArchiveDirectory);
- mLocalFileBuffer.setArchiveFileCount(localFileBufferArchiveFileCount);
-
- setBufferAndDestination(mLocalFileBuffer, mHdfsDestination);
- }
-}
-
-
-
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/provider/hdfs/HdfsLogDestination.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/provider/hdfs/HdfsLogDestination.java b/agents-audit/src/main/java/com/xasecure/audit/provider/hdfs/HdfsLogDestination.java
deleted file mode 100644
index f81f526..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/provider/hdfs/HdfsLogDestination.java
+++ /dev/null
@@ -1,452 +0,0 @@
-/*
- * 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 com.xasecure.audit.provider.hdfs;
-
-
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.FSDataOutputStream;
-import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.fs.Path;
-
-import com.xasecure.audit.provider.DebugTracer;
-import com.xasecure.audit.provider.LogDestination;
-import com.xasecure.audit.provider.MiscUtil;
-
-public class HdfsLogDestination<T> implements LogDestination<T> {
- public final static String EXCP_MSG_FILESYSTEM_CLOSED = "Filesystem closed";
-
- private String mDirectory = null;
- private String mFile = null;
- private int mFlushIntervalSeconds = 1 * 60;
- private String mEncoding = null;
- private boolean mIsAppend = false;
- private int mRolloverIntervalSeconds = 24 * 60 * 60;
- private int mOpenRetryIntervalSeconds = 60;
- private DebugTracer mLogger = null;
-
- private FSDataOutputStream mFsDataOutStream = null;
- private OutputStreamWriter mWriter = null;
- private String mHdfsFilename = null;
- private long mNextRolloverTime = 0;
- private long mNextFlushTime = 0;
- private long mLastOpenFailedTime = 0;
- private boolean mIsStopInProgress = false;
-
- public HdfsLogDestination(DebugTracer tracer) {
- mLogger = tracer;
- }
-
- public String getDirectory() {
- return mDirectory;
- }
-
- public void setDirectory(String directory) {
- this.mDirectory = directory;
- }
-
- public String getFile() {
- return mFile;
- }
-
- public void setFile(String file) {
- this.mFile = file;
- }
-
- public int getFlushIntervalSeconds() {
- return mFlushIntervalSeconds;
- }
-
- public void setFlushIntervalSeconds(int flushIntervalSeconds) {
- mFlushIntervalSeconds = flushIntervalSeconds;
- }
-
- public String getEncoding() {
- return mEncoding;
- }
-
- public void setEncoding(String encoding) {
- mEncoding = encoding;
- }
-
- public int getRolloverIntervalSeconds() {
- return mRolloverIntervalSeconds;
- }
-
- public void setRolloverIntervalSeconds(int rolloverIntervalSeconds) {
- this.mRolloverIntervalSeconds = rolloverIntervalSeconds;
- }
-
- public int getOpenRetryIntervalSeconds() {
- return mOpenRetryIntervalSeconds;
- }
-
- public void setOpenRetryIntervalSeconds(int minIntervalOpenRetrySeconds) {
- this.mOpenRetryIntervalSeconds = minIntervalOpenRetrySeconds;
- }
-
- @Override
- public void start() {
- mLogger.debug("==> HdfsLogDestination.start()");
-
- openFile();
-
- mLogger.debug("<== HdfsLogDestination.start()");
- }
-
- @Override
- public void stop() {
- mLogger.debug("==> HdfsLogDestination.stop()");
-
- mIsStopInProgress = true;
-
- closeFile();
-
- mIsStopInProgress = false;
-
- mLogger.debug("<== HdfsLogDestination.stop()");
- }
-
- @Override
- public boolean isAvailable() {
- return mWriter != null;
- }
-
- @Override
- public boolean send(T log) {
- boolean ret = false;
-
- if(log != null) {
- String msg = log.toString();
-
- ret = sendStringified(msg);
- }
-
- return ret;
- }
-
- @Override
- public boolean sendStringified(String log) {
- boolean ret = false;
-
- checkFileStatus();
-
- OutputStreamWriter writer = mWriter;
-
- if(writer != null) {
- try {
- writer.write(log + MiscUtil.LINE_SEPARATOR);
-
- ret = true;
- } catch (IOException excp) {
- mLogger.warn("HdfsLogDestination.sendStringified(): write failed", excp);
-
- closeFile();
- }
- }
-
- return ret;
- }
-
- @Override
- public boolean flush() {
- mLogger.debug("==> HdfsLogDestination.flush()");
-
- boolean ret = false;
-
- OutputStreamWriter writer = mWriter;
-
- if(writer != null) {
- try {
- writer.flush();
-
- ret = true;
- } catch (IOException excp) {
- logException("HdfsLogDestination: flush() failed", excp);
- }
- }
-
- FSDataOutputStream ostream = mFsDataOutStream;
-
- if(ostream != null) {
- try {
- ostream.hflush();
-
- ret = true;
- } catch (IOException excp) {
- logException("HdfsLogDestination: hflush() failed", excp);
- }
- }
-
- if(ret) {
- mNextFlushTime = System.currentTimeMillis() + (mFlushIntervalSeconds * 1000L);
- }
-
- mLogger.debug("<== HdfsLogDestination.flush()");
-
- return ret;
- }
-
- private void openFile() {
- mLogger.debug("==> HdfsLogDestination.openFile()");
-
- closeFile();
-
- mNextRolloverTime = MiscUtil.getNextRolloverTime(mNextRolloverTime, (mRolloverIntervalSeconds * 1000L));
-
- long startTime = MiscUtil.getRolloverStartTime(mNextRolloverTime, (mRolloverIntervalSeconds * 1000L));
-
- mHdfsFilename = MiscUtil.replaceTokens(mDirectory + org.apache.hadoop.fs.Path.SEPARATOR + mFile, startTime);
-
- FSDataOutputStream ostream = null;
- FileSystem fileSystem = null;
- Path pathLogfile = null;
- Configuration conf = null;
- boolean bOverwrite = false;
-
- try {
- mLogger.debug("HdfsLogDestination.openFile(): opening file " + mHdfsFilename);
-
- URI uri = URI.create(mHdfsFilename);
-
- // TODO: mechanism to XA-HDFS plugin to disable auditing of access checks to the current HDFS file
-
- conf = new Configuration();
- pathLogfile = new Path(mHdfsFilename);
- fileSystem = FileSystem.get(uri, conf);
-
- try {
- if(fileSystem.exists(pathLogfile)) { // file already exists. either append to the file or write to a new file
- if(mIsAppend) {
- mLogger.info("HdfsLogDestination.openFile(): opening file for append " + mHdfsFilename);
-
- ostream = fileSystem.append(pathLogfile);
- } else {
- mHdfsFilename = getNewFilename(mHdfsFilename, fileSystem);
- pathLogfile = new Path(mHdfsFilename);
- }
- }
-
- // if file does not exist or if mIsAppend==false, create the file
- if(ostream == null) {
- mLogger.info("HdfsLogDestination.openFile(): opening file for write " + mHdfsFilename);
-
- createParents(pathLogfile, fileSystem);
- ostream = fileSystem.create(pathLogfile, bOverwrite);
- }
- } catch(IOException excp) {
- // append may not be supported by the filesystem; or the file might already be open by another application. Try a different filename
- String failedFilename = mHdfsFilename;
-
- mHdfsFilename = getNewFilename(mHdfsFilename, fileSystem);
- pathLogfile = new Path(mHdfsFilename);
-
- mLogger.info("HdfsLogDestination.openFile(): failed in opening file " + failedFilename + ". Will try opening " + mHdfsFilename);
- }
-
- if(ostream == null){
- mLogger.info("HdfsLogDestination.openFile(): opening file for write " + mHdfsFilename);
-
- createParents(pathLogfile, fileSystem);
- ostream = fileSystem.create(pathLogfile, bOverwrite);
- }
- } catch(Throwable ex) {
- mLogger.warn("HdfsLogDestination.openFile() failed", ex);
- } finally {
- // TODO: unset the property set above to exclude auditing of logfile opening
- // System.setProperty(hdfsCurrentFilenameProperty, null);
- }
-
- mWriter = createWriter(ostream);
-
- if(mWriter != null) {
- mLogger.debug("HdfsLogDestination.openFile(): opened file " + mHdfsFilename);
-
- mFsDataOutStream = ostream;
- mNextFlushTime = System.currentTimeMillis() + (mFlushIntervalSeconds * 1000L);
- mLastOpenFailedTime = 0;
- } else {
- mLogger.warn("HdfsLogDestination.openFile(): failed to open file for write " + mHdfsFilename);
-
- mHdfsFilename = null;
- mLastOpenFailedTime = System.currentTimeMillis();
- }
-
- mLogger.debug("<== HdfsLogDestination.openFile(" + mHdfsFilename + ")");
- }
-
- private void closeFile() {
- mLogger.debug("==> HdfsLogDestination.closeFile()");
-
- flush();
-
- OutputStreamWriter writer = mWriter;
-
- mWriter = null;
- mFsDataOutStream = null;
-
- if(writer != null) {
- try {
- mLogger.info("HdfsLogDestination.closeFile(): closing file " + mHdfsFilename);
-
- writer.close();
- } catch(IOException excp) {
- logException("HdfsLogDestination: failed to close file " + mHdfsFilename, excp);
- }
- }
-
- mLogger.debug("<== HdfsLogDestination.closeFile()");
- }
-
- private void rollover() {
- mLogger.debug("==> HdfsLogDestination.rollover()");
-
- closeFile();
-
- openFile();
-
- mLogger.debug("<== HdfsLogDestination.rollover()");
- }
-
- private void checkFileStatus() {
- long now = System.currentTimeMillis();
-
- if(mWriter == null) {
- if(now > (mLastOpenFailedTime + (mOpenRetryIntervalSeconds * 1000L))) {
- openFile();
- }
- } else if(now > mNextRolloverTime) {
- rollover();
- } else if(now > mNextFlushTime) {
- flush();
- }
- }
-
- private OutputStreamWriter createWriter(OutputStream os ) {
- OutputStreamWriter writer = null;
-
- if(os != null) {
- if(mEncoding != null) {
- try {
- writer = new OutputStreamWriter(os, mEncoding);
- } catch(UnsupportedEncodingException excp) {
- mLogger.warn("HdfsLogDestination.createWriter(): failed to create output writer.", excp);
- }
- }
-
- if(writer == null) {
- writer = new OutputStreamWriter(os);
- }
- }
-
- return writer;
- }
-
- private void createParents(Path pathLogfile, FileSystem fileSystem) {
- try {
- Path parentPath = pathLogfile != null ? pathLogfile.getParent() : null;
-
- if(parentPath != null && fileSystem != null && !fileSystem.exists(parentPath)) {
- fileSystem.mkdirs(parentPath);
- }
- } catch (IOException e) {
- logException("HdfsLogDestination.createParents() failed", e);
- } catch (Throwable e) {
- mLogger.warn("HdfsLogDestination.createParents() failed", e);
- }
- }
-
- private String getNewFilename(String fileName, FileSystem fileSystem) {
- if(fileName == null) {
- return "";
- }
-
- for(int i = 1; ; i++) {
- String ret = fileName;
-
- String strToAppend = "-" + Integer.toString(i);
-
- int extnPos = ret.lastIndexOf(".");
-
- if(extnPos < 0) {
- ret += strToAppend;
- } else {
- String extn = ret.substring(extnPos);
-
- ret = ret.substring(0, extnPos) + strToAppend + extn;
- }
-
- if(fileSystem != null && fileExists(ret, fileSystem)) {
- continue;
- } else {
- return ret;
- }
- }
- }
-
- private boolean fileExists(String fileName, FileSystem fileSystem) {
- boolean ret = false;
-
- if(fileName != null && fileSystem != null) {
- Path path = new Path(fileName);
-
- try {
- ret = fileSystem.exists(path);
- } catch(IOException excp) {
- // ignore
- }
- }
-
- return ret;
- }
-
- private void logException(String msg, IOException excp) {
- // during shutdown, the underlying FileSystem might already be closed; so don't print error details
-
- if(mIsStopInProgress) {
- return;
- }
-
- String excpMsgToExclude = EXCP_MSG_FILESYSTEM_CLOSED;;
- String excpMsg = excp != null ? excp.getMessage() : null;
- boolean excpExcludeLogging = (excpMsg != null && excpMsg.contains(excpMsgToExclude));
-
- if(! excpExcludeLogging) {
- mLogger.warn(msg, excp);
- }
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
-
- sb.append("HdfsLogDestination {");
- sb.append("Directory=").append(mDirectory).append("; ");
- sb.append("File=").append(mFile).append("; ");
- sb.append("RolloverIntervalSeconds=").append(mRolloverIntervalSeconds);
- sb.append("}");
-
- return sb.toString();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/test/TestEvents.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/test/TestEvents.java b/agents-audit/src/main/java/com/xasecure/audit/test/TestEvents.java
deleted file mode 100644
index 92497f7..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/test/TestEvents.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * 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 com.xasecure.audit.test;
-import org.apache.commons.logging.Log;
-import org.apache.log4j.xml.DOMConfigurator;
-import org.apache.commons.logging.LogFactory;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.util.Date;
-import java.util.Properties;
-
-import com.xasecure.audit.model.AuditEventBase;
-import com.xasecure.audit.model.HBaseAuditEvent;
-import com.xasecure.audit.model.HdfsAuditEvent;
-import com.xasecure.audit.model.HiveAuditEvent;
-import com.xasecure.audit.model.KnoxAuditEvent;
-import com.xasecure.audit.model.StormAuditEvent;
-import com.xasecure.audit.provider.AuditProvider;
-import com.xasecure.audit.provider.AuditProviderFactory;
-import com.xasecure.audit.provider.AuditProviderFactory.ApplicationType;
-
-public class TestEvents {
-
- private static final Log LOG = LogFactory.getLog(TestEvents.class);
-
- public static void main(String[] args) {
- DOMConfigurator.configure("log4j.xml");
-
- LOG.info("==> TestEvents.main()");
-
- try {
- Properties auditProperties = new Properties();
-
- String AUDIT_PROPERTIES_FILE = "xasecure-audit.properties";
-
- File propFile = new File(AUDIT_PROPERTIES_FILE);
-
- if(propFile.exists()) {
- LOG.info("Loading Audit properties file" + AUDIT_PROPERTIES_FILE);
-
- auditProperties.load(new FileInputStream(propFile));
- } else {
- LOG.info("Audit properties file missing: " + AUDIT_PROPERTIES_FILE);
-
- auditProperties.setProperty("xasecure.audit.jpa.javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xa_db");
- auditProperties.setProperty("xasecure.audit.jpa.javax.persistence.jdbc.user", "xaaudit");
- auditProperties.setProperty("xasecure.audit.jpa.javax.persistence.jdbc.password", "xaaudit");
- auditProperties.setProperty("xasecure.audit.jpa.javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
-
- auditProperties.setProperty("xasecure.audit.is.enabled", "true");
- auditProperties.setProperty("xasecure.audit.log4j.is.enabled", "false");
- auditProperties.setProperty("xasecure.audit.log4j.is.async", "false");
- auditProperties.setProperty("xasecure.audit.log4j.async.max.queue.size", "100000");
- auditProperties.setProperty("xasecure.audit.log4j.async.max.flush.interval.ms", "30000");
- auditProperties.setProperty("xasecure.audit.db.is.enabled", "true");
- auditProperties.setProperty("xasecure.audit.db.is.async", "true");
- auditProperties.setProperty("xasecure.audit.db.async.max.queue.size", "100000");
- auditProperties.setProperty("xasecure.audit.db.async.max.flush.interval.ms", "30000");
- auditProperties.setProperty("xasecure.audit.db.batch.size", "100");
- }
-
- AuditProviderFactory.getInstance().init(auditProperties, ApplicationType.Hdfs);
-
- AuditProvider provider = AuditProviderFactory.getAuditProvider();
-
- LOG.info("provider=" + provider.toString());
-
- String strEventCount = args.length > 0 ? args[0] : auditProperties.getProperty("xasecure.audit.test.event.count");
- String strEventPauseTimeInMs = args.length > 1 ? args[1] : auditProperties.getProperty("xasecure.audit.test.event.pause.time.ms");
- String strSleepTimeBeforeExit = args.length > 2 ? args[2] : auditProperties.getProperty("xasecure.audit.test.sleep.time.before.exit.seconds");
-
- int eventCount = (strEventCount == null) ? 1024 : Integer.parseInt(strEventCount);
- int eventPauseTime = (strEventPauseTimeInMs == null) ? 0 : Integer.parseInt(strEventPauseTimeInMs);
- int sleepTimeBeforeExit = ((strSleepTimeBeforeExit == null) ? 0 : Integer.parseInt(strSleepTimeBeforeExit)) * 1000;
-
- for(int i = 0; i < eventCount; i++) {
- AuditEventBase event = getTestEvent(i);
-
- LOG.info("==> TestEvents.main(" + (i+1) + "): adding " + event.getClass().getName());
- provider.log(event);
-
- if(eventPauseTime > 0) {
- Thread.sleep(eventPauseTime);
- }
- }
-
- provider.waitToComplete();
-
- // incase of HdfsAuditProvider, logs are saved to local file system which gets sent to HDFS asynchronusly in a separate thread.
- // So, at this point it is possible that few local log files haven't made to HDFS.
- if(sleepTimeBeforeExit > 0) {
- LOG.info("waiting for " + sleepTimeBeforeExit + "ms before exiting..");
-
- try {
- Thread.sleep(sleepTimeBeforeExit);
- } catch(Exception excp) {
- LOG.info("error while waiting before exiting..");
- }
- }
-
- provider.stop();
- } catch(Exception excp) {
- LOG.info(excp.getLocalizedMessage());
- excp.printStackTrace();
- }
-
- LOG.info("<== TestEvents.main()");
- }
-
- private static AuditEventBase getTestEvent(int idx) {
- AuditEventBase event = null;
-
- switch(idx % 5) {
- case 0:
- event = new HdfsAuditEvent();
- break;
- case 1:
- event = new HBaseAuditEvent();
- break;
- case 2:
- event = new HiveAuditEvent();
- break;
- case 3:
- event = new KnoxAuditEvent();
- break;
- case 4:
- event = new StormAuditEvent();
- break;
- }
- event.setEventTime(new Date());
- event.setResultReason(Integer.toString(idx));
-
- return event;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/dao/BaseDao.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/dao/BaseDao.java b/agents-audit/src/main/java/org/apache/ranger/audit/dao/BaseDao.java
new file mode 100644
index 0000000..8c42d86
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/dao/BaseDao.java
@@ -0,0 +1,234 @@
+/*
+ * 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.audit.dao;
+
+
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.EntityTransaction;
+import javax.persistence.NoResultException;
+import javax.persistence.TypedQuery;
+
+import org.apache.log4j.Logger;
+
+public abstract class BaseDao<T> {
+ static final Logger logger = Logger.getLogger(BaseDao.class);
+
+ protected DaoManager daoManager;
+
+ protected Class<T> tClass;
+
+ public BaseDao(DaoManagerBase daoManager) {
+ this.init(daoManager);
+ }
+
+ @SuppressWarnings("unchecked")
+ private void init(DaoManagerBase daoManager) {
+ this.daoManager = (DaoManager) daoManager;
+
+ ParameterizedType genericSuperclass = (ParameterizedType) getClass()
+ .getGenericSuperclass();
+
+ Type type = genericSuperclass.getActualTypeArguments()[0];
+
+ if (type instanceof ParameterizedType) {
+ this.tClass = (Class<T>) ((ParameterizedType) type).getRawType();
+ } else {
+ this.tClass = (Class<T>) type;
+ }
+ }
+
+ public EntityManager getEntityManager() {
+ return daoManager.getEntityManager();
+ }
+
+ public boolean beginTransaction() {
+ boolean ret = false;
+
+ EntityManager em = getEntityManager();
+
+ if(em != null) {
+ EntityTransaction et = em.getTransaction();
+
+ // check the transaction is not already active
+ if(et != null && !et.isActive()) {
+ et.begin();
+ ret = true;
+ }
+ }
+
+ return ret;
+ }
+
+ public void commitTransaction() {
+ EntityManager em = getEntityManager();
+
+ if(em != null) {
+ em.flush();
+
+ EntityTransaction et = em.getTransaction();
+
+ if(et != null) {
+ et.commit();
+ }
+ }
+ }
+
+ public void rollbackTransaction() {
+ EntityManager em = getEntityManager();
+
+ if(em != null) {
+ EntityTransaction et = em.getTransaction();
+
+ if(et != null) {
+ et.rollback();
+ }
+ }
+ }
+
+ public T create(T obj) {
+ T ret = null;
+
+ boolean trxBegan = beginTransaction();
+
+ getEntityManager().persist(obj);
+
+ if(trxBegan) {
+ commitTransaction();
+ }
+
+ ret = obj;
+
+ return ret;
+ }
+
+ public T update(T obj) {
+ boolean trxBegan = beginTransaction();
+
+ getEntityManager().merge(obj);
+
+ if(trxBegan) {
+ commitTransaction();
+ }
+
+ return obj;
+ }
+
+ public boolean remove(Long id) {
+ return remove(getById(id));
+ }
+
+ public boolean remove(T obj) {
+ if (obj == null) {
+ return true;
+ }
+
+ boolean ret = false;
+
+ boolean trxBegan = beginTransaction();
+
+ getEntityManager().remove(obj);
+
+ if(trxBegan) {
+ commitTransaction();
+ }
+
+ ret = true;
+
+ return ret;
+ }
+
+ public T getById(Long id) {
+ if (id == null) {
+ return null;
+ }
+ T ret = null;
+ try {
+ ret = getEntityManager().find(tClass, id);
+ } catch (NoResultException e) {
+ return null;
+ }
+ return ret;
+ }
+
+ public List<T> getAll() {
+ List<T> ret = null;
+
+ TypedQuery<T> qry = getEntityManager().createQuery(
+ "SELECT t FROM " + tClass.getSimpleName() + " t", tClass);
+
+ ret = qry.getResultList();
+
+ return ret;
+ }
+
+ public Long getAllCount() {
+ Long ret = null;
+
+ TypedQuery<Long> qry = getEntityManager().createQuery(
+ "SELECT count(t) FROM " + tClass.getSimpleName() + " t",
+ Long.class);
+
+ ret = qry.getSingleResult();
+
+ return ret;
+ }
+
+ public T getUniqueResult(TypedQuery<T> qry) {
+ T ret = null;
+
+ try {
+ ret = qry.getSingleResult();
+ } catch (NoResultException e) {
+ // ignore
+ }
+ return ret;
+ }
+
+ public List<T> executeQuery(TypedQuery<T> qry) {
+ List<T> ret = null;
+
+ ret = qry.getResultList();
+
+ return ret;
+ }
+
+ public List<T> findByNamedQuery(String namedQuery, String paramName,
+ Object refId) {
+ List<T> ret = new ArrayList<T>();
+
+ if (namedQuery == null) {
+ return ret;
+ }
+ try {
+ TypedQuery<T> qry = getEntityManager().createNamedQuery(namedQuery, tClass);
+ qry.setParameter(paramName, refId);
+ ret = qry.getResultList();
+ } catch (NoResultException e) {
+ // ignore
+ }
+ return ret;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/dao/DaoManager.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/dao/DaoManager.java b/agents-audit/src/main/java/org/apache/ranger/audit/dao/DaoManager.java
new file mode 100644
index 0000000..6d81744
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/dao/DaoManager.java
@@ -0,0 +1,56 @@
+/*
+ * 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.audit.dao;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.PersistenceContext;
+
+
+//@Component
+public class DaoManager extends DaoManagerBase {
+
+ @PersistenceContext
+ private EntityManagerFactory emf;
+
+ static ThreadLocal<EntityManager> sEntityManager;
+
+ public void setEntityManagerFactory(EntityManagerFactory emf) {
+ this.emf = emf;
+ sEntityManager = new ThreadLocal<EntityManager>();
+ }
+
+ @Override
+ public EntityManager getEntityManager() {
+ EntityManager em = null;
+
+ if(sEntityManager != null) {
+ em = sEntityManager.get();
+
+ if(em == null && this.emf != null) {
+ em = this.emf.createEntityManager();
+
+ sEntityManager.set(em);
+ }
+ }
+
+ return em;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/dao/DaoManagerBase.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/dao/DaoManagerBase.java b/agents-audit/src/main/java/org/apache/ranger/audit/dao/DaoManagerBase.java
new file mode 100644
index 0000000..af7cfb4
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/dao/DaoManagerBase.java
@@ -0,0 +1,80 @@
+/**
+ * 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.audit.dao;
+
+import javax.persistence.EntityManager;
+
+import org.apache.log4j.Logger;
+
+
+public abstract class DaoManagerBase {
+ final static Logger logger = Logger.getLogger(DaoManagerBase.class);
+
+ abstract public EntityManager getEntityManager();
+
+ private RangerHBaseAuditEventDao mHBaseDao = null;
+ private RangerHdfsAuditEventDao mHdfsDao = null;
+ private RangerHiveAuditEventDao mHiveDao = null;
+ private RangerKnoxAuditEventDao mKnoxDao = null;
+ private RangerStormAuditEventDao mStormDao = null;
+
+ public DaoManagerBase() {
+ }
+
+ public RangerHBaseAuditEventDao getXAHBaseAuditEventDao() {
+ if(mHBaseDao == null) {
+ mHBaseDao = new RangerHBaseAuditEventDao(this);
+ }
+
+ return mHBaseDao;
+ }
+
+ public RangerHdfsAuditEventDao getXAHdfsAuditEventDao() {
+ if(mHdfsDao == null) {
+ mHdfsDao = new RangerHdfsAuditEventDao(this);
+ }
+
+ return mHdfsDao;
+ }
+
+ public RangerHiveAuditEventDao getXAHiveAuditEventDao() {
+ if(mHiveDao == null) {
+ mHiveDao = new RangerHiveAuditEventDao(this);
+ }
+
+ return mHiveDao;
+ }
+
+ public RangerKnoxAuditEventDao getXAKnoxAuditEventDao() {
+ if(mKnoxDao == null) {
+ mKnoxDao = new RangerKnoxAuditEventDao(this);
+ }
+
+ return mKnoxDao;
+ }
+
+ public RangerStormAuditEventDao getXAStormAuditEventDao() {
+ if(mStormDao == null) {
+ mStormDao = new RangerStormAuditEventDao(this);
+ }
+
+ return mStormDao;
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/dao/RangerHBaseAuditEventDao.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/dao/RangerHBaseAuditEventDao.java b/agents-audit/src/main/java/org/apache/ranger/audit/dao/RangerHBaseAuditEventDao.java
new file mode 100644
index 0000000..1d6cd93
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/dao/RangerHBaseAuditEventDao.java
@@ -0,0 +1,29 @@
+/*
+ * 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.audit.dao;
+
+import org.apache.ranger.audit.entity.XXHBaseAuditEvent;
+
+public class RangerHBaseAuditEventDao extends BaseDao<XXHBaseAuditEvent> {
+
+ public RangerHBaseAuditEventDao(DaoManagerBase daoManager) {
+ super(daoManager);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/dao/RangerHdfsAuditEventDao.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/dao/RangerHdfsAuditEventDao.java b/agents-audit/src/main/java/org/apache/ranger/audit/dao/RangerHdfsAuditEventDao.java
new file mode 100644
index 0000000..566dee9
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/dao/RangerHdfsAuditEventDao.java
@@ -0,0 +1,29 @@
+/*
+ * 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.audit.dao;
+
+import org.apache.ranger.audit.entity.XXHdfsAuditEvent;
+
+public class RangerHdfsAuditEventDao extends BaseDao<XXHdfsAuditEvent> {
+
+ public RangerHdfsAuditEventDao(DaoManagerBase daoManager) {
+ super(daoManager);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/dao/RangerHiveAuditEventDao.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/dao/RangerHiveAuditEventDao.java b/agents-audit/src/main/java/org/apache/ranger/audit/dao/RangerHiveAuditEventDao.java
new file mode 100644
index 0000000..f94523d
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/dao/RangerHiveAuditEventDao.java
@@ -0,0 +1,29 @@
+/*
+ * 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.audit.dao;
+
+import org.apache.ranger.audit.entity.XXHiveAuditEvent;
+
+public class RangerHiveAuditEventDao extends BaseDao<XXHiveAuditEvent> {
+
+ public RangerHiveAuditEventDao(DaoManagerBase daoManager) {
+ super(daoManager);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/dao/RangerKnoxAuditEventDao.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/dao/RangerKnoxAuditEventDao.java b/agents-audit/src/main/java/org/apache/ranger/audit/dao/RangerKnoxAuditEventDao.java
new file mode 100644
index 0000000..21ec1af
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/dao/RangerKnoxAuditEventDao.java
@@ -0,0 +1,29 @@
+/**
+ * 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.audit.dao;
+
+import org.apache.ranger.audit.entity.XXKnoxAuditEvent;
+
+public class RangerKnoxAuditEventDao extends BaseDao<XXKnoxAuditEvent> {
+
+ public RangerKnoxAuditEventDao(DaoManagerBase daoManager) {
+ super(daoManager);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/dao/RangerStormAuditEventDao.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/dao/RangerStormAuditEventDao.java b/agents-audit/src/main/java/org/apache/ranger/audit/dao/RangerStormAuditEventDao.java
new file mode 100644
index 0000000..71b5e50
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/dao/RangerStormAuditEventDao.java
@@ -0,0 +1,29 @@
+/**
+ * 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.audit.dao;
+
+import org.apache.ranger.audit.entity.XXStormAuditEvent;
+
+public class RangerStormAuditEventDao extends BaseDao<XXStormAuditEvent> {
+
+ public RangerStormAuditEventDao(DaoManagerBase daoManager) {
+ super(daoManager);
+ }
+
+}
[45/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-common/src/main/java/com/xasecure/authorization/utils/StringUtil.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/com/xasecure/authorization/utils/StringUtil.java b/agents-common/src/main/java/com/xasecure/authorization/utils/StringUtil.java
deleted file mode 100644
index 7e3dccd..0000000
--- a/agents-common/src/main/java/com/xasecure/authorization/utils/StringUtil.java
+++ /dev/null
@@ -1,276 +0,0 @@
-/*
- * 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 com.xasecure.authorization.utils;
-
-import java.util.Calendar;
-import java.util.Collection;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.List;
-import java.util.TimeZone;
-
-public class StringUtil {
-
- private static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT+0");
-
- public static boolean equals(String str1, String str2) {
- boolean ret = false;
-
- if(str1 == null) {
- ret = str2 == null;
- } else if(str2 == null) {
- ret = false;
- } else {
- ret = str1.equals(str2);
- }
-
- return ret;
- }
-
- public static boolean equalsIgnoreCase(String str1, String str2) {
- boolean ret = false;
-
- if(str1 == null) {
- ret = str2 == null;
- } else if(str2 == null) {
- ret = false;
- } else {
- ret = str1.equalsIgnoreCase(str2);
- }
-
- return ret;
- }
-
- public static boolean equals(Collection<String> set1, Collection<String> set2) {
- boolean ret = false;
-
- if(set1 == null) {
- ret = set2 == null;
- } else if(set2 == null) {
- ret = false;
- } else if(set1.size() == set2.size()) {
- ret = set1.containsAll(set2);
- }
-
- return ret;
- }
-
- public static boolean equalsIgnoreCase(Collection<String> set1, Collection<String> set2) {
- boolean ret = false;
-
- if(set1 == null) {
- ret = set2 == null;
- } else if(set2 == null) {
- ret = false;
- } else if(set1.size() == set2.size()) {
- int numFound = 0;
-
- for(String str1 : set1) {
- boolean str1Found = false;
-
- for(String str2 : set2) {
- if(equalsIgnoreCase(str1, str2)) {
- str1Found = true;
-
- break;
- }
- }
-
- if(str1Found) {
- numFound++;
- } else {
- break;
- }
- }
-
- ret = numFound == set1.size();
- }
-
- return ret;
- }
-
- public static boolean matches(String pattern, String str) {
- boolean ret = false;
-
- if(pattern == null || str == null || pattern.isEmpty() || str.isEmpty()) {
- ret = true;
- } else {
- ret = str.matches(pattern);
- }
-
- return ret;
- }
-
- /*
- public static boolean matches(Collection<String> patternSet, Collection<String> strSet) {
- boolean ret = false;
-
- if(patternSet == null || strSet == null || patternSet.isEmpty() || strSet.isEmpty()) {
- ret = true;
- } else {
- boolean foundUnmatched = false;
-
- for(String str : strSet) {
- boolean isMatched = false;
- for(String pattern : patternSet) {
- isMatched = str.matches(pattern);
-
- if(isMatched) {
- break;
- }
- }
-
- foundUnmatched = ! isMatched;
-
- if(foundUnmatched) {
- break;
- }
- }
-
- ret = !foundUnmatched;
- }
-
- return ret;
- }
- */
-
- public static boolean contains(String str, String strToFind) {
- boolean ret = false;
-
- if(str != null && strToFind != null) {
- ret = str.contains(strToFind);
- }
-
- return ret;
- }
-
- public static boolean containsIgnoreCase(String str, String strToFind) {
- boolean ret = false;
-
- if(str != null && strToFind != null) {
- ret = str.toLowerCase().contains(strToFind.toLowerCase());
- }
-
- return ret;
- }
-
- public static boolean contains(String[] strArr, String str) {
- boolean ret = false;
-
- if(strArr != null && strArr.length > 0 && str != null) {
- for(String s : strArr) {
- ret = equals(s, str);
-
- if(ret) {
- break;
- }
- }
- }
-
- return ret;
- }
-
- public static boolean containsIgnoreCase(String[] strArr, String str) {
- boolean ret = false;
-
- if(strArr != null && strArr.length > 0 && str != null) {
- for(String s : strArr) {
- ret = equalsIgnoreCase(s, str);
-
- if(ret) {
- break;
- }
- }
- }
-
- return ret;
- }
-
- public static String toString(Iterable<String> iterable) {
- String ret = "";
-
- if(iterable != null) {
- int count = 0;
- for(String str : iterable) {
- if(count == 0)
- ret = str;
- else
- ret += (", " + str);
- count++;
- }
- }
-
- return ret;
- }
-
- public static String toString(String[] arr) {
- String ret = "";
-
- if(arr != null && arr.length > 0) {
- ret = arr[0];
- for(int i = 1; i < arr.length; i++) {
- ret += (", " + arr[i]);
- }
- }
-
- return ret;
- }
-
- public static String toString(List<String> arr) {
- String ret = "";
-
- if(arr != null && arr.size() > 0) {
- ret = arr.get(0);
- for(int i = 1; i < arr.size(); i++) {
- ret += (", " + arr.get(i));
- }
- }
-
- return ret;
- }
-
- public static boolean isEmpty(String str) {
- return str == null || str.trim().isEmpty();
- }
-
- public static <T> boolean isEmpty(Collection<T> set) {
- return set == null || set.isEmpty();
- }
-
- public static String toLower(String str) {
- return str == null ? null : str.toLowerCase();
- }
-
- public static byte[] getBytes(String str) {
- return str == null ? null : str.getBytes();
- }
-
- public static Date getUTCDate() {
- Calendar local = Calendar.getInstance();
- int offset = local.getTimeZone().getOffset(local.getTimeInMillis());
-
- GregorianCalendar utc = new GregorianCalendar(gmtTimeZone);
-
- utc.setTimeInMillis(local.getTimeInMillis());
- utc.add(Calendar.MILLISECOND, -offset);
-
- return utc.getTime();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-common/src/main/java/org/apache/ranger/admin/client/RangerAdminClient.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/admin/client/RangerAdminClient.java b/agents-common/src/main/java/org/apache/ranger/admin/client/RangerAdminClient.java
new file mode 100644
index 0000000..a9c2a9a
--- /dev/null
+++ b/agents-common/src/main/java/org/apache/ranger/admin/client/RangerAdminClient.java
@@ -0,0 +1,32 @@
+/*
+ * 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.admin.client;
+
+
+import org.apache.ranger.admin.client.datatype.GrantRevokeData;
+
+
+public interface RangerAdminClient {
+ String getPolicies(String repositoryName, long lastModifiedTime, int policyCount, String agentName);
+
+ void grantPrivilege(GrantRevokeData grData) throws Exception;
+
+ void revokePrivilege(GrantRevokeData grData) throws Exception;
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-common/src/main/java/org/apache/ranger/admin/client/RangerAdminRESTClient.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/admin/client/RangerAdminRESTClient.java b/agents-common/src/main/java/org/apache/ranger/admin/client/RangerAdminRESTClient.java
new file mode 100644
index 0000000..d883dd3
--- /dev/null
+++ b/agents-common/src/main/java/org/apache/ranger/admin/client/RangerAdminRESTClient.java
@@ -0,0 +1,389 @@
+/*
+ * 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.admin.client;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.List;
+import java.security.KeyManagementException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.CertificateException;
+
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+
+import com.sun.jersey.api.client.Client;
+import com.sun.jersey.api.client.ClientResponse;
+import com.sun.jersey.api.client.WebResource;
+import com.sun.jersey.api.client.config.ClientConfig;
+import com.sun.jersey.api.client.config.DefaultClientConfig;
+import com.sun.jersey.client.urlconnection.HTTPSProperties;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.ranger.admin.client.datatype.GrantRevokeData;
+import org.apache.ranger.admin.client.datatype.RESTResponse;
+import org.apache.ranger.authorization.hadoop.config.RangerConfiguration;
+import org.apache.ranger.authorization.hadoop.utils.RangerCredentialProvider;
+import org.apache.ranger.authorization.utils.StringUtil;
+
+
+public class RangerAdminRESTClient implements RangerAdminClient {
+ private static final Log LOG = LogFactory.getLog(RangerAdminRESTClient.class);
+
+ public static final String RANGER_PROP_POLICYMGR_URL = "xasecure.policymgr.url";
+ public static final String RANGER_PROP_POLICYMGR_SSLCONFIG_FILENAME = "xasecure.policymgr.sslconfig.filename";
+
+ public static final String RANGER_POLICYMGR_CLIENT_KEY_FILE = "xasecure.policymgr.clientssl.keystore";
+ public static final String RANGER_POLICYMGR_CLIENT_KEY_FILE_PASSWORD = "xasecure.policymgr.clientssl.keystore.password";
+ public static final String RANGER_POLICYMGR_CLIENT_KEY_FILE_TYPE = "xasecure.policymgr.clientssl.keystore.type";
+ public static final String RANGER_POLICYMGR_CLIENT_KEY_FILE_CREDENTIAL = "xasecure.policymgr.clientssl.keystore.credential.file";
+ public static final String RANGER_POLICYMGR_CLIENT_KEY_FILE_CREDENTIAL_ALIAS = "sslKeyStore";
+ public static final String RANGER_POLICYMGR_CLIENT_KEY_FILE_TYPE_DEFAULT = "jks";
+
+ public static final String RANGER_POLICYMGR_TRUSTSTORE_FILE = "xasecure.policymgr.clientssl.truststore";
+ public static final String RANGER_POLICYMGR_TRUSTSTORE_FILE_PASSWORD = "xasecure.policymgr.clientssl.truststore.password";
+ public static final String RANGER_POLICYMGR_TRUSTSTORE_FILE_TYPE = "xasecure.policymgr.clientssl.truststore.type";
+ public static final String RANGER_POLICYMGR_TRUSTSTORE_FILE_CREDENTIAL = "xasecure.policymgr.clientssl.truststore.credential.file";
+ public static final String RANGER_POLICYMGR_TRUSTSTORE_FILE_CREDENTIAL_ALIAS = "sslTrustStore";
+ public static final String RANGER_POLICYMGR_TRUSTSTORE_FILE_TYPE_DEFAULT = "jks";
+
+ public static final String RANGER_SSL_KEYMANAGER_ALGO_TYPE = "SunX509" ;
+ public static final String RANGER_SSL_TRUSTMANAGER_ALGO_TYPE = "SunX509" ;
+ public static final String RANGER_SSL_CONTEXT_ALGO_TYPE = "SSL" ;
+
+ public static final String REST_EXPECTED_MIME_TYPE = "application/json" ;
+
+ private static final String REST_URL_PATH_POLICYLIST = "/service/assets/policyList/";
+ private static final String REST_URL_PATH_GRANT = "/service/assets/resources/grant";
+ private static final String REST_URL_PATH_REVOKE = "/service/assets/resources/revoke";
+ private static final String REST_URL_PARAM_LASTUPDATED_TIME = "epoch";
+ private static final String REST_URL_PARAM_POLICY_COUNT = "policyCount";
+ private static final String REST_URL_PARAM_AGENT_NAME = "agentId";
+
+ private String mUrl = null;
+ private String mSslConfigFileName = null;
+ private boolean mIsSSL = false;
+
+ private String mKeyStoreURL = null;
+ private String mKeyStoreAlias = null;
+ private String mKeyStoreFile = null;
+ private String mKeyStoreType = null;
+ private String mTrustStoreURL = null;
+ private String mTrustStoreAlias = null;
+ private String mTrustStoreFile = null;
+ private String mTrustStoreType = null;
+
+
+ public RangerAdminRESTClient() {
+ mUrl = RangerConfiguration.getInstance().get(RANGER_PROP_POLICYMGR_URL);
+ mSslConfigFileName = RangerConfiguration.getInstance().get(RANGER_PROP_POLICYMGR_SSLCONFIG_FILENAME);
+
+ init();
+ }
+
+ public RangerAdminRESTClient(String url, String sslConfigFileName) {
+ mUrl = url;
+ mSslConfigFileName = sslConfigFileName;
+
+ init();
+ }
+
+ @Override
+ public String getPolicies(String repositoryName, long lastModifiedTime, int policyCount, String agentName) {
+ String ret = null;
+ Client client = null;
+
+ try {
+ client = buildClient();
+
+ WebResource webResource = client.resource(mUrl + REST_URL_PATH_POLICYLIST + repositoryName)
+ .queryParam(REST_URL_PARAM_LASTUPDATED_TIME, String.valueOf(lastModifiedTime))
+ .queryParam(REST_URL_PARAM_POLICY_COUNT, String.valueOf(policyCount))
+ .queryParam(REST_URL_PARAM_AGENT_NAME, agentName);
+
+ ClientResponse response = webResource.accept(REST_EXPECTED_MIME_TYPE).get(ClientResponse.class);
+
+ if(response != null && response.getStatus() == 200) {
+ ret = response.getEntity(String.class);
+ }
+ } finally {
+ destroy(client);
+ }
+
+ return ret;
+ }
+
+ @Override
+ public void grantPrivilege(GrantRevokeData grData) throws Exception {
+ Client client = null;
+
+ try {
+ client = buildClient();
+
+ WebResource webResource = client.resource(mUrl + REST_URL_PATH_GRANT);
+
+ ClientResponse response = webResource.accept(REST_EXPECTED_MIME_TYPE).type(REST_EXPECTED_MIME_TYPE).post(ClientResponse.class, grData.toJson());
+
+ if(response == null || response.getStatus() != 200) {
+ RESTResponse resp = RESTResponse.fromClientResponse(response);
+
+ throw new Exception(resp.getMessage());
+ }
+ } finally {
+ destroy(client);
+ }
+ }
+
+ @Override
+ public void revokePrivilege(GrantRevokeData grData) throws Exception {
+ Client client = null;
+
+ try {
+ client = buildClient();
+
+ WebResource webResource = client.resource(mUrl + REST_URL_PATH_REVOKE);
+
+ ClientResponse response = webResource.accept(REST_EXPECTED_MIME_TYPE).type(REST_EXPECTED_MIME_TYPE).post(ClientResponse.class, grData.toJson());
+
+ if(response == null || response.getStatus() != 200) {
+ RESTResponse resp = RESTResponse.fromClientResponse(response);
+
+ throw new Exception(resp.getMessage());
+ }
+ } finally {
+ destroy(client);
+ }
+ }
+ private void init() {
+ mIsSSL = StringUtil.containsIgnoreCase(mUrl, "https");
+
+ InputStream in = null ;
+
+ try {
+ Configuration conf = new Configuration() ;
+
+ in = getFileInputStream(mSslConfigFileName) ;
+
+ if (in != null) {
+ conf.addResource(in);
+ }
+
+ mKeyStoreURL = conf.get(RANGER_POLICYMGR_CLIENT_KEY_FILE_CREDENTIAL);
+ mKeyStoreAlias = RANGER_POLICYMGR_CLIENT_KEY_FILE_CREDENTIAL_ALIAS;
+ mKeyStoreType = conf.get(RANGER_POLICYMGR_CLIENT_KEY_FILE_TYPE, RANGER_POLICYMGR_CLIENT_KEY_FILE_TYPE_DEFAULT);
+ mKeyStoreFile = conf.get(RANGER_POLICYMGR_CLIENT_KEY_FILE);
+
+ mTrustStoreURL = conf.get(RANGER_POLICYMGR_TRUSTSTORE_FILE_CREDENTIAL);
+ mTrustStoreAlias = RANGER_POLICYMGR_TRUSTSTORE_FILE_CREDENTIAL_ALIAS;
+ mTrustStoreType = conf.get(RANGER_POLICYMGR_TRUSTSTORE_FILE_TYPE, RANGER_POLICYMGR_TRUSTSTORE_FILE_TYPE_DEFAULT);
+ mTrustStoreFile = conf.get(RANGER_POLICYMGR_TRUSTSTORE_FILE);
+ }
+ catch(IOException ioe) {
+ LOG.error("Unable to load SSL Config FileName: [" + mSslConfigFileName + "]", ioe);
+ }
+ finally {
+ close(in, mSslConfigFileName);
+ }
+ }
+
+ private synchronized Client buildClient() {
+ Client client = null;
+
+ if (mIsSSL) {
+ KeyManager[] kmList = getKeyManagers();
+ TrustManager[] tmList = getTrustManagers();
+ SSLContext sslContext = getSSLContext(kmList, tmList);
+ ClientConfig config = new DefaultClientConfig();
+
+ HostnameVerifier hv = new HostnameVerifier() {
+ public boolean verify(String urlHostName, SSLSession session) {
+ return session.getPeerHost().equals(urlHostName);
+ }
+ };
+
+ config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(hv, sslContext));
+
+ client = Client.create(config);
+ }
+
+ if(client == null) {
+ client = Client.create();
+ }
+
+ return client;
+ }
+
+ private KeyManager[] getKeyManagers() {
+ KeyManager[] kmList = null;
+
+ String keyStoreFilepwd = getCredential(mKeyStoreURL, mKeyStoreAlias);
+
+ if (!StringUtil.isEmpty(mKeyStoreFile) && !StringUtil.isEmpty(keyStoreFilepwd)) {
+ InputStream in = null ;
+
+ try {
+ in = getFileInputStream(mKeyStoreFile) ;
+
+ if (in != null) {
+ KeyStore keyStore = KeyStore.getInstance(mKeyStoreType);
+
+ keyStore.load(in, keyStoreFilepwd.toCharArray());
+
+ KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(RANGER_SSL_KEYMANAGER_ALGO_TYPE);
+
+ keyManagerFactory.init(keyStore, keyStoreFilepwd.toCharArray());
+
+ kmList = keyManagerFactory.getKeyManagers();
+ } else {
+ LOG.error("Unable to obtain keystore from file [" + mKeyStoreFile + "]");
+ }
+ } catch (KeyStoreException e) {
+ LOG.error("Unable to obtain from KeyStore", e);
+ } catch (NoSuchAlgorithmException e) {
+ LOG.error("SSL algorithm is available in the environment", e);
+ } catch (CertificateException e) {
+ LOG.error("Unable to obtain the requested certification ", e);
+ } catch (FileNotFoundException e) {
+ LOG.error("Unable to find the necessary SSL Keystore and TrustStore Files", e);
+ } catch (IOException e) {
+ LOG.error("Unable to read the necessary SSL Keystore and TrustStore Files", e);
+ } catch (UnrecoverableKeyException e) {
+ LOG.error("Unable to recover the key from keystore", e);
+ } finally {
+ close(in, mKeyStoreFile);
+ }
+ }
+
+ return kmList;
+ }
+
+ private TrustManager[] getTrustManagers() {
+ TrustManager[] tmList = null;
+
+ String trustStoreFilepwd = getCredential(mTrustStoreURL, mTrustStoreAlias);
+
+ if (!StringUtil.isEmpty(mTrustStoreFile) && !StringUtil.isEmpty(trustStoreFilepwd)) {
+ InputStream in = null ;
+
+ try {
+ in = getFileInputStream(mTrustStoreFile) ;
+
+ if (in != null) {
+ KeyStore trustStore = KeyStore.getInstance(mTrustStoreType);
+
+ trustStore.load(in, trustStoreFilepwd.toCharArray());
+
+ TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(RANGER_SSL_TRUSTMANAGER_ALGO_TYPE);
+
+ trustManagerFactory.init(trustStore);
+
+ tmList = trustManagerFactory.getTrustManagers();
+ } else {
+ LOG.error("Unable to obtain keystore from file [" + mTrustStoreFile + "]");
+ }
+ } catch (KeyStoreException e) {
+ LOG.error("Unable to obtain from KeyStore", e);
+ } catch (NoSuchAlgorithmException e) {
+ LOG.error("SSL algorithm is available in the environment", e);
+ } catch (CertificateException e) {
+ LOG.error("Unable to obtain the requested certification ", e);
+ } catch (FileNotFoundException e) {
+ LOG.error("Unable to find the necessary SSL Keystore and TrustStore Files", e);
+ } catch (IOException e) {
+ LOG.error("Unable to read the necessary SSL Keystore and TrustStore Files", e);
+ } finally {
+ close(in, mTrustStoreFile);
+ }
+ }
+
+ return tmList;
+ }
+
+ private SSLContext getSSLContext(KeyManager[] kmList, TrustManager[] tmList) {
+ try {
+ if(kmList != null && tmList != null) {
+ SSLContext sslContext = SSLContext.getInstance(RANGER_SSL_CONTEXT_ALGO_TYPE);
+
+ sslContext.init(kmList, tmList, new SecureRandom());
+
+ return sslContext;
+ }
+ } catch (NoSuchAlgorithmException e) {
+ LOG.error("SSL algorithm is available in the environment", e);
+ } catch (KeyManagementException e) {
+ LOG.error("Unable to initials the SSLContext", e);
+ }
+
+ return null;
+ }
+
+ private String getCredential(String url, String alias) {
+ char[] credStr = RangerCredentialProvider.getInstance().getCredentialString(url, alias);
+
+ return credStr == null ? null : new String(credStr);
+ }
+
+ private InputStream getFileInputStream(String fileName) throws IOException {
+ InputStream in = null ;
+
+ if(! StringUtil.isEmpty(fileName)) {
+ File f = new File(fileName) ;
+
+ if (f.exists()) {
+ in = new FileInputStream(f) ;
+ }
+ else {
+ in = ClassLoader.getSystemResourceAsStream(fileName) ;
+ }
+ }
+
+ return in ;
+ }
+
+ private void close(InputStream str, String filename) {
+ if (str != null) {
+ try {
+ str.close() ;
+ } catch (IOException excp) {
+ LOG.error("Error while closing file: [" + filename + "]", excp) ;
+ }
+ }
+ }
+
+ private void destroy(Client client) {
+ if(client != null) {
+ client.destroy();
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-common/src/main/java/org/apache/ranger/admin/client/datatype/GrantRevokeData.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/admin/client/datatype/GrantRevokeData.java b/agents-common/src/main/java/org/apache/ranger/admin/client/datatype/GrantRevokeData.java
new file mode 100644
index 0000000..b9496be
--- /dev/null
+++ b/agents-common/src/main/java/org/apache/ranger/admin/client/datatype/GrantRevokeData.java
@@ -0,0 +1,272 @@
+/*
+ * 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.admin.client.datatype;
+
+
+import java.io.IOException;
+import java.util.List;
+import java.util.ArrayList;
+
+import org.apache.ranger.authorization.utils.StringUtil;
+import org.codehaus.jackson.JsonGenerationException;
+import org.codehaus.jackson.annotate.JsonAutoDetect;
+import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
+import org.codehaus.jackson.annotate.JsonIgnoreProperties;
+import org.codehaus.jackson.map.annotate.JsonSerialize;
+import org.codehaus.jackson.map.JsonMappingException;
+import org.codehaus.jackson.map.ObjectMapper;
+
+
+@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY)
+@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class GrantRevokeData implements java.io.Serializable {
+ private static final long serialVersionUID = 1L;
+
+ private String grantor;
+ private String repositoryName;
+ private String repositoryType;
+ private String databases;
+ private String tables;
+ private String columns;
+ private String columnFamilies;
+ private boolean isEnabled;
+ private boolean isAuditEnabled;
+ private boolean replacePerm;
+ private List<PermMap> permMapList = new ArrayList<PermMap>();
+
+ private static String WILDCARD_ASTERISK = "*";
+
+
+ public GrantRevokeData() {
+ }
+
+ public String getGrantor() {
+ return grantor;
+ }
+
+ public void setGrantor(String grantor) {
+ this.grantor = grantor;
+ }
+
+ public String getRepositoryName() {
+ return repositoryName;
+ }
+
+ public void setRepositoryName(String repositoryName) {
+ this.repositoryName = repositoryName;
+ }
+
+ public String getRepositoryType() {
+ return repositoryType;
+ }
+
+ public void setRepositoryType(String repositoryType) {
+ this.repositoryType = repositoryType;
+ }
+
+ public String getDatabases() {
+ return databases;
+ }
+
+ public void setDatabases(String databases) {
+ this.databases = databases;
+ }
+
+ public String getTables() {
+ return tables;
+ }
+
+ public void setTables(String tables) {
+ this.tables = tables;
+ }
+
+ public String getColumns() {
+ return columns;
+ }
+
+ public void setColumns(String columns) {
+ this.columns = columns;
+ }
+
+ public String getColumnFamilies() {
+ return columnFamilies;
+ }
+
+ public void setColumnFamilies(String columnFamilies) {
+ this.columnFamilies = columnFamilies;
+ }
+
+ public List<PermMap> getPermMapList() {
+ return permMapList;
+ }
+
+ public void setPermMapList(List<PermMap> permMapList) {
+ this.permMapList = permMapList;
+ }
+
+
+ public void setHiveData(String grantor,
+ String repositoryName,
+ String databases,
+ String tables,
+ String columns,
+ PermMap permMap) {
+ this.grantor = grantor;
+ this.repositoryName = repositoryName;
+ this.repositoryType = "hive";
+ this.databases = StringUtil.isEmpty(databases) ? WILDCARD_ASTERISK : databases;
+ this.tables = StringUtil.isEmpty(tables) ? WILDCARD_ASTERISK : tables;
+ this.columns = StringUtil.isEmpty(columns) ? WILDCARD_ASTERISK : columns;
+ this.isAuditEnabled = true;
+ this.isEnabled = true;
+ this.replacePerm = false;
+ this.permMapList.add(permMap);
+ }
+
+ public void setHBaseData(String grantor,
+ String repositoryName,
+ String tables,
+ String columns,
+ String columnFamilies,
+ PermMap permMap) {
+ this.grantor = grantor;
+ this.repositoryName = repositoryName;
+ this.repositoryType = "hbase";
+ this.tables = StringUtil.isEmpty(tables) ? WILDCARD_ASTERISK : tables;
+ this.columns = StringUtil.isEmpty(columns) ? WILDCARD_ASTERISK : columns;
+ this.columnFamilies = StringUtil.isEmpty(columnFamilies) ? WILDCARD_ASTERISK : columnFamilies;
+ this.isAuditEnabled = true;
+ this.isEnabled = true;
+ this.replacePerm = true;
+ this.permMapList.add(permMap);
+ }
+
+ public String toJson() {
+ try {
+ ObjectMapper om = new ObjectMapper();
+
+ return om.writeValueAsString(this);
+ } catch (JsonGenerationException e) {
+ e.printStackTrace();
+ } catch (JsonMappingException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ return "";
+ }
+
+ @Override
+ public String toString() {
+ return toJson();
+ }
+
+
+ @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY)
+ @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ public static class PermMap {
+ private List<String> userList = new ArrayList<String>();
+ private List<String> groupList = new ArrayList<String>();
+ private List<String> permList = new ArrayList<String>();
+
+ public PermMap() {
+ }
+
+ public PermMap(String user, String group, String perm) {
+ addUser(user);
+ addGroup(group);
+ addPerm(perm);
+ }
+
+ public PermMap(List<String> userList, List<String> groupList, List<String> permList) {
+ copyList(userList, this.userList);
+ copyList(groupList, this.groupList);
+ copyList(permList, this.permList);
+ }
+
+ public List<String> getUserList() {
+ return userList;
+ }
+
+ public List<String> getGroupList() {
+ return groupList;
+ }
+
+ public List<String> getPermList() {
+ return permList;
+ }
+
+ public void addUser(String user) {
+ addToList(user, userList);
+ }
+
+ public void addGroup(String group) {
+ addToList(group, groupList);
+ }
+
+ public void addPerm(String perm) {
+ addToList(perm, permList);
+ }
+
+ private void addToList(String str, List<String> list) {
+ if(list != null && !StringUtil.isEmpty(str)) {
+ list.add(str);
+ }
+ }
+
+ private void copyList(List<String> fromList, List<String> toList) {
+ if(fromList != null && toList != null) {
+ for(String str : fromList) {
+ addToList(str, toList);
+ }
+ }
+ }
+
+ public String toJson() {
+ try {
+ ObjectMapper om = new ObjectMapper();
+
+ return om.writeValueAsString(this);
+ } catch (JsonGenerationException e) {
+ e.printStackTrace();
+ } catch (JsonMappingException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ return "";
+ }
+
+ @Override
+ public String toString() {
+ return toJson();
+ }
+ }
+
+ public static void main(String[] args) {
+ GrantRevokeData grData = new GrantRevokeData();
+
+ System.out.println(grData.toString());
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-common/src/main/java/org/apache/ranger/admin/client/datatype/RESTResponse.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/admin/client/datatype/RESTResponse.java b/agents-common/src/main/java/org/apache/ranger/admin/client/datatype/RESTResponse.java
new file mode 100644
index 0000000..6f0547f
--- /dev/null
+++ b/agents-common/src/main/java/org/apache/ranger/admin/client/datatype/RESTResponse.java
@@ -0,0 +1,208 @@
+/**
+ *
+ * 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.admin.client.datatype;
+
+import java.util.List;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.authorization.utils.StringUtil;
+import org.codehaus.jackson.annotate.JsonAutoDetect;
+import org.codehaus.jackson.annotate.JsonIgnoreProperties;
+import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.codehaus.jackson.map.annotate.JsonSerialize;
+
+import com.sun.jersey.api.client.ClientResponse;
+
+
+@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY)
+@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class RESTResponse {
+ private static Logger LOG = Logger.getLogger(RESTResponse.class);
+
+ private int httpStatusCode;
+ private int statusCode;
+ private String msgDesc;
+ private List<Message> messageList;
+
+
+ public int getHttpStatusCode() {
+ return httpStatusCode;
+ }
+
+ public void setHttpStatusCode(int httpStatusCode) {
+ this.httpStatusCode = httpStatusCode;
+ }
+
+ public int getStatusCode() {
+ return statusCode;
+ }
+
+ public void setStatusCode(int statusCode) {
+ this.statusCode = statusCode;
+ }
+
+ public String getMsgDesc() {
+ return msgDesc;
+ }
+
+ public void setMsgDesc(String msgDesc) {
+ this.msgDesc = msgDesc;
+ }
+
+ public List<Message> getMessageList() {
+ return messageList;
+ }
+
+ public void setMessageList(List<Message> messageList) {
+ this.messageList = messageList;
+ }
+
+ public String getMessage() {
+ return StringUtil.isEmpty(msgDesc) ? ("HTTP " + httpStatusCode) : msgDesc;
+ }
+
+ public static RESTResponse fromClientResponse(ClientResponse response) {
+ RESTResponse ret = null;
+
+ String jsonString = response == null ? null : response.getEntity(String.class);
+ int httpStatus = response == null ? 0 : response.getStatus();
+
+ if(! StringUtil.isEmpty(jsonString)) {
+ ret = RESTResponse.fromJson(jsonString);
+ }
+
+ if(ret == null) {
+ ret = new RESTResponse();
+ }
+
+ ret.setHttpStatusCode(httpStatus);
+
+ return ret;
+ }
+
+ public String toJson() {
+ try {
+ ObjectMapper om = new ObjectMapper();
+
+ return om.writeValueAsString(this);
+ } catch (Exception e) {
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("toJson() failed", e);
+ }
+ }
+
+ return "";
+ }
+
+ public static RESTResponse fromJson(String jsonString) {
+ try {
+ ObjectMapper om = new ObjectMapper();
+
+ return om.readValue(jsonString, RESTResponse.class);
+ } catch (Exception e) {
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("fromJson('" + jsonString + "') failed", e);
+ }
+ }
+
+ return null;
+ }
+
+ @Override
+ public String toString() {
+ return toJson();
+ }
+
+ @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY)
+ @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ public static class Message {
+ private String name;
+ private String rbKey;
+ private String message;
+ private Long objectId;
+ private String fieldName;
+
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+ public String getRbKey() {
+ return rbKey;
+ }
+ public void setRbKey(String rbKey) {
+ this.rbKey = rbKey;
+ }
+ public String getMessage() {
+ return message;
+ }
+ public void setMessage(String message) {
+ this.message = message;
+ }
+ public Long getObjectId() {
+ return objectId;
+ }
+ public void setObjectId(Long objectId) {
+ this.objectId = objectId;
+ }
+ public String getFieldName() {
+ return fieldName;
+ }
+ public void setFieldName(String fieldName) {
+ this.fieldName = fieldName;
+ }
+
+ public String toJson() {
+ try {
+ ObjectMapper om = new ObjectMapper();
+
+ return om.writeValueAsString(this);
+ } catch (Exception e) {
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("toJson() failed", e);
+ }
+ }
+
+ return "";
+ }
+
+ public static RESTResponse fromJson(String jsonString) {
+ try {
+ ObjectMapper om = new ObjectMapper();
+
+ return om.readValue(jsonString, RESTResponse.class);
+ } catch (Exception e) {
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("fromJson('" + jsonString + "') failed", e);
+ }
+ }
+
+ return null;
+ }
+
+ @Override
+ public String toString() {
+ return toJson();
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-common/src/main/java/org/apache/ranger/authorization/hadoop/config/RangerConfiguration.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/authorization/hadoop/config/RangerConfiguration.java b/agents-common/src/main/java/org/apache/ranger/authorization/hadoop/config/RangerConfiguration.java
new file mode 100644
index 0000000..a959b6b
--- /dev/null
+++ b/agents-common/src/main/java/org/apache/ranger/authorization/hadoop/config/RangerConfiguration.java
@@ -0,0 +1,164 @@
+/*
+ * 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.authorization.hadoop.config;
+
+import java.io.File;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Properties;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.log4j.Logger;
+import org.apache.ranger.audit.provider.AuditProviderFactory;
+import org.apache.ranger.authorization.hadoop.constants.RangerHadoopConstants;
+
+public class RangerConfiguration extends Configuration {
+
+ private static final Logger LOG = Logger.getLogger(RangerConfiguration.class) ;
+
+ private static RangerConfiguration config = null;
+
+ private RangerConfiguration() {
+ super(false) ;
+
+ //
+ // WorkAround for having all Hadoop Configuration in the CLASSPATH first, even if it is invoked by Hive Engine.
+ //
+ // So, we look for "hive-site.xml", if it is available, take the xasecure-audit.xml file from the same location.
+ // If we do not see "hive-site.xml", we look for "hbase-site.xml", if found, take the xasecure-audit.xml file from the same location.
+ // If we do not see "hbase-site.xml", we look for "hdfs-site.xml", if found, take the xasecure-audit.xml file from the same location.
+ // If we do not see, we let the CLASSPATH based search to find xasecure-audit.xml file.
+
+
+ URL auditFileLocation = getRangerAuditXMLFileLocation() ;
+
+ if (auditFileLocation != null) {
+ addResource(auditFileLocation) ;
+ }
+ else {
+ addResourceIfReadable(RangerHadoopConstants.RANGER_AUDIT_FILE) ;
+ }
+ addResourceIfReadable(RangerHadoopConstants.RANGER_HDFS_SECURITY_FILE);
+ addResourceIfReadable(RangerHadoopConstants.RANGER_KNOX_SECURITY_FILE);
+ addResourceIfReadable(RangerHadoopConstants.RANGER_HBASE_SECURITY_FILE) ;
+ addResourceIfReadable(RangerHadoopConstants.RANGER_HIVE_SECURITY_FILE) ;
+ addResourceIfReadable(RangerHadoopConstants.RANGER_STORM_SECURITY_FILE);
+
+ }
+
+ @SuppressWarnings("deprecation")
+ private void addResourceIfReadable(String aResourceName) {
+ String fName = getFileLocation(aResourceName) ;
+ if (fName != null) {
+ File f = new File(fName) ;
+ if (f.exists() && f.canRead()) {
+ URL fUrl = null ;
+ try {
+ fUrl = f.toURL() ;
+ addResource(fUrl) ;
+ } catch (MalformedURLException e) {
+ LOG.debug("Unable to find URL for the resource name [" + aResourceName +"]. Ignoring the resource:" + aResourceName);
+ }
+ }
+ }
+ }
+
+
+ public static RangerConfiguration getInstance() {
+ if (config == null) {
+ synchronized (RangerConfiguration.class) {
+ RangerConfiguration temp = config;
+ if (temp == null) {
+ config = new RangerConfiguration();
+ }
+ }
+ }
+ return config;
+ }
+
+ public void initAudit(AuditProviderFactory.ApplicationType appType) {
+ AuditProviderFactory auditFactory = AuditProviderFactory.getInstance();
+
+ if(auditFactory == null) {
+ LOG.error("Unable to find the AuditProviderFactory. (null) found") ;
+ return;
+ }
+
+ Properties props = getProps();
+
+ if(props == null) {
+ return;
+ }
+
+ if(! auditFactory.isInitDone()) {
+ auditFactory.init(props, appType);
+ }
+ }
+
+ public boolean isAuditInitDone() {
+ AuditProviderFactory auditFactory = AuditProviderFactory.getInstance();
+
+ return auditFactory != null && auditFactory.isInitDone();
+ }
+
+
+ @SuppressWarnings("deprecation")
+ public URL getRangerAuditXMLFileLocation() {
+ URL ret = null ;
+
+ try {
+ for(String cfgFile : new String[] { "hive-site.xml", "hbase-site.xml", "hdfs-site.xml" } ) {
+ String loc = getFileLocation(cfgFile) ;
+ if (loc != null) {
+ if (new File(loc).canRead()) {
+ File parentFile = new File(loc).getParentFile() ;
+ ret = new File(parentFile, RangerHadoopConstants.RANGER_AUDIT_FILE).toURL() ;
+ break ;
+ }
+ }
+ }
+ }
+ catch(Throwable t) {
+ LOG.error("Unable to locate audit file location." , t) ;
+ ret = null ;
+ }
+
+ return ret ;
+ }
+
+ private String getFileLocation(String fileName) {
+
+ String ret = null ;
+
+ URL lurl = RangerConfiguration.class.getClassLoader().getResource(fileName) ;
+
+ if (lurl == null ) {
+ lurl = RangerConfiguration.class.getClassLoader().getResource("/" + fileName) ;
+ }
+
+ if (lurl != null) {
+ ret = lurl.getFile() ;
+ }
+
+ return ret ;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-common/src/main/java/org/apache/ranger/authorization/hadoop/constants/RangerHadoopConstants.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/authorization/hadoop/constants/RangerHadoopConstants.java b/agents-common/src/main/java/org/apache/ranger/authorization/hadoop/constants/RangerHadoopConstants.java
new file mode 100644
index 0000000..d87057d
--- /dev/null
+++ b/agents-common/src/main/java/org/apache/ranger/authorization/hadoop/constants/RangerHadoopConstants.java
@@ -0,0 +1,89 @@
+/**
+ * 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.authorization.hadoop.constants;
+
+public class RangerHadoopConstants {
+
+ public static final String RANGER_AUDIT_FILE = "xasecure-audit.xml" ;
+ public static final String RANGER_HDFS_SECURITY_FILE = "xasecure-hdfs-security.xml" ;
+ public static final String RANGER_KNOX_SECURITY_FILE = "xasecure-knox-security.xml" ;
+ public static final String RANGER_HBASE_SECURITY_FILE = "xasecure-hbase-security.xml" ;
+ public static final String RANGER_HIVE_SECURITY_FILE = "xasecure-hive-security.xml" ;
+ public static final String RANGER_POLICYMGR_SSL_FILE = "xasecure-policymgr-ssl.xml" ;
+ public static final String RANGER_STORM_SECURITY_FILE = "xasecure-storm-security.xml" ;
+
+ public static final String RANGER_ADD_HDFS_PERMISSION_PROP = "xasecure.add-hadoop-authorization" ;
+ public static final boolean RANGER_ADD_HDFS_PERMISSION_DEFAULT = false ;
+ public static final String READ_ACCCESS_TYPE = "read";
+ public static final String WRITE_ACCCESS_TYPE = "write";
+ public static final String EXECUTE_ACCCESS_TYPE = "execute";
+
+ public static final String HDFS_ROOT_FOLDER_PATH_ALT = "";
+ public static final String HDFS_ROOT_FOLDER_PATH = "/";
+
+ public static final String HDFS_ACCESS_VERIFIER_CLASS_NAME_PROP = "hdfs.authorization.verifier.classname" ;
+ public static final String HDFS_ACCESS_VERIFIER_CLASS_NAME_DEFAULT_VALUE = "org.apache.ranger.pdp.hdfs.RangerAuthorizer" ;
+
+ public static final String HIVE_ACCESS_VERIFIER_CLASS_NAME_PROP = "hive.authorization.verifier.classname" ;
+ public static final String HIVE_ACCESS_VERIFIER_CLASS_NAME_DEFAULT_VALUE = "org.apache.ranger.pdp.hive.RangerAuthorizer" ;
+
+ public static final String HIVE_UPDATE_RANGER_POLICIES_ON_GRANT_REVOKE_PROP = "xasecure.hive.update.xapolicies.on.grant.revoke" ;
+ public static final boolean HIVE_UPDATE_RANGER_POLICIES_ON_GRANT_REVOKE_DEFAULT_VALUE = true;
+
+ public static final String HBASE_UPDATE_RANGER_POLICIES_ON_GRANT_REVOKE_PROP = "xasecure.hbase.update.xapolicies.on.grant.revoke" ;
+ public static final boolean HBASE_UPDATE_RANGER_POLICIES_ON_GRANT_REVOKE_DEFAULT_VALUE = true;
+
+ public static final String KNOX_ACCESS_VERIFIER_CLASS_NAME_PROP = "knox.authorization.verifier.classname" ;
+ public static final String KNOX_ACCESS_VERIFIER_CLASS_NAME_DEFAULT_VALUE = "org.apache.ranger.pdp.knox.RangerAuthorizer" ;
+
+ public static final String HBASE_ACCESS_VERIFIER_CLASS_NAME_PROP = "hbase.authorization.verifier.classname" ;
+ public static final String HBASE_ACCESS_VERIFIER_CLASS_NAME_DEFAULT_VALUE = "org.apache.ranger.pdp.hbase.RangerAuthorizer" ;
+
+ public static final String STORM_ACCESS_VERIFIER_CLASS_NAME_PROP = "storm.authorization.verifier.classname" ;
+ public static final String STORM_ACCESS_VERIFIER_CLASS_NAME_DEFAULT_VALUE = "org.apache.ranger.pdp.storm.RangerAuthorizer" ;
+
+ //
+ // Loging constants
+ //
+ public static final String AUDITLOG_FIELD_DELIMITER_PROP = "xasecure.auditlog.fieldDelimiterString";
+ public static final String AUDITLOG_RANGER_MODULE_ACL_NAME_PROP = "xasecure.auditlog.xasecureAcl.name" ;
+ public static final String AUDITLOG_HADOOP_MODULE_ACL_NAME_PROP = "xasecure.auditlog.hadoopAcl.name" ;
+
+ public static final String DEFAULT_LOG_FIELD_DELIMITOR = "|" ;
+ public static final String DEFAULT_RANGER_MODULE_ACL_NAME = "xasecure-acl" ;
+ public static final String DEFAULT_HADOOP_MODULE_ACL_NAME = "hadoop-acl" ;
+
+
+ public static final String AUDITLOG_FIELDINFO_VISIBLE_PROP = "xasecure.auditlog.fieldInfoVisible" ;
+ public static final boolean DEFAULT_AUDITLOG_FIELDINFO_VISIBLE = false ;
+
+ public static final String AUDITLOG_ACCESS_GRANTED_TEXT_PROP = "xasecure.auditlog.accessgranted.text" ;
+ public static final String AUDITLOG_ACCESS_DENIED_TEXT_PROP = "xasecure.auditlog.accessdenied.text" ;
+
+ public static final String DEFAULT_ACCESS_GRANTED_TEXT = "granted" ;
+ public static final String DEFAULT_ACCESS_DENIED_TEXT = "denied" ;
+
+ public static final String AUDITLOG_EMPTY_STRING = "" ;
+
+ public static final String AUDITLOG_HDFS_EXCLUDE_LIST_PROP = "xasecure.auditlog.hdfs.excludeusers" ;
+ public static final String AUDITLOG_REPOSITORY_NAME_PROP = "xasecure.audit.repository.name" ;
+ public static final String AUDITLOG_IS_ENABLED_PROP = "xasecure.audit.is.enabled" ;
+
+ public static final String KEYMGR_URL_PROP = "hdfs.keymanager.url" ;
+}
[15/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XPermMapService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XPermMapService.java b/security-admin/src/main/java/com/xasecure/service/XPermMapService.java
deleted file mode 100644
index 94f458e..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XPermMapService.java
+++ /dev/null
@@ -1,316 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-import com.xasecure.common.SearchCriteria;
-import com.xasecure.common.SearchField;
-
-import org.apache.commons.lang.ArrayUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Service;
-
-import com.xasecure.common.AppConstants;
-import com.xasecure.common.view.VTrxLogAttr;
-import com.xasecure.db.XADaoManager;
-import com.xasecure.entity.*;
-import com.xasecure.util.XAEnumUtil;
-import com.xasecure.view.*;
-
-@Service
-@Scope("singleton")
-public class XPermMapService extends XPermMapServiceBase<XXPermMap, VXPermMap> {
-
- @Autowired
- XGroupService xGroupService;
-
- @Autowired
- XUserService xUserService;
-
- @Autowired
- XAEnumUtil xaEnumUtil;
-
- @Autowired
- XADaoManager xADaoManager;
-
- static HashMap<String, VTrxLogAttr> trxLogAttrs = new HashMap<String, VTrxLogAttr>();
- static {
-// trxLogAttrs.put("groupId", new VTrxLogAttr("groupId", "Group Permission", false));
-// trxLogAttrs.put("userId", new VTrxLogAttr("userId", "User Permission", false));
- trxLogAttrs.put("permType", new VTrxLogAttr("permType", "Permission Type", true));
- trxLogAttrs.put("ipAddress", new VTrxLogAttr("ipAddress", "IP Address", false));
- }
-
-
- public XPermMapService() {
- searchFields.add(new SearchField("resourceId", "obj.resourceId",
- SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
- searchFields.add(new SearchField("permType", "obj.permType",
- SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
- searchFields.add(new SearchField("permFor", "obj.permFor",
- SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
- searchFields.add(new SearchField("userId", "obj.userId",
- SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
- searchFields.add(new SearchField("groupId", "obj.groupId",
- SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
- }
-
- @Override
- protected void validateForCreate(VXPermMap vObj) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void validateForUpdate(VXPermMap vObj, XXPermMap mObj) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public VXPermMap populateViewBean(XXPermMap xXPermMap){
- VXPermMap map = super.populateViewBean(xXPermMap);
- if(map.getPermFor() == AppConstants.XA_PERM_FOR_GROUP) {
- String groupName = getGroupName(map.getGroupId());
- if(groupName != null){
- map.setGroupName(groupName);
- }
- } else if(map.getPermFor() == AppConstants.XA_PERM_FOR_USER) {
- String username = getUserName(map.getUserId());
- if(username != null){
- map.setUserName(username);
- }
- }
- return map;
- }
-
- @Override
- public VXPermMapList searchXPermMaps(SearchCriteria searchCriteria) {
- VXPermMapList vXPermMapList = super.searchXPermMaps(searchCriteria);
- if(vXPermMapList != null && vXPermMapList.getResultSize() != 0){
- for(VXPermMap vXPermMap : vXPermMapList.getVXPermMaps()){
- if(vXPermMap.getPermFor() == AppConstants.XA_PERM_FOR_GROUP) {
- String groupName = getGroupName(vXPermMap.getGroupId());
- vXPermMap.setGroupName(groupName);
- } else if(vXPermMap.getPermFor() == AppConstants.XA_PERM_FOR_USER) {
- String username = getUserName(vXPermMap.getUserId());
- vXPermMap.setUserName(username);
- }
- }
- }
- return vXPermMapList;
- }
-
- public String getGroupName(Long groupId){
- if(groupId!=null && groupId!=0){
- VXGroup vXGroup = xGroupService.readResource(groupId);
- return vXGroup.getName();
- }
- else
- return null;
- }
-
- public String getUserName(Long userId){
- if(userId!=null && userId!=0){
- VXUser vXUser = xUserService.readResource(userId);
- return vXUser.getName();
- }
- else
- return null;
- }
-
- public List<XXTrxLog> getTransactionLog(VXPermMap vXPermMap, String action){
- return getTransactionLog(vXPermMap, null, action);
- }
-
- public List<XXTrxLog> getTransactionLog(VXPermMap vObj, VXPermMap mObj, String action){
- if(vObj == null && (action == null || !action.equalsIgnoreCase("update"))){
- return null;
- }
-
- boolean isGroupPolicy = true;
- if(vObj.getGroupId() == null){
- isGroupPolicy = false;
- }
-
- Long groupId = null;
- Long userId = null;
- String groupName = null;
- String userName = null;
-
- if(isGroupPolicy){
- groupId = vObj.getGroupId();
- XXGroup xGroup = xADaoManager.getXXGroup().getById(groupId);
- groupName = xGroup.getName();
- } else {
- userId = vObj.getUserId();
- XXUser xUser = xADaoManager.getXXUser().getById(userId);
- userName = xUser.getName();
- }
-
- List<XXTrxLog> trxLogList = new ArrayList<XXTrxLog>();
- Field[] fields = vObj.getClass().getDeclaredFields();
-
- try {
- for(Field field : fields){
- field.setAccessible(true);
- String fieldName = field.getName();
- if(!trxLogAttrs.containsKey(fieldName)){
- continue;
-// int policyType = vObj.getIpAddress();
- /*if(policyType == AppConstants.ASSET_HDFS){
- String[] ignoredAttribs = {"ipAddress"};
- if(ArrayUtils.contains(ignoredAttribs, fieldName)){
- continue;
- }
- }*/
-// } else {
-// if(isGroupPolicy){
-// if(fieldName.equalsIgnoreCase("userId")){
-// continue;
-// }
-// } else {
-// if (fieldName.equalsIgnoreCase("groupId")){
-// continue;
-// }
-// }
- }
- Long assetId = xADaoManager.getXXResource().getById(vObj.getResourceId()).getAssetId();
- int policyType = xADaoManager.getXXAsset().getById(assetId).getAssetType();
- if(policyType != AppConstants.ASSET_KNOX){
- if(fieldName.equals("ipAddress"))
- continue;
- }
-
- VTrxLogAttr vTrxLogAttr = trxLogAttrs.get(fieldName);
-
- XXTrxLog xTrxLog = new XXTrxLog();
- xTrxLog.setAttributeName(vTrxLogAttr.getAttribUserFriendlyName());
-
- String value = null,prevValue = "";
- boolean isEnum = vTrxLogAttr.isEnum();
- if(isEnum){
- String enumName = XXPermMap.getEnumName(fieldName);
- int enumValue = field.get(vObj) == null ? 0 : Integer.parseInt(""+field.get(vObj));
- value = xaEnumUtil.getLabel(enumName, enumValue);
- } else {
- value = ""+field.get(vObj);
-// XXUser xUser = xADaoManager.getXXUser().getById(Long.parseLong(value));
-// value = xUser.getName();
- if(fieldName.equals("ipAddress") && action.equalsIgnoreCase("update")){
- prevValue = ""+field.get(mObj);
- value = value.equalsIgnoreCase("null") ? "" : value;
- }
- else if(value == null || value.equalsIgnoreCase("null") || stringUtil.isEmpty(value)){
- continue;
- }
- }
-
- if(action.equalsIgnoreCase("create")){
- xTrxLog.setNewValue(value);
- } else if(action.equalsIgnoreCase("delete")){
- xTrxLog.setPreviousValue(value);
- } else if(action.equalsIgnoreCase("update")){
- // Not Changed.
- xTrxLog.setNewValue(value);
- xTrxLog.setPreviousValue(value);
- if(fieldName.equals("ipAddress")){
- xTrxLog.setPreviousValue(prevValue);
- }
- }
-
- xTrxLog.setAction(action);
- xTrxLog.setObjectClassType(AppConstants.CLASS_TYPE_XA_PERM_MAP);
- xTrxLog.setObjectId(vObj.getId());
- if(isGroupPolicy){
- xTrxLog.setParentObjectClassType(AppConstants.CLASS_TYPE_XA_GROUP);
- xTrxLog.setParentObjectId(groupId);
- xTrxLog.setParentObjectName(groupName);
- } else {
- xTrxLog.setParentObjectClassType(AppConstants.CLASS_TYPE_XA_USER);
- xTrxLog.setParentObjectId(userId);
- xTrxLog.setParentObjectName(userName);
- }
-// xTrxLog.setObjectName(objectName);
- trxLogList.add(xTrxLog);
-
- }
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (SecurityException e) {
- e.printStackTrace();
- }
-
- return trxLogList;
- }
-
- @Override
- protected XXPermMap mapViewToEntityBean(VXPermMap vObj, XXPermMap mObj, int OPERATION_CONTEXT) {
- super.mapViewToEntityBean(vObj, mObj, OPERATION_CONTEXT);
- if(vObj!=null && mObj!=null){
- XXPortalUser xXPortalUser=null;
- if(mObj.getAddedByUserId()==null || mObj.getAddedByUserId()==0){
- if(!stringUtil.isEmpty(vObj.getOwner())){
- xXPortalUser=xADaoManager.getXXPortalUser().findByLoginId(vObj.getOwner());
- if(xXPortalUser!=null){
- mObj.setAddedByUserId(xXPortalUser.getId());
- }
- }
- }
- if(mObj.getUpdatedByUserId()==null || mObj.getUpdatedByUserId()==0){
- if(!stringUtil.isEmpty(vObj.getUpdatedBy())){
- xXPortalUser= xADaoManager.getXXPortalUser().findByLoginId(vObj.getUpdatedBy());
- if(xXPortalUser!=null){
- mObj.setUpdatedByUserId(xXPortalUser.getId());
- }
- }
- }
- }
- return mObj;
- }
-
- @Override
- protected VXPermMap mapEntityToViewBean(VXPermMap vObj, XXPermMap mObj) {
- super.mapEntityToViewBean(vObj, mObj);
- if(mObj!=null && vObj!=null){
- XXPortalUser xXPortalUser=null;
- if(stringUtil.isEmpty(vObj.getOwner())){
- xXPortalUser= xADaoManager.getXXPortalUser().getById(mObj.getAddedByUserId());
- if(xXPortalUser!=null){
- vObj.setOwner(xXPortalUser.getLoginId());
- }
- }
- if(stringUtil.isEmpty(vObj.getUpdatedBy())){
- xXPortalUser= xADaoManager.getXXPortalUser().getById(mObj.getUpdatedByUserId());
- if(xXPortalUser!=null){
- vObj.setUpdatedBy(xXPortalUser.getLoginId());
- }
- }
- }
- return vObj;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XPermMapServiceBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XPermMapServiceBase.java b/security-admin/src/main/java/com/xasecure/service/XPermMapServiceBase.java
deleted file mode 100644
index eb1eb30..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XPermMapServiceBase.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-/**
- *
- */
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-import com.xasecure.view.*;
-import com.xasecure.service.*;
-
-public abstract class XPermMapServiceBase<T extends XXPermMap, V extends VXPermMap>
- extends AbstractBaseResourceService<T, V> {
- public static final String NAME = "XPermMap";
-
- public XPermMapServiceBase() {
-
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected XXPermMap mapViewToEntityBean(VXPermMap vObj, XXPermMap mObj, int OPERATION_CONTEXT) {
- mObj.setPermGroup( vObj.getPermGroup());
- mObj.setResourceId( vObj.getResourceId());
- mObj.setGroupId( vObj.getGroupId());
- mObj.setUserId( vObj.getUserId());
- mObj.setPermFor( vObj.getPermFor());
- mObj.setPermType( vObj.getPermType());
- mObj.setIsRecursive( vObj.getIsRecursive());
- mObj.setIsWildCard( vObj.isIsWildCard());
- mObj.setGrantOrRevoke( vObj.isGrantOrRevoke());
- mObj.setIpAddress( vObj.getIpAddress());
- return mObj;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected VXPermMap mapEntityToViewBean(VXPermMap vObj, XXPermMap mObj) {
- vObj.setPermGroup( mObj.getPermGroup());
- vObj.setResourceId( mObj.getResourceId());
- vObj.setGroupId( mObj.getGroupId());
- vObj.setUserId( mObj.getUserId());
- vObj.setPermFor( mObj.getPermFor());
- vObj.setPermType( mObj.getPermType());
- vObj.setIsRecursive( mObj.getIsRecursive());
- vObj.setIsWildCard( mObj.isIsWildCard());
- vObj.setGrantOrRevoke( mObj.isGrantOrRevoke());
- vObj.setIpAddress( mObj.getIpAddress());
- return vObj;
- }
-
- /**
- * @param searchCriteria
- * @return
- */
- public VXPermMapList searchXPermMaps(SearchCriteria searchCriteria) {
- VXPermMapList returnList = new VXPermMapList();
- List<VXPermMap> xPermMapList = new ArrayList<VXPermMap>();
-
- @SuppressWarnings("unchecked")
- List<XXPermMap> resultList = (List<XXPermMap>)searchResources(searchCriteria,
- searchFields, sortFields, returnList);
-
- // Iterate over the result list and create the return list
- for (XXPermMap gjXPermMap : resultList) {
- @SuppressWarnings("unchecked")
- VXPermMap vXPermMap = populateViewBean((T)gjXPermMap);
- xPermMapList.add(vXPermMap);
- }
-
- returnList.setVXPermMaps(xPermMapList);
- return returnList;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XPolicyExportAuditService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XPolicyExportAuditService.java b/security-admin/src/main/java/com/xasecure/service/XPolicyExportAuditService.java
deleted file mode 100644
index bd66b28..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XPolicyExportAuditService.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-import com.xasecure.common.SearchField;
-import com.xasecure.common.SearchField.DATA_TYPE;
-import com.xasecure.common.SearchField.SEARCH_TYPE;
-import com.xasecure.common.SortField.SORT_ORDER;
-import com.xasecure.common.SortField;
-
-import com.xasecure.view.*;
-import com.xasecure.entity.*;
-
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Service;
-
-@Service
-@Scope("singleton")
-public class XPolicyExportAuditService extends XPolicyExportAuditServiceBase<XXPolicyExportAudit, VXPolicyExportAudit> {
-
- public XPolicyExportAuditService(){
- searchFields.add(new SearchField("httpRetCode", "obj.httpRetCode",
- SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
- searchFields.add(new SearchField("clientIP", "obj.clientIP",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
- searchFields.add(new SearchField("agentId", "obj.agentId",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
- searchFields.add(new SearchField("repositoryName", "obj.repositoryName",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
- searchFields.add(new SearchField("startDate", "obj.createTime",
- DATA_TYPE.DATE, SEARCH_TYPE.GREATER_EQUAL_THAN));
- searchFields.add(new SearchField("endDate", "obj.createTime",
- DATA_TYPE.DATE, SEARCH_TYPE.LESS_EQUAL_THAN));
-
- sortFields.add(new SortField("createDate", "obj.createTime", true, SORT_ORDER.DESC));
- }
-
- @Override
- protected void validateForCreate(VXPolicyExportAudit vObj) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void validateForUpdate(VXPolicyExportAudit vObj, XXPolicyExportAudit mObj) {
- // TODO Auto-generated method stub
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XPolicyExportAuditServiceBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XPolicyExportAuditServiceBase.java b/security-admin/src/main/java/com/xasecure/service/XPolicyExportAuditServiceBase.java
deleted file mode 100644
index 0293c49..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XPolicyExportAuditServiceBase.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-/**
- *
- */
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-import com.xasecure.view.*;
-import com.xasecure.service.*;
-
-public abstract class XPolicyExportAuditServiceBase<T extends XXPolicyExportAudit, V extends VXPolicyExportAudit>
- extends AbstractBaseResourceService<T, V> {
- public static final String NAME = "XPolicyExportAudit";
-
- public XPolicyExportAuditServiceBase() {
-
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected XXPolicyExportAudit mapViewToEntityBean(VXPolicyExportAudit vObj, XXPolicyExportAudit mObj, int OPERATION_CONTEXT) {
- mObj.setClientIP( vObj.getClientIP());
- mObj.setAgentId( vObj.getAgentId());
- mObj.setRequestedEpoch( vObj.getRequestedEpoch());
- mObj.setLastUpdated( vObj.getLastUpdated());
- mObj.setRepositoryName( vObj.getRepositoryName());
- mObj.setExportedJson( vObj.getExportedJson());
- mObj.setHttpRetCode( vObj.getHttpRetCode());
- return mObj;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected VXPolicyExportAudit mapEntityToViewBean(VXPolicyExportAudit vObj, XXPolicyExportAudit mObj) {
- vObj.setClientIP( mObj.getClientIP());
- vObj.setAgentId( mObj.getAgentId());
- vObj.setRequestedEpoch( mObj.getRequestedEpoch());
- vObj.setLastUpdated( mObj.getLastUpdated());
- vObj.setRepositoryName( mObj.getRepositoryName());
- vObj.setExportedJson( mObj.getExportedJson());
- vObj.setHttpRetCode( mObj.getHttpRetCode());
- return vObj;
- }
-
- /**
- * @param searchCriteria
- * @return
- */
- public VXPolicyExportAuditList searchXPolicyExportAudits(SearchCriteria searchCriteria) {
- VXPolicyExportAuditList returnList = new VXPolicyExportAuditList();
- List<VXPolicyExportAudit> xPolicyExportAuditList = new ArrayList<VXPolicyExportAudit>();
-
- @SuppressWarnings("unchecked")
- List<XXPolicyExportAudit> resultList = (List<XXPolicyExportAudit>)searchResources(searchCriteria,
- searchFields, sortFields, returnList);
-
- // Iterate over the result list and create the return list
- for (XXPolicyExportAudit gjXPolicyExportAudit : resultList) {
- @SuppressWarnings("unchecked")
- VXPolicyExportAudit vXPolicyExportAudit = populateViewBean((T)gjXPolicyExportAudit);
- xPolicyExportAuditList.add(vXPolicyExportAudit);
- }
-
- returnList.setVXPolicyExportAudits(xPolicyExportAuditList);
- return returnList;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XPolicyService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XPolicyService.java b/security-admin/src/main/java/com/xasecure/service/XPolicyService.java
deleted file mode 100644
index 9e2addc..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XPolicyService.java
+++ /dev/null
@@ -1,754 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Random;
-
-import org.apache.commons.lang.StringUtils;
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-import com.xasecure.common.AppConstants;
-import com.xasecure.common.DateUtil;
-import com.xasecure.common.MessageEnums;
-import com.xasecure.common.PropertiesUtil;
-import com.xasecure.common.RESTErrorUtil;
-import com.xasecure.common.SearchCriteria;
-import com.xasecure.common.StringUtil;
-import com.xasecure.db.XADaoManager;
-import com.xasecure.entity.XXAsset;
-import com.xasecure.entity.XXGroup;
-import com.xasecure.entity.XXPermMap;
-import com.xasecure.entity.XXResource;
-import com.xasecure.entity.XXUser;
-import com.xasecure.view.VXAuditMap;
-import com.xasecure.view.VXAuditMapList;
-import com.xasecure.view.VXDataObject;
-import com.xasecure.view.VXPermMap;
-import com.xasecure.view.VXPermMapList;
-import com.xasecure.view.VXPermObj;
-import com.xasecure.view.VXPolicy;
-import com.xasecure.view.VXPolicyList;
-import com.xasecure.view.VXResource;
-import com.xasecure.view.VXResourceList;
-
-@Service
-public class XPolicyService extends PublicAPIServiceBase<VXResource, VXPolicy> {
- Logger logger = Logger.getLogger(XPolicyService.class);
-
- @Autowired
- RESTErrorUtil restErrorUtil;
-
- @Autowired
- StringUtil stringUtil;
-
- @Autowired
- XADaoManager xaDaoMgr;
-
- @Autowired
- XPermMapService xPermMapService;
-
- @Autowired
- XAuditMapService xAuditMapService;
-
- @Autowired
- XResourceService xResourceService;
-
- String version;
-
- private static String uniqueKeySeparator = "_";
-
- public XPolicyService() {
- version = PropertiesUtil.getProperty("maven.project.version", "");
- }
-
- public VXPolicy mapXAToPublicObject(VXResource vXResource) {
-
- VXPolicy vXPolicy = new VXPolicy();
- vXPolicy = super.mapBaseAttributesToPublicObject(vXResource, vXPolicy);
-
- vXPolicy.setPolicyName(vXResource.getPolicyName());
- vXPolicy.setResourceName(vXResource.getName());
- vXPolicy.setDescription(vXResource.getDescription());
- vXPolicy.setRepositoryName(vXResource.getAssetName());
- vXPolicy.setRepositoryType(AppConstants
- .getLabelFor_AssetType(vXResource.getAssetType()));
-
-
- List<VXPermObj> permObjList = mapPermMapToPermObj(vXResource
- .getPermMapList());
- if (!stringUtil.isEmpty(permObjList)) {
- vXPolicy.setPermMapList(permObjList);
- }
- vXPolicy.setTables(vXResource.getTables());
- vXPolicy.setColumnFamilies(vXResource.getColumnFamilies());
- vXPolicy.setColumns(vXResource.getColumns());
- vXPolicy.setDatabases(vXResource.getDatabases());
- vXPolicy.setUdfs(vXResource.getUdfs());
-
- vXPolicy.setTopologies(vXResource.getTopologies());
- vXPolicy.setServices(vXResource.getServices());
-
- boolean enable = true;
- if (vXResource.getResourceStatus() == AppConstants.STATUS_DISABLED
- || vXResource.getResourceStatus() == AppConstants.STATUS_DELETED) {
- enable = false;
- }
- vXPolicy.setIsEnabled(enable);
-
- boolean auditEnable = true;
- if (stringUtil.isEmpty(vXResource.getAuditList())) {
- auditEnable = false;
- }
- vXPolicy.setIsAuditEnabled(auditEnable);
- vXPolicy.setVersion(version);
-
- /*
- * TODO : These parameters are specific for some components. Need to
- * take care while adding new component
- */
- if (vXResource.getAssetType() == AppConstants.ASSET_HIVE) {
- vXPolicy.setTableType(AppConstants
- .getLabelFor_PolicyType(vXResource.getTableType()));
- vXPolicy.setColumnType(AppConstants
- .getLabelFor_PolicyType(vXResource.getColumnType()));
- }
- if (vXResource.getAssetType() == AppConstants.ASSET_HDFS) {
- vXPolicy.setIsRecursive(AppConstants
- .getBooleanFor_BooleanValue(vXResource.getIsRecursive()));
- } else {
- vXPolicy.setIsRecursive(null);
- }
-
- return vXPolicy;
- }
-
- public VXResource mapPublicToXAObject(VXPolicy vXPolicy,
- int operationContext) {
- VXResource vXResource = new VXResource();
- vXResource = super.mapBaseAttributesToXAObject(vXPolicy, vXResource);
-
- vXResource.setName(vXPolicy.getResourceName());
- vXResource.setPolicyName(vXPolicy.getPolicyName());
- vXResource.setDescription(vXPolicy.getDescription());
- vXResource.setResourceType(getResourceType(vXPolicy));
-
- XXAsset xAsset = xaDaoMgr.getXXAsset().findByAssetName(
- vXPolicy.getRepositoryName());
- if (xAsset == null) {
- throw restErrorUtil.createRESTException("The repository for which "
- + "you're updating policy, doesn't exist.",
- MessageEnums.INVALID_INPUT_DATA);
- }
- vXResource.setAssetId(xAsset.getId());
-
- if (operationContext == AbstractBaseResourceService.OPERATION_UPDATE_CONTEXT) {
- XXResource xxResource = xaDaoMgr.getXXResource().getById(
- vXPolicy.getId());
- if (xxResource == null) {
- logger.error("No policy found with given Id : "
- + vXPolicy.getId());
- throw restErrorUtil
- .createRESTException("No Policy found with given Id : "
- + vXResource.getId(),
- MessageEnums.DATA_NOT_FOUND);
- }
- /*
- * While updating public object we wont have createDate/updateDate,
- * so create time, addedById, updatedById, etc. we ll have to take
- * from existing object
- */
-
- xxResource.setUpdateTime(DateUtil.getUTCDate());
- xResourceService
- .mapBaseAttributesToViewBean(xxResource, vXResource);
-
- SearchCriteria scAuditMap = new SearchCriteria();
- scAuditMap.addParam("resourceId", xxResource.getId());
- VXAuditMapList vXAuditMapList = xAuditMapService
- .searchXAuditMaps(scAuditMap);
-
- List<VXAuditMap> auditList = new ArrayList<VXAuditMap>();
-
- if (vXAuditMapList.getListSize() > 0
- && vXPolicy.getIsAuditEnabled()) {
- auditList.addAll(vXAuditMapList.getVXAuditMaps());
- } else if (vXAuditMapList.getListSize() == 0
- && vXPolicy.getIsAuditEnabled()) {
- VXAuditMap vXAuditMap = new VXAuditMap();
- vXAuditMap.setAuditType(AppConstants.XA_AUDIT_TYPE_ALL);
- auditList.add(vXAuditMap);
-
- }
-
- List<VXPermMap> permMapList = mapPermObjToPermList(
- vXPolicy.getPermMapList(), vXPolicy);
-
- vXResource.setAuditList(auditList);
- vXResource.setPermMapList(permMapList);
-
- } else if (operationContext == AbstractBaseResourceService.OPERATION_CREATE_CONTEXT) {
- if (vXPolicy.getIsAuditEnabled()) {
- VXAuditMap vXAuditMap = new VXAuditMap();
- vXAuditMap.setAuditType(AppConstants.XA_AUDIT_TYPE_ALL);
- List<VXAuditMap> auditList = new ArrayList<VXAuditMap>();
- auditList.add(vXAuditMap);
-
- vXResource.setAuditList(auditList);
- }
- if (!stringUtil.isEmpty(vXPolicy.getPermMapList())) {
- List<VXPermMap> permMapList = mapPermObjToPermList(vXPolicy
- .getPermMapList());
- vXResource.setPermMapList(permMapList);
- }
- }
-
- vXResource.setDatabases(vXPolicy.getDatabases());
- vXResource.setTables(vXPolicy.getTables());
- vXResource.setColumnFamilies(vXPolicy.getColumnFamilies());
- vXResource.setColumns(vXPolicy.getColumns());
- vXResource.setUdfs(vXPolicy.getUdfs());
- vXResource.setAssetName(vXPolicy.getRepositoryName());
-
- int assetType = AppConstants.getEnumFor_AssetType(vXPolicy
- .getRepositoryType());
- if (assetType == 0 || assetType == AppConstants.ASSET_UNKNOWN) {
- assetType = xAsset.getAssetType();
- vXPolicy.setRepositoryType(AppConstants.getLabelFor_AssetType(assetType));
- }
- vXResource.setAssetType(assetType);
-
- int resourceStatus = AppConstants.STATUS_ENABLED;
- if (!vXPolicy.getIsEnabled()) {
- resourceStatus = AppConstants.STATUS_DISABLED;
- }
- vXResource.setResourceStatus(resourceStatus);
- // Allowing to create policy without checking parent permission
- vXResource.setCheckParentPermission(AppConstants.BOOL_FALSE);
- vXResource.setTopologies(vXPolicy.getTopologies());
- vXResource.setServices(vXPolicy.getServices());
-
- /*
- * TODO : These parameters are specific for some components. Need to
- * take care while adding new component
- */
- if (vXPolicy.getRepositoryType().equalsIgnoreCase(
- AppConstants.getLabelFor_AssetType(AppConstants.ASSET_HIVE))) {
- vXResource.setTableType(AppConstants.getEnumFor_PolicyType(vXPolicy
- .getTableType()));
- vXResource.setColumnType(AppConstants
- .getEnumFor_PolicyType(vXPolicy.getColumnType()));
- }
- if (vXPolicy.getRepositoryType().equalsIgnoreCase(
- AppConstants.getLabelFor_AssetType(AppConstants.ASSET_HDFS))) {
- vXResource.setIsRecursive(AppConstants
- .getEnumFor_BooleanValue(vXPolicy.getIsRecursive()));
- }
-
- return vXResource;
- }
-
- private List<VXPermMap> mapPermObjToPermList(List<VXPermObj> permObjList,
- VXPolicy vXPolicy) {
-
- Long resId = vXPolicy.getId();
- List<VXPermMap> permMapList = new ArrayList<VXPermMap>();
- List<VXPermMap> updPermMapList = new ArrayList<VXPermMap>();
- Map<String, VXPermMap> newPermMap = new LinkedHashMap<String, VXPermMap>();
- Random rand = new Random();
-
- Map<String, XXPermMap> prevPermMap = getPrevPermMap(resId);
-
- if (permObjList == null) {
- permObjList = new ArrayList<VXPermObj>();
- }
- for (VXPermObj permObj : permObjList) {
- String permGrp = new Date() + " : " + rand.nextInt(9999);
- String ipAddress = permObj.getIpAddress();
-
- if (!stringUtil.isEmpty(permObj.getUserList())) {
- int permFor = AppConstants.XA_PERM_FOR_USER;
-
- for (String user : permObj.getUserList()) {
-
- XXUser xxUser = xaDaoMgr.getXXUser().findByUserName(user);
- if (xxUser == null) {
- logger.error("No User found with this name : " + user);
- throw restErrorUtil.createRESTException(
- "No User found with name : " + user,
- MessageEnums.DATA_NOT_FOUND);
- }
- Long userId = xxUser.getId();
- for (String permission : permObj.getPermList()) {
-
- int permType = AppConstants
- .getEnumFor_XAPermType(permission);
- VXPermMap vXPermMap = new VXPermMap();
- vXPermMap.setPermFor(AppConstants.XA_PERM_FOR_USER);
- vXPermMap.setPermGroup(permGrp);
- vXPermMap.setPermType(permType);
- vXPermMap.setUserId(xxUser.getId());
- vXPermMap.setResourceId(resId);
- vXPermMap.setIpAddress(ipAddress);
- permMapList.add(vXPermMap);
-
- StringBuilder uniqueKey = new StringBuilder();
- uniqueKey.append(resId + uniqueKeySeparator);
- uniqueKey.append(permFor + uniqueKeySeparator);
- uniqueKey.append(userId + uniqueKeySeparator);
- uniqueKey.append(permType);
- newPermMap.put(uniqueKey.toString(), vXPermMap);
- }
- }
- }
- if (!stringUtil.isEmpty(permObj.getGroupList())) {
- int permFor = AppConstants.XA_PERM_FOR_GROUP;
-
- for (String group : permObj.getGroupList()) {
-
- XXGroup xxGroup = xaDaoMgr.getXXGroup().findByGroupName(
- group);
- if (xxGroup == null) {
- logger.error("No UserGroup found with this name : "
- + group);
- throw restErrorUtil.createRESTException(
- "No Group found with name : " + group,
- MessageEnums.DATA_NOT_FOUND);
- }
- Long grpId = xxGroup.getId();
- for (String permission : permObj.getPermList()) {
-
- int permType = AppConstants
- .getEnumFor_XAPermType(permission);
- VXPermMap vXPermMap = new VXPermMap();
- vXPermMap.setPermFor(AppConstants.XA_PERM_FOR_GROUP);
- vXPermMap.setPermGroup(permGrp);
- vXPermMap.setPermType(permType);
- vXPermMap.setGroupId(xxGroup.getId());
- vXPermMap.setResourceId(resId);
- vXPermMap.setIpAddress(ipAddress);
- permMapList.add(vXPermMap);
-
- StringBuilder uniqueKey = new StringBuilder();
- uniqueKey.append(resId + uniqueKeySeparator);
- uniqueKey.append(permFor + uniqueKeySeparator);
- uniqueKey.append(grpId + uniqueKeySeparator);
- uniqueKey.append(permType);
- newPermMap.put(uniqueKey.toString(), vXPermMap);
- }
- }
- }
- }
-
- // Create Newly added permissions and Remove deleted permissions from DB
- if (prevPermMap.size() == 0) {
- updPermMapList.addAll(permMapList);
- } else {
- for (Entry<String, VXPermMap> entry : newPermMap.entrySet()) {
- if (!prevPermMap.containsKey(entry.getKey())) {
- updPermMapList.add(entry.getValue());
- } else {
- VXPermMap vPMap = xPermMapService
- .populateViewBean(prevPermMap.get(entry.getKey()));
- VXPermMap vPMapNew = entry.getValue();
- vPMap.setIpAddress(vPMapNew.getIpAddress());
- updPermMapList.add(vPMap);
- }
- }
- }
- return updPermMapList;
- }
-
- private Map<String, XXPermMap> getPrevPermMap(Long resId) {
- List<XXPermMap> xxPermMapList = xaDaoMgr.getXXPermMap()
- .findByResourceId(resId);
-
- Map<String, XXPermMap> prevPermMap = new LinkedHashMap<String, XXPermMap>();
-
- for (XXPermMap xxPermMap : xxPermMapList) {
- int permFor = xxPermMap.getPermFor();
- Long userId = xxPermMap.getUserId();
- Long grpId = xxPermMap.getGroupId();
- int permType = xxPermMap.getPermType();
-
- StringBuilder uniqueKey = new StringBuilder();
- uniqueKey.append(resId + uniqueKeySeparator);
- uniqueKey.append(permFor + uniqueKeySeparator);
-
- if (userId != null) {
- uniqueKey.append(userId + uniqueKeySeparator);
- } else if (grpId != null) {
- uniqueKey.append(grpId + uniqueKeySeparator);
- }
- uniqueKey.append(permType);
- prevPermMap.put(uniqueKey.toString(), xxPermMap);
- }
-
- return prevPermMap;
- }
-
- public List<VXPermObj> mapPermMapToPermObj(List<VXPermMap> permMapList) {
-
- List<VXPermObj> permObjList = new ArrayList<VXPermObj>();
- HashMap<String, List<VXPermMap>> sortedPemMap = new HashMap<String, List<VXPermMap>>();
-
- if (permMapList != null) {
- for (VXPermMap vXPermMap : permMapList) {
-
- String permGrp = vXPermMap.getPermGroup();
- List<VXPermMap> sortedList = sortedPemMap.get(permGrp);
- if (sortedList == null) {
- sortedList = new ArrayList<VXPermMap>();
- sortedPemMap.put(permGrp, sortedList);
- }
- sortedList.add(vXPermMap);
- }
- }
-
- for (Entry<String, List<VXPermMap>> entry : sortedPemMap.entrySet()) {
- VXPermObj vXPermObj = new VXPermObj();
- List<String> userList = new ArrayList<String>();
- List<String> groupList = new ArrayList<String>();
- List<String> permList = new ArrayList<String>();
- String ipAddress = "";
-
- List<VXPermMap> permListForGrp = entry.getValue();
-
- for (VXPermMap permMap : permListForGrp) {
- if (permMap.getPermFor() == AppConstants.XA_PERM_FOR_USER) {
- if (!userList.contains(permMap.getUserName())) {
- userList.add(permMap.getUserName());
- }
- } else if (permMap.getPermFor() == AppConstants.XA_PERM_FOR_GROUP) {
- if (!groupList.contains(permMap.getGroupName())) {
- groupList.add(permMap.getGroupName());
- }
- }
- String perm = AppConstants.getLabelFor_XAPermType(permMap
- .getPermType());
- if (!permList.contains(perm)) {
- permList.add(perm);
- }
- ipAddress = permMap.getIpAddress();
- }
- if (!userList.isEmpty()) {
- vXPermObj.setUserList(userList);
- }
- if (!groupList.isEmpty()) {
- vXPermObj.setGroupList(groupList);
- }
- vXPermObj.setPermList(permList);
- vXPermObj.setIpAddress(ipAddress);
-
- permObjList.add(vXPermObj);
- }
- return permObjList;
- }
-
- public VXPolicyList mapToVXPolicyList(VXResourceList vXResourceList) {
-
- List<VXPolicy> policyList = new ArrayList<VXPolicy>();
- for (VXResource vXAsset : vXResourceList.getVXResources()) {
- VXPolicy vXRepo = mapXAToPublicObject(vXAsset);
- policyList.add(vXRepo);
- }
- VXPolicyList vXPolicyList = new VXPolicyList(policyList);
- return vXPolicyList;
- }
-
- private List<VXPermMap> mapPermObjToPermList(List<VXPermObj> permObjList) {
-
- List<VXPermMap> permMapList = new ArrayList<VXPermMap>();
- Random rand = new Random();
-
- for (VXPermObj permObj : permObjList) {
-
- String ipAddress = permObj.getIpAddress();
-
- if (!stringUtil.isEmpty(permObj.getUserList())) {
- String permGrp = new Date() + " : " + rand.nextInt(9999);
- for (String user : permObj.getUserList()) {
-
- XXUser xxUser = xaDaoMgr.getXXUser().findByUserName(user);
- if (xxUser == null) {
- logger.error("No User found with this name : " + user);
- throw restErrorUtil.createRESTException(
- "No User found with name : " + user,
- MessageEnums.DATA_NOT_FOUND);
- }
- for (String permission : permObj.getPermList()) {
-
- VXPermMap vXPermMap = new VXPermMap();
- int permType = AppConstants
- .getEnumFor_XAPermType(permission);
- vXPermMap.setPermFor(AppConstants.XA_PERM_FOR_USER);
- vXPermMap.setPermGroup(permGrp);
- vXPermMap.setPermType(permType);
- vXPermMap.setUserId(xxUser.getId());
- vXPermMap.setIpAddress(ipAddress);
-
- permMapList.add(vXPermMap);
- }
- }
- }
- if (!stringUtil.isEmpty(permObj.getGroupList())) {
- String permGrp = new Date() + " : " + rand.nextInt(9999);
- for (String group : permObj.getGroupList()) {
-
- XXGroup xxGroup = xaDaoMgr.getXXGroup().findByGroupName(
- group);
- if (xxGroup == null) {
- logger.error("No UserGroup found with this name : "
- + group);
- throw restErrorUtil.createRESTException(
- "No User found with name : " + group,
- MessageEnums.DATA_NOT_FOUND);
- }
-
- for (String permission : permObj.getPermList()) {
-
- VXPermMap vXPermMap = new VXPermMap();
- int permType = AppConstants
- .getEnumFor_XAPermType(permission);
- vXPermMap.setPermFor(AppConstants.XA_PERM_FOR_GROUP);
- vXPermMap.setPermGroup(permGrp);
- vXPermMap.setPermType(permType);
- vXPermMap.setGroupId(xxGroup.getId());
- vXPermMap.setIpAddress(ipAddress);
-
- permMapList.add(vXPermMap);
- }
- }
- }
- }
- return permMapList;
- }
-
- public List<VXPermMap> updatePermGroup(VXResource vXResource) {
-
- XXResource xxResource = xaDaoMgr.getXXResource().getById(
- vXResource.getId());
- if (xxResource == null) {
- logger.info("Resource : " + vXResource.getPolicyName()
- + " Not Found, while updating PermGroup");
- throw restErrorUtil.createRESTException(
- "Resource Not found to update PermGroup",
- MessageEnums.DATA_NOT_FOUND);
- }
- Long resId = vXResource.getId();
- List<VXPermMap> updatedPermMapList = new ArrayList<VXPermMap>();
-
- SearchCriteria searchCriteria = new SearchCriteria();
- searchCriteria.addParam("resourceId", resId);
- VXPermMapList currentPermMaps = xPermMapService
- .searchXPermMaps(searchCriteria);
-
- List<VXPermMap> currentPermMapList = currentPermMaps.getVXPermMaps();
- HashMap<String, List<String>> userPermMap = new HashMap<String, List<String>>();
-
- for (VXPermMap currentPermMap : currentPermMapList) {
- Long userId = currentPermMap.getUserId();
- Long groupId = currentPermMap.getGroupId();
- int permFor = currentPermMap.getPermFor();
- int permType = currentPermMap.getPermType();
- String ipAddress = currentPermMap.getIpAddress();
-
- String uniKey = resId + uniqueKeySeparator + permFor;
- if (permFor == AppConstants.XA_PERM_FOR_GROUP) {
- uniKey = uniKey + uniqueKeySeparator + groupId;
- } else if (permFor == AppConstants.XA_PERM_FOR_USER) {
- uniKey = uniKey + uniqueKeySeparator + userId;
- }
-
- List<String> permList = userPermMap.get(uniKey);
- if (permList == null) {
- permList = new ArrayList<String>();
- userPermMap.put(uniKey, permList);
- }
- permList.add(""+permType);
-
- if (stringUtil.isEmpty(ipAddress)) {
- permList.add(ipAddress);
- }
-
- }
-
- List<List<String>> masterKeyList = new ArrayList<List<String>>();
- List<String> proceedKeyList = new ArrayList<String>();
- for (Entry<String, List<String>> upMap : userPermMap.entrySet()) {
-
- if (proceedKeyList.contains(upMap.getKey())) {
- continue;
- }
-
- List<String> keyList = new ArrayList<String>();
- keyList.add(upMap.getKey());
- proceedKeyList.add(upMap.getKey());
-
- for (Entry<String, List<String>> entry : userPermMap.entrySet()) {
-
- if (proceedKeyList.contains(entry.getKey())) {
- continue;
- }
-
- boolean result = compareTwoListElements(upMap.getValue(),
- entry.getValue());
- if (result) {
- keyList.add(entry.getKey());
- proceedKeyList.add(entry.getKey());
- }
- }
- masterKeyList.add(keyList);
- }
-
- for (List<String> keyList : masterKeyList) {
- Random rand = new Random();
- String permGrp = new Date() + " : " + rand.nextInt(9999);
- for (String key : keyList) {
-
- SearchCriteria scPermMap = new SearchCriteria();
- String[] keyEle = StringUtils.split(key, uniqueKeySeparator);
- if (keyEle != null && keyEle.length == 3) {
-
- int permFor = Integer.parseInt(keyEle[1]);
- int ugId = Integer.parseInt(keyEle[2]);
- scPermMap.addParam("resourceId", resId);
- scPermMap.addParam("permFor", permFor);
-
- if (permFor == AppConstants.XA_PERM_FOR_GROUP) {
- scPermMap.addParam("groupId", ugId);
- } else if (permFor == AppConstants.XA_PERM_FOR_USER) {
- scPermMap.addParam("userId", ugId);
- }
-
- VXPermMapList permList = xPermMapService
- .searchXPermMaps(scPermMap);
- for (VXPermMap vXPerm : permList.getVXPermMaps()) {
- vXPerm.setPermGroup(permGrp);
- xPermMapService.updateResource(vXPerm);
- updatedPermMapList.add(vXPerm);
- }
- } else {
- logger.info("variable : keyEle, should fulfill the checked"
- + " condition, but its not fulfilling required "
- + "condition. Ignoring appropriate permMap from"
- + " updating permGroup. Key : " + key
- + "Resource Id : " + resId);
- }
- }
- }
- return updatedPermMapList;
- }
-
- private boolean compareTwoListElements(List<?> list1, List<?> list2) {
- if (list1 == null || list2 == null) {
- return false;
- }
- if (list1.size() != list2.size()) {
- return false;
- }
- int listSize = list1.size();
- for (int i = 0; i < listSize; i++) {
- Object obj1 = list1.get(i);
- if (!list2.contains(obj1)) {
- return false;
- }
- }
- return true;
- }
-
- public int getResourceType(VXDataObject vObj) {
- int resourceType = AppConstants.RESOURCE_PATH;
- if (vObj == null) {
- return resourceType;
- }
-
- VXPolicy vXPolicy = null;
- VXResource vXResource = null;
- if (vObj instanceof VXPolicy) {
- vXPolicy = (VXPolicy) vObj;
- } else if (vObj instanceof VXResource) {
- vXResource = (VXResource) vObj;
- } else {
- return resourceType;
- }
-
- String databases = null;
- String tables = null;
- String columns = null;
- String udfs = null;
- String columnFamilies = null;
- String topologies = null;
- String services = null;
-
- if (vXPolicy != null) {
- databases = vXPolicy.getDatabases();
- tables = vXPolicy.getTables();
- columns = vXPolicy.getColumns();
- udfs = vXPolicy.getUdfs();
- columnFamilies = vXPolicy.getColumnFamilies();
- topologies = vXPolicy.getTopologies();
- services = vXPolicy.getServices();
- } else if (vXResource != null) {
- databases = vXResource.getDatabases();
- tables = vXResource.getTables();
- columns = vXResource.getColumns();
- udfs = vXResource.getUdfs();
- columnFamilies = vXResource.getColumnFamilies();
- topologies = vXResource.getTopologies();
- services = vXResource.getServices();
- }
-
- if (!stringUtil.isEmpty(databases)) {
- resourceType = AppConstants.RESOURCE_DB;
- if (!stringUtil.isEmptyOrWildcardAsterisk(tables)) {
- resourceType = AppConstants.RESOURCE_TABLE;
- }
- if (!stringUtil.isEmptyOrWildcardAsterisk(columns)) {
- resourceType = AppConstants.RESOURCE_COLUMN;
- }
- if (!stringUtil.isEmpty(udfs)) {
- resourceType = AppConstants.RESOURCE_UDF;
- }
- } else if (!stringUtil.isEmpty(tables)) {
- resourceType = AppConstants.RESOURCE_TABLE;
- if (!stringUtil.isEmptyOrWildcardAsterisk(columnFamilies)) {
- resourceType = AppConstants.RESOURCE_COL_FAM;
- }
- if (!stringUtil.isEmptyOrWildcardAsterisk(columns)) {
- resourceType = AppConstants.RESOURCE_COLUMN;
- }
- } else if (!stringUtil.isEmpty(topologies)) {
- resourceType = AppConstants.RESOURCE_TOPOLOGY;
- if (!stringUtil.isEmptyOrWildcardAsterisk(services)) {
- resourceType = AppConstants.RESOURCE_SERVICE_NAME;
- }
- }
- return resourceType;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XPortalUserService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XPortalUserService.java b/security-admin/src/main/java/com/xasecure/service/XPortalUserService.java
deleted file mode 100644
index 3641b31..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XPortalUserService.java
+++ /dev/null
@@ -1,195 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-import com.xasecure.common.AppConstants;
-import com.xasecure.common.StringUtil;
-import com.xasecure.common.view.VTrxLogAttr;
-import com.xasecure.entity.*;
-import com.xasecure.util.XAEnumUtil;
-import com.xasecure.view.*;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Service;
-
-@Service
-@Scope("singleton")
-public class XPortalUserService extends
- XPortalUserServiceBase<XXPortalUser, VXPortalUser> {
-
- @Autowired
- XAEnumUtil xaEnumUtil;
-
- @Autowired
- StringUtil stringUtil;
-
- static HashMap<String, VTrxLogAttr> trxLogAttrs = new HashMap<String, VTrxLogAttr>();
- static {
- trxLogAttrs.put("loginId",
- new VTrxLogAttr("loginId", "Login ID", false));
- trxLogAttrs.put("status", new VTrxLogAttr("status",
- "Activation Status", false));
- trxLogAttrs.put("firstName", new VTrxLogAttr("firstName", "First Name",
- false));
- trxLogAttrs.put("lastName", new VTrxLogAttr("lastName", "Last Name",
- false));
- trxLogAttrs.put("emailAddress", new VTrxLogAttr("emailAddress",
- "Email Address", false));
- trxLogAttrs.put("publicScreenName", new VTrxLogAttr("publicScreenName",
- "Public Screen Name", false));
- }
-
- @Override
- protected void validateForCreate(VXPortalUser vObj) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void validateForUpdate(VXPortalUser vObj, XXPortalUser mObj) {
- // TODO Auto-generated method stub
-
- }
-
- public List<XXTrxLog> getTransactionLog(VXPortalUser vUser, String action) {
- return getTransactionLog(vUser, null, action);
- }
-
- public List<XXTrxLog> getTransactionLog(VXPortalUser vObj,
- XXPortalUser xObj, String action) {
- if (vObj == null
- && (action == null || !action.equalsIgnoreCase("update"))) {
- return null;
- }
-
- List<XXTrxLog> trxLogList = new ArrayList<XXTrxLog>();
- Field[] fields = vObj.getClass().getDeclaredFields();
-
- try {
- Field nameField = vObj.getClass().getDeclaredField("loginId");
- nameField.setAccessible(true);
- String objectName = "" + nameField.get(vObj);
-
- for (Field field : fields) {
- field.setAccessible(true);
- String fieldName = field.getName();
- if (!trxLogAttrs.containsKey(fieldName)) {
- continue;
- }
-
- VTrxLogAttr vTrxLogAttr = trxLogAttrs.get(fieldName);
-
- XXTrxLog xTrxLog = new XXTrxLog();
- xTrxLog.setAttributeName(vTrxLogAttr
- .getAttribUserFriendlyName());
-
- String value = null;
- boolean isEnum = vTrxLogAttr.isEnum();
- if (isEnum) {
- String enumName = XXAsset.getEnumName(fieldName);
- int enumValue = field.get(vObj) == null ? 0 : Integer
- .parseInt("" + field.get(vObj));
- value = xaEnumUtil.getLabel(enumName, enumValue);
- } else {
- value = "" + field.get(vObj);
- }
-
- if (action.equalsIgnoreCase("create")) {
- if (stringUtil.isEmpty(value)) {
- continue;
- }
- xTrxLog.setNewValue(value);
- } else if (action.equalsIgnoreCase("delete")) {
- xTrxLog.setPreviousValue(value);
- } else if (action.equalsIgnoreCase("update")) {
- String oldValue = null;
- Field[] xFields = xObj.getClass().getDeclaredFields();
-
- for (Field xField : xFields) {
- xField.setAccessible(true);
- String xFieldName = xField.getName();
-
- if (fieldName.equalsIgnoreCase(xFieldName)) {
- if (isEnum) {
- String enumName = XXAsset
- .getEnumName(xFieldName);
- int enumValue = xField.get(xObj) == null ? 0
- : Integer.parseInt(""
- + xField.get(xObj));
- oldValue = xaEnumUtil.getLabel(enumName,
- enumValue);
- } else {
- oldValue = xField.get(xObj) + "";
- }
- break;
- }
- }
- if (fieldName.equalsIgnoreCase("emailAddress")) {
- if (!stringUtil.validateEmail(oldValue)) {
- oldValue = "";
- }
- if (!stringUtil.validateEmail(value)) {
- value = "";
- }
- }
- if (value.equalsIgnoreCase(oldValue)) {
- continue;
- }
- xTrxLog.setPreviousValue(oldValue);
- xTrxLog.setNewValue(value);
- }
-
- xTrxLog.setAction(action);
- xTrxLog.setObjectClassType(AppConstants.CLASS_TYPE_USER_PROFILE);
- xTrxLog.setObjectId(vObj.getId());
- xTrxLog.setObjectName(objectName);
- trxLogList.add(xTrxLog);
- }
- } catch (IllegalArgumentException e) {
- logger.info(
- "Caught IllegalArgumentException while"
- + " getting Transaction log for user : "
- + vObj.getLoginId(), e);
- } catch (NoSuchFieldException e) {
- logger.info(
- "Caught NoSuchFieldException while"
- + " getting Transaction log for user : "
- + vObj.getLoginId(), e);
- } catch (SecurityException e) {
- logger.info(
- "Caught SecurityException while"
- + " getting Transaction log for user : "
- + vObj.getLoginId(), e);
- } catch (IllegalAccessException e) {
- logger.info(
- "Caught IllegalAccessException while"
- + " getting Transaction log for user : "
- + vObj.getLoginId(), e);
- }
- return trxLogList;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XPortalUserServiceBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XPortalUserServiceBase.java b/security-admin/src/main/java/com/xasecure/service/XPortalUserServiceBase.java
deleted file mode 100644
index 8d78975..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XPortalUserServiceBase.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-/**
- *
- */
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-import com.xasecure.view.*;
-import com.xasecure.service.*;
-
-public abstract class XPortalUserServiceBase<T extends XXPortalUser, V extends VXPortalUser>
- extends AbstractBaseResourceService<T, V> {
- public static final String NAME = "XPortalUser";
-
- public XPortalUserServiceBase() {
-
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected XXPortalUser mapViewToEntityBean(VXPortalUser vObj, XXPortalUser mObj, int OPERATION_CONTEXT) {
- mObj.setFirstName( vObj.getFirstName());
- mObj.setLastName( vObj.getLastName());
- mObj.setPublicScreenName( vObj.getPublicScreenName());
- mObj.setLoginId( vObj.getLoginId());
- mObj.setPassword( vObj.getPassword());
- mObj.setEmailAddress( vObj.getEmailAddress());
- mObj.setStatus( vObj.getStatus());
- mObj.setUserSource( vObj.getUserSource());
- mObj.setNotes( vObj.getNotes());
- return mObj;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected VXPortalUser mapEntityToViewBean(VXPortalUser vObj, XXPortalUser mObj) {
- vObj.setFirstName( mObj.getFirstName());
- vObj.setLastName( mObj.getLastName());
- vObj.setPublicScreenName( mObj.getPublicScreenName());
- vObj.setLoginId( mObj.getLoginId());
- vObj.setPassword( mObj.getPassword());
- vObj.setEmailAddress( mObj.getEmailAddress());
- vObj.setStatus( mObj.getStatus());
- vObj.setUserSource( mObj.getUserSource());
- vObj.setNotes( mObj.getNotes());
- return vObj;
- }
-
- /**
- * @param searchCriteria
- * @return
- */
- public VXPortalUserList searchXPortalUsers(SearchCriteria searchCriteria) {
- VXPortalUserList returnList = new VXPortalUserList();
- List<VXPortalUser> xPortalUserList = new ArrayList<VXPortalUser>();
-
- @SuppressWarnings("unchecked")
- List<XXPortalUser> resultList = (List<XXPortalUser>)searchResources(searchCriteria,
- searchFields, sortFields, returnList);
-
- // Iterate over the result list and create the return list
- for (XXPortalUser gjXPortalUser : resultList) {
- @SuppressWarnings("unchecked")
- VXPortalUser vXPortalUser = populateViewBean((T)gjXPortalUser);
- xPortalUserList.add(vXPortalUser);
- }
-
- returnList.setVXPortalUsers(xPortalUserList);
- return returnList;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XRepositoryService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XRepositoryService.java b/security-admin/src/main/java/com/xasecure/service/XRepositoryService.java
deleted file mode 100644
index ade952a..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XRepositoryService.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-import com.xasecure.common.AppConstants;
-import com.xasecure.common.MessageEnums;
-import com.xasecure.common.PropertiesUtil;
-import com.xasecure.common.RESTErrorUtil;
-import com.xasecure.common.SearchCriteria;
-import com.xasecure.common.XACommonEnums;
-import com.xasecure.view.VXAsset;
-import com.xasecure.view.VXAssetList;
-import com.xasecure.view.VXRepository;
-import com.xasecure.view.VXRepositoryList;
-
-@Service
-public class XRepositoryService extends
- PublicAPIServiceBase<VXAsset, VXRepository> {
-
- @Autowired
- RESTErrorUtil restErrorUtil;
-
- String version;
-
- public XRepositoryService() {
- version = PropertiesUtil.getProperty("maven.project.version", "");
- }
-
- public VXRepository mapXAToPublicObject(VXAsset vXAsset) {
- VXRepository vRepo = new VXRepository();
- vRepo = super.mapBaseAttributesToPublicObject(vXAsset, vRepo);
-
- vRepo.setName(vXAsset.getName());
- vRepo.setDescription(vXAsset.getDescription());
- vRepo.setRepositoryType(AppConstants.getLabelFor_AssetType(vXAsset
- .getAssetType()));
- vRepo.setConfig(vXAsset.getConfig());
-
- int actStatus = vXAsset.getActiveStatus();
- boolean isAct = (actStatus == XACommonEnums.STATUS_DISABLED) ? false
- : true;
-
- vRepo.setIsActive(isAct);
- vRepo.setVersion(version);
-
- return vRepo;
- }
-
- public VXAsset mapPublicToXAObject(VXRepository vXRepo) {
-
- VXAsset vXAsset = new VXAsset();
- vXAsset = super.mapBaseAttributesToXAObject(vXRepo, vXAsset);
-
- vXAsset.setName(vXRepo.getName());
- vXAsset.setDescription(vXRepo.getDescription());
- vXAsset.setAssetType(AppConstants.getEnumFor_AssetType(vXRepo
- .getRepositoryType()));
- vXAsset.setConfig(vXRepo.getConfig());
-
- int actStatus = (!vXRepo.getIsActive()) ? XACommonEnums.STATUS_DISABLED
- : XACommonEnums.STATUS_ENABLED;
-
- vXAsset.setActiveStatus(actStatus);
-
- return vXAsset;
- }
-
- public SearchCriteria getMappedSearchParams(HttpServletRequest request,
- SearchCriteria searchCriteria) {
-
- Object typeObj = searchCriteria.getParamValue("type");
- Object statusObj = searchCriteria.getParamValue("status");
-
- ArrayList<Integer> statusList = new ArrayList<Integer>();
- if (statusObj == null) {
- statusList.add(XACommonEnums.STATUS_DISABLED);
- statusList.add(XACommonEnums.STATUS_ENABLED);
- } else {
- boolean status = restErrorUtil.parseBoolean(
- request.getParameter("status"), "Invalid value for "
- + "status", MessageEnums.INVALID_INPUT_DATA, null,
- "status");
- int statusEnum = (status == false) ? AppConstants.STATUS_DISABLED
- : AppConstants.STATUS_ENABLED;
- statusList.add(statusEnum);
- }
- searchCriteria.addParam("status", statusList);
-
- if (typeObj != null) {
- String type = typeObj.toString();
- int typeEnum = AppConstants.getEnumFor_AssetType(type);
- searchCriteria.addParam("type", typeEnum);
- }
- return searchCriteria;
- }
-
- public VXRepositoryList mapToVXRepositoryList(VXAssetList vXAssetList) {
-
- List<VXRepository> repoList = new ArrayList<VXRepository>();
- for (VXAsset vXAsset : vXAssetList.getVXAssets()) {
- VXRepository vXRepo = mapXAToPublicObject(vXAsset);
- repoList.add(vXRepo);
- }
- VXRepositoryList vXRepositoryList = new VXRepositoryList(repoList);
- return vXRepositoryList;
- }
-
-}
[41/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/model/RolePermission.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/model/RolePermission.java b/agents-impl/src/main/java/com/xasecure/pdp/model/RolePermission.java
deleted file mode 100644
index 53dfe6e..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/model/RolePermission.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * 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 com.xasecure.pdp.model;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class RolePermission {
-
- private List<String> users ;
- private List<String> groups ;
- private List<String> access ;
- private List<String> ipAddress ;
-
- public RolePermission() {
- users = new ArrayList<String>() ;
- groups = new ArrayList<String>() ;
- access = new ArrayList<String>() ;
- }
-
-
- public List<String> getUsers() {
- return users;
- }
-
- public void setUsers(List<String> users) {
- this.users = users;
- }
-
- public List<String> getGroups() {
- return groups;
- }
-
- public void setGroups(List<String> groups) {
- this.groups = groups;
- }
-
- public List<String> getAccess() {
- return this.access;
- }
-
- public List<String> getIpAddress() {
- return this.ipAddress;
- }
-
- public void setIpAddress(List<String> ipAddress) {
- this.ipAddress = ipAddress ;
- }
-
- public void setAccess(List<String> access) {
- this.access = access ;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/storm/StormAuthRule.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/storm/StormAuthRule.java b/agents-impl/src/main/java/com/xasecure/pdp/storm/StormAuthRule.java
deleted file mode 100644
index d7ec72d..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/storm/StormAuthRule.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * 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 com.xasecure.pdp.storm;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.commons.io.FilenameUtils;
-
-import com.xasecure.authorization.utils.StringUtil;
-
-public class StormAuthRule {
- private String topologyName ;
- private List<String> accessTypeList ;
- private List<String> groupList ;
- private List<String> userList;
- private boolean auditEnabled ;
-
-
- public StormAuthRule(String topologyName, List<String> accessTypeList,
- List<String> userList, List<String> groupList, boolean auditEnabled) {
- super();
- this.topologyName = topologyName;
- this.accessTypeList = accessTypeList;
- if (this.accessTypeList == null) {
- this.accessTypeList = new ArrayList<String>();
- }
- this.userList = userList;
- if (this.userList == null) {
- this.userList = new ArrayList<String>();
- }
-
- this.groupList = groupList;
- if (this.groupList == null) {
- this.groupList = new ArrayList<String>();
- }
-
- this.auditEnabled = auditEnabled ;
- }
-
- public String getTopologyName() {
- return topologyName;
- }
- public void setTopologyName(String topologyName) {
- this.topologyName = topologyName;
- }
- public List<String> getAccessTypeList() {
- return accessTypeList;
- }
- public void setAccessTypeList(List<String> accessTypeList) {
- this.accessTypeList = accessTypeList;
- }
- public List<String> getGroupList() {
- return groupList;
- }
- public void setGroupList(List<String> groupList) {
- this.groupList = groupList;
- }
- public List<String> getUserList() {
- return userList;
- }
- public void setUserList(List<String> userList) {
- this.userList = userList;
- }
-
- public boolean isMatchedTopology(String aTopologyName) {
-
- boolean ret = false ;
-
- if (aTopologyName == null || aTopologyName.length() == 0) {
- ret = "*".equals(this.topologyName) ;
- }
- else {
- ret = (aTopologyName.equals(this.topologyName) || FilenameUtils.wildcardMatch(aTopologyName,this.topologyName)) ;
- }
- return ret ;
- }
-
- public boolean isOperationAllowed(String aOperationName) {
- return this.accessTypeList.contains(aOperationName);
- }
-
- private static final String PUBLIC_GROUP_NAME = "public" ;
-
- public boolean isUserAllowed(String aUserName, String[] aGroupList) {
-
- boolean accessAllowed = false ;
-
- if ( this.userList.contains(aUserName) ) {
- accessAllowed = true ;
- }
- else if (this.groupList.contains(PUBLIC_GROUP_NAME)) {
- accessAllowed = true ;
- }
- else if (aGroupList != null ) {
- for(String userGroup : aGroupList ) {
- if (this.groupList.contains(userGroup) ) {
- accessAllowed = true ;
- break ;
- }
- }
- }
-
- return accessAllowed ;
- }
-
- public boolean getAuditEnabled() {
- return this.auditEnabled ;
- }
-
- @Override
- public String toString() {
- return "StormAuthRule: { topologyName: [" + topologyName + "]," +
- "userList: [" + StringUtil.toString(userList) + "]" +
- "groupList: [" + StringUtil.toString(groupList) + "]" +
- "accessTypeList: [" + StringUtil.toString(accessTypeList) + "]" +
- "auditEnabled: [" + auditEnabled + "] }";
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/storm/URLBasedAuthDB.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/storm/URLBasedAuthDB.java b/agents-impl/src/main/java/com/xasecure/pdp/storm/URLBasedAuthDB.java
deleted file mode 100644
index 3cb2916..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/storm/URLBasedAuthDB.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- * 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 com.xasecure.pdp.storm;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.xasecure.authorization.hadoop.config.XaSecureConfiguration;
-import com.xasecure.authorization.storm.XaStormAccessVerifier;
-import com.xasecure.pdp.config.PolicyChangeListener;
-import com.xasecure.pdp.config.PolicyRefresher;
-import com.xasecure.pdp.constants.XaSecureConstants;
-import com.xasecure.pdp.model.Policy;
-import com.xasecure.pdp.model.PolicyContainer;
-import com.xasecure.pdp.model.RolePermission;
-
-
-public class URLBasedAuthDB implements PolicyChangeListener, XaStormAccessVerifier {
-
- private static final Logger LOG = LoggerFactory.getLogger(URLBasedAuthDB.class) ;
-
- private static URLBasedAuthDB me = null;
-
- private PolicyRefresher refresher = null ;
-
- private PolicyContainer policyContainer = null;
-
- private List<StormAuthRule> stormAuthDB = null ;
-
- public static URLBasedAuthDB getInstance() {
- if (me == null) {
- synchronized (URLBasedAuthDB.class) {
- URLBasedAuthDB temp = me;
- if (temp == null) {
- me = new URLBasedAuthDB();
- me.init() ;
- }
- }
- }
- return me;
- }
-
- private URLBasedAuthDB() {
-
- String url = XaSecureConfiguration.getInstance().get(XaSecureConstants.XASECURE_STORM_POLICYMGR_URL_PROP);
-
- long refreshInMilli = XaSecureConfiguration.getInstance().getLong(
- XaSecureConstants.XASECURE_STORM_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_PROP ,
- XaSecureConstants.XASECURE_STORM_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_DEFAULT);
-
- String lastStoredFileName = XaSecureConfiguration.getInstance().get(XaSecureConstants.XASECURE_STORM_LAST_SAVED_POLICY_FILE_PROP) ;
-
- String sslConfigFileName = XaSecureConfiguration.getInstance().get(XaSecureConstants.XASECURE_STORM_POLICYMGR_SSL_CONFIG_FILE_PROP) ;
-
- refresher = new PolicyRefresher(url, refreshInMilli,sslConfigFileName,lastStoredFileName) ;
-
- String saveAsFileName = XaSecureConfiguration.getInstance().get(XaSecureConstants.XASECURE_STORM_POLICYMGR_URL_SAVE_FILE_PROP) ;
- if (saveAsFileName != null) {
- refresher.setSaveAsFileName(saveAsFileName) ;
- }
-
- if (lastStoredFileName != null) {
- refresher.setLastStoredFileName(lastStoredFileName);
- }
- }
-
-
- private void init() {
- refresher.setPolicyChangeListener(this);
- }
-
-
- @Override
- public void OnPolicyChange(PolicyContainer aPolicyContainer) {
- setPolicyContainer(aPolicyContainer);
- }
-
-
- public PolicyContainer getPolicyContainer() {
- return policyContainer;
- }
-
-
-
- public synchronized void setPolicyContainer(PolicyContainer aPolicyContainer) {
-
- if (aPolicyContainer != null) {
-
- List<StormAuthRule> tempStormAuthDB = new ArrayList<StormAuthRule>() ;
-
- for(Policy p : aPolicyContainer.getAcl()) {
-
- if (! p.isEnabled()) {
- continue;
- }
-
- for (String topologyName : p.getTopologyList()) {
-
- List<RolePermission> rpList = p.getPermissions() ;
-
- for(RolePermission rp : rpList) {
- StormAuthRule rule = new StormAuthRule(topologyName, rp.getAccess() , rp.getUsers(), rp.getGroups(), (p.getAuditInd() == 1)) ;
- tempStormAuthDB.add(rule) ;
- }
- }
- }
-
- this.stormAuthDB = tempStormAuthDB ;
-
- this.policyContainer = aPolicyContainer ;
- }
- }
-
- @Override
- public boolean isAccessAllowed(String aUserName, String[] aGroupName, String aOperationName, String aTopologyName) {
-
- boolean accessAllowed = false ;
-
- List<StormAuthRule> tempStormAuthDB = this.stormAuthDB ;
-
- if (tempStormAuthDB != null) {
- for(StormAuthRule rule : tempStormAuthDB) {
- if (rule.isMatchedTopology(aTopologyName)) {
- if (rule.isOperationAllowed(aOperationName)) {
- if (rule.isUserAllowed(aUserName, aGroupName)) {
- accessAllowed = true ;
- break ;
- }
- }
- }
- }
- }
-
- return accessAllowed ;
- }
-
- @Override
- public boolean isAudited(String aTopologyName) {
- boolean auditEnabled = false ;
-
- List<StormAuthRule> tempStormAuthDB = stormAuthDB ;
-
- if (tempStormAuthDB != null) {
- for(StormAuthRule rule : tempStormAuthDB) {
- if (rule.isMatchedTopology(aTopologyName)) {
- auditEnabled = rule.getAuditEnabled() ;
- if (auditEnabled) {
- break ;
- }
- }
- }
- }
-
- return auditEnabled ;
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/storm/XASecureAuthorizer.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/storm/XASecureAuthorizer.java b/agents-impl/src/main/java/com/xasecure/pdp/storm/XASecureAuthorizer.java
deleted file mode 100644
index 82a9c8d..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/storm/XASecureAuthorizer.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * 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 com.xasecure.pdp.storm;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import com.xasecure.authorization.storm.XaStormAccessVerifier;
-
-public class XASecureAuthorizer implements XaStormAccessVerifier {
-
- private static final Log LOG = LogFactory.getLog(XASecureAuthorizer.class) ;
-
- private static URLBasedAuthDB authDB = URLBasedAuthDB.getInstance() ;
-
-
- @Override
- public boolean isAccessAllowed(String aUserName, String[] aGroupName, String aOperationName, String aTopologyName) {
- boolean ret = false ;
-
- if (authDB != null) {
- ret = authDB.isAccessAllowed(aUserName, aGroupName, aOperationName, aTopologyName) ;
- }
- else {
- LOG.error("Unable to find a URLBasedAuthDB for authorization - Found null");
- }
-
- return ret ;
- }
-
- @Override
- public boolean isAudited(String aTopologyName) {
- boolean ret = false ;
-
- if (authDB != null) {
- ret = authDB.isAudited(aTopologyName) ;
- }
- else {
- LOG.error("Unable to find a URLBasedAuthDB for authorization - Found null");
- }
-
- return ret ;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/utils/XaSecureUtils.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/utils/XaSecureUtils.java b/agents-impl/src/main/java/com/xasecure/pdp/utils/XaSecureUtils.java
deleted file mode 100644
index 93c257e..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/utils/XaSecureUtils.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * 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 com.xasecure.pdp.utils;
-
-import java.io.File;
-import java.net.URL;
-
-public class XaSecureUtils {
-
- public static String getFilePathFromClassPath(String aFileName) {
- String pathName = null;
-
- File lf = new File(aFileName) ;
-
- if (lf.exists()) {
- pathName = lf.getAbsolutePath();
- }
- else {
- URL lurl = XaSecureUtils.class.getResource(aFileName);
- if (lurl == null) {
- if (!aFileName.startsWith("/")) {
- lurl = XaSecureUtils.class.getResource("/" + aFileName);
- }
- }
- if (lurl != null) {
- pathName = lurl.getFile();
- }
- }
- return pathName;
-
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/config/ConfigWatcher.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/config/ConfigWatcher.java b/agents-impl/src/main/java/org/apache/ranger/pdp/config/ConfigWatcher.java
new file mode 100644
index 0000000..63b6733
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/config/ConfigWatcher.java
@@ -0,0 +1,543 @@
+/**
+ * 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.pdp.config;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.security.KeyManagementException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.CertificateException;
+
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.ranger.authorization.hadoop.config.RangerConfiguration;
+import org.apache.ranger.authorization.hadoop.utils.RangerCredentialProvider;
+import org.apache.ranger.pdp.config.gson.PolicyExclusionStrategy;
+import org.apache.ranger.pdp.constants.RangerConstants;
+import org.apache.ranger.pdp.model.PolicyContainer;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.sun.jersey.api.client.Client;
+import com.sun.jersey.api.client.ClientResponse;
+import com.sun.jersey.api.client.WebResource;
+import com.sun.jersey.api.client.config.ClientConfig;
+import com.sun.jersey.api.client.config.DefaultClientConfig;
+import com.sun.jersey.client.urlconnection.HTTPSProperties;
+
+public abstract class ConfigWatcher extends Thread {
+
+ private static final Log LOG = LogFactory.getLog(ConfigWatcher.class);
+
+ public static final String EXPECTED_MIME_TYPE = "application/json" ;
+
+ // public static final String EXPECTED_MIME_TYPE = "application/octet-stream";
+
+ private static final String LASTUPDATED_PARAM = "epoch";
+ private static final String POLICY_COUNT_PARAM = "policyCount";
+ private static final String AGENT_NAME_PARAM = "agentId" ;
+
+ private static final int MAX_AGENT_NAME_LEN = 255 ;
+
+
+ private String url;
+
+ private long intervalInMilliSeconds;
+
+ private long lastModifiedTime = 0;
+
+ private boolean shutdownFlag = false;
+
+ private String lastStoredFileName = null;
+
+ protected PolicyContainer policyContainer = null;
+
+ private static PolicyExclusionStrategy policyExclusionStrategy = new PolicyExclusionStrategy();
+
+ private static RangerCredentialProvider rangerCp = null;
+
+
+ public abstract void doOnChange();
+
+ private String keyStoreFile = null ;
+ private String keyStoreFilepwd = null;
+ private String keyStoreURL = null;
+ private String keyStoreAlias = null;
+ private String trustStoreFile = null ;
+ private String trustStoreFilepwd = null ;
+ private String trustStoreURL = null;
+ private String trustStoreAlias = null;
+ private String keyStoreType = null ;
+ private String trustStoreType = null ;
+ private SSLContext sslContext = null ;
+ private HostnameVerifier hv = null ;
+ private String agentName = "unknown" ;
+
+ private String sslConfigFileName = null ;
+
+ public boolean policyCacheLoadedOnce = false;
+
+ public boolean cacheModfied = false;
+
+ public ConfigWatcher(String url, long aIntervalInMilliSeconds,String sslConfigFileName,String lastStoredFileName) {
+ super("RangerConfigURLWatcher");
+ setDaemon(true);
+ this.url = url;
+ intervalInMilliSeconds = aIntervalInMilliSeconds;
+ this.sslConfigFileName = sslConfigFileName ;
+ this.agentName = getAgentName(this.url) ;
+ this.lastStoredFileName = lastStoredFileName;
+ if (LOG.isInfoEnabled()) {
+ LOG.info("Creating PolicyRefreshser with url: " + url +
+ ", refreshInterval(milliSeconds): " + aIntervalInMilliSeconds +
+ ", sslConfigFileName: " + sslConfigFileName +
+ ", lastStoredFileName: " + lastStoredFileName);
+ }
+ init();
+ validateAndRun();
+ LOG.debug("Created new ConfigWatcher for URL [" + url + "]");
+ }
+
+
+ public void init() {
+ if (sslConfigFileName != null) {
+ LOG.debug("Loading SSL Configuration from [" + sslConfigFileName + "]");
+ InputStream in = null ;
+ try {
+ Configuration conf = new Configuration() ;
+ in = getFileInputStream(sslConfigFileName) ;
+ if (in != null) {
+ conf.addResource(in);
+ }
+
+ rangerCp = RangerCredentialProvider.getInstance();
+
+ keyStoreFile = conf.get(RangerConstants.RANGER_POLICYMGR_CLIENT_KEY_FILE);
+
+ keyStoreURL=conf.get(RangerConstants.RANGER_POLICYMGR_CLIENT_KEY_FILE_CREDENTIAL);
+ keyStoreAlias=RangerConstants.RANGER_POLICYMGR_CLIENT_KEY_FILE_CREDENTIAL_ALIAS;
+
+ char[] v_keyStoreFilePwd = getCredential(keyStoreURL,keyStoreAlias);
+ if ( v_keyStoreFilePwd == null ) {
+ keyStoreFilepwd = null;
+ } else {
+ keyStoreFilepwd = new String(v_keyStoreFilePwd);
+ }
+
+ trustStoreFile = conf.get(RangerConstants.RANGER_POLICYMGR_TRUSTSTORE_FILE);
+
+ trustStoreURL=conf.get(RangerConstants.RANGER_POLICYMGR_TRUSTSTORE_FILE_CREDENTIAL);
+ trustStoreAlias=RangerConstants.RANGER_POLICYMGR_TRUSTSTORE_FILE_CREDENTIAL_ALIAS;
+
+ char[] v_TrustStoreFilePwd = getCredential(trustStoreURL,trustStoreAlias);
+ if ( v_TrustStoreFilePwd == null ) {
+ trustStoreFilepwd = null;
+ } else {
+ trustStoreFilepwd = new String(v_TrustStoreFilePwd);
+ }
+
+
+ keyStoreType = conf.get(RangerConstants.RANGER_POLICYMGR_CLIENT_KEY_FILE_TYPE, RangerConstants.RANGER_POLICYMGR_CLIENT_KEY_FILE_TYPE_DEFAULT);
+ trustStoreType = conf.get(RangerConstants.RANGER_POLICYMGR_TRUSTSTORE_FILE_TYPE, RangerConstants.RANGER_POLICYMGR_TRUSTSTORE_FILE_TYPE_DEFAULT);
+ }
+ catch(IOException ioe) {
+ LOG.error("Unable to load SSL Config FileName: [" + sslConfigFileName + "]", ioe);
+ }
+ finally {
+ if (in != null) {
+ try {
+ in.close() ;
+ } catch (IOException e) {
+ LOG.error("Unable to close SSL Config FileName: [" + sslConfigFileName + "]", e) ;
+ }
+ }
+ }
+
+ LOG.debug("Keystore filename:[" + keyStoreFile + "]");
+ LOG.debug("TrustStore filename:[" + trustStoreFile + "]");
+
+ }
+ }
+
+ public String getURL() {
+ return url;
+ }
+
+ public long getIntervalInMilliSeconds() {
+ return intervalInMilliSeconds;
+ }
+
+ public long getLastModifiedTime() {
+ return lastModifiedTime;
+ }
+
+ public void run() {
+ while (!shutdownFlag) {
+ validateAndRun();
+ try {
+ Thread.sleep(intervalInMilliSeconds);
+ } catch (InterruptedException e) {
+ LOG.error("Unable to complete sleep for [" + intervalInMilliSeconds + "]", e);
+ }
+ }
+ }
+
+ private void validateAndRun() {
+ if (isFileChanged()) {
+ LOG.debug("Policy has been changed from " + url + " ... RELOADING");
+ try {
+ doOnChange();
+ } catch (Exception e) {
+ LOG.error("Unable to complete doOnChange() method on file change [" + url + "]", e);
+ }
+ } else {
+ LOG.debug("No Change found in the policy from " + url);
+ }
+ }
+
+ public boolean iscacheModfied() {
+ return cacheModfied;
+ }
+
+ private boolean isFileChanged() {
+ boolean isChanged = false;
+
+ cacheModfied = false;
+ try {
+
+ Client client = null;
+ ClientResponse response = null;
+
+ try {
+
+ int policyCount = getPolicyCount(policyContainer);
+
+ if (url.contains("https")) {
+ // build SSL Client
+ client = buildSSLClient();
+ }
+
+ if (client == null) {
+ client = Client.create();
+ }
+
+ WebResource webResource = client.resource(url)
+ .queryParam(LASTUPDATED_PARAM, String.valueOf(lastModifiedTime))
+ .queryParam(POLICY_COUNT_PARAM, String.valueOf(policyCount))
+ .queryParam(AGENT_NAME_PARAM, agentName);
+
+ response = webResource.accept(EXPECTED_MIME_TYPE).get(ClientResponse.class);
+
+
+ if (response != null) {
+
+ boolean responsePresent = true;
+ int responseStatus = response.getStatus();
+
+ if ( fetchPolicyfromCahce(responsePresent,responseStatus,lastStoredFileName) ) {
+ /* If the response is other than 200 and 304 load the policy from the cache */
+ isChanged = true;
+
+ } else {
+ /* If Policy Manager is available fetch the policy from it */
+ if (response.getStatus() == 200) {
+ String jsonString = response.getEntity(String.class);
+ Gson gson = new GsonBuilder().setPrettyPrinting().addDeserializationExclusionStrategy(policyExclusionStrategy).create();
+ PolicyContainer newPolicyContainer = gson.fromJson(jsonString, PolicyContainer.class);
+ if ((newPolicyContainer.getLastUpdatedTimeInEpoc() > lastModifiedTime) || (getPolicyCount(newPolicyContainer) != policyCount)) {
+ policyContainer = newPolicyContainer;
+ lastModifiedTime = policyContainer.getLastUpdatedTimeInEpoc();
+ isChanged = true;
+ policyCacheLoadedOnce = false;
+ cacheModfied = true;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Got response: 200 with {change in lastupdatedTime}\n" + gson.toJson(newPolicyContainer));
+ }
+ } else {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Got response: 200 with {no-change in lastupdatedTime}\n" + gson.toJson(newPolicyContainer));
+ }
+ isChanged = false;
+ }
+ } else if (response.getStatus() == 304) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Got response: 304 ");
+ }
+ isChanged = false; // No Change has been there since our
+ // earlier request
+ } else {
+ LOG.error("Unable to get a valid response for isFileChanged() call for [" + url + "] = response code found [" + response.getStatus() + "]");
+ }
+ }
+
+ } else {
+ LOG.error("Unable to get a valid response for isFileChanged() call for [" + url + "] - got null response.");
+ // force the policy update to get fresh copy
+ lastModifiedTime = 0;
+ }
+
+ } finally {
+ if (response != null) {
+ response.close();
+ }
+ if (client != null) {
+ client.destroy();
+ }
+ }
+ } catch (Throwable t) {
+
+ boolean responsePresent = false;
+ int responseStatus = -1;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Policy Manager Failed",t);
+ }
+ if ( fetchPolicyfromCahce(responsePresent,responseStatus,lastStoredFileName) ) {
+ /* Successfully found the Policy Cache file and loaded */
+ isChanged = false;
+ } else {
+ LOG.error("Unable to complete isFileChanged() call for [" + url + "]", t);
+ // force the policy update to get fresh copy
+ lastModifiedTime = 0;
+ LOG.error("Policy file Cache not found..");
+ throw new RuntimeException("Unable to find Enterprise Policy Storage");
+ }
+
+ } finally {
+ if (isChanged) {
+ LOG.info("URL: [" + url + "], isModified: " + isChanged + ", lastModifiedTime:" + lastModifiedTime);
+ } else if (LOG.isDebugEnabled()) {
+ LOG.debug("URL: [" + url + "], isModified: " + isChanged + ", lastModifiedTime:" + lastModifiedTime);
+ }
+ }
+ return isChanged;
+ }
+
+ public PolicyContainer getPolicyContainer() {
+ return policyContainer;
+ }
+
+ private int getPolicyCount(PolicyContainer aPolicyContainer) {
+ return (aPolicyContainer == null ? 0 : (aPolicyContainer.getAcl() == null ? 0 : aPolicyContainer.getAcl().size()));
+ }
+
+
+ public synchronized Client buildSSLClient() {
+ Client client = null;
+ try {
+
+ ClientConfig config = new DefaultClientConfig();
+
+ if (sslContext == null) {
+
+ KeyManager[] kmList = null;
+ TrustManager[] tmList = null;
+
+ if (keyStoreFile != null && keyStoreFilepwd != null) {
+
+ KeyStore keyStore = KeyStore.getInstance(keyStoreType);
+ InputStream in = null ;
+ try {
+ in = getFileInputStream(keyStoreFile) ;
+ if (in == null) {
+ LOG.error("Unable to obtain keystore from file [" + keyStoreFile + "]");
+ return client ;
+ }
+ keyStore.load(in, keyStoreFilepwd.toCharArray());
+ KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(RangerConstants.RANGER_SSL_KEYMANAGER_ALGO_TYPE);
+ keyManagerFactory.init(keyStore, keyStoreFilepwd.toCharArray());
+ kmList = keyManagerFactory.getKeyManagers();
+ }
+ finally {
+ if (in != null) {
+ in.close();
+ }
+ }
+
+ }
+
+ if (trustStoreFile != null && trustStoreFilepwd != null) {
+
+ KeyStore trustStore = KeyStore.getInstance(trustStoreType);
+ InputStream in = null ;
+ try {
+ in = getFileInputStream(trustStoreFile) ;
+ if (in == null) {
+ LOG.error("Unable to obtain keystore from file [" + trustStoreFile + "]");
+ return client ;
+ }
+ trustStore.load(in, trustStoreFilepwd.toCharArray());
+ TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(RangerConstants.RANGER_SSL_TRUSTMANAGER_ALGO_TYPE);
+ trustManagerFactory.init(trustStore);
+ tmList = trustManagerFactory.getTrustManagers();
+ }
+ finally {
+ if (in != null) {
+ in.close() ;
+ }
+ }
+ }
+
+ sslContext = SSLContext.getInstance(RangerConstants.RANGER_SSL_CONTEXT_ALGO_TYPE);
+
+ sslContext.init(kmList, tmList, new SecureRandom());
+
+ hv = new HostnameVerifier() {
+ public boolean verify(String urlHostName, SSLSession session) {
+ return session.getPeerHost().equals(urlHostName);
+ }
+ };
+
+ }
+
+ config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(hv, sslContext));
+
+ client = Client.create(config);
+
+ } catch (KeyStoreException e) {
+ LOG.error("Unable to obtain from KeyStore", e);
+ } catch (NoSuchAlgorithmException e) {
+ LOG.error("SSL algorithm is available in the environment", e);
+ } catch (CertificateException e) {
+ LOG.error("Unable to obtain the requested certification ", e);
+ } catch (FileNotFoundException e) {
+ LOG.error("Unable to find the necessary SSL Keystore and TrustStore Files", e);
+ } catch (IOException e) {
+ LOG.error("Unable to read the necessary SSL Keystore and TrustStore Files", e);
+ } catch (KeyManagementException e) {
+ LOG.error("Unable to initials the SSLContext", e);
+ } catch (UnrecoverableKeyException e) {
+ LOG.error("Unable to recover the key from keystore", e);
+ }
+ return client;
+ }
+
+ private InputStream getFileInputStream(String fileName) throws IOException {
+ InputStream in = null ;
+
+ File f = new File(fileName) ;
+
+ if (f.exists()) {
+ in = new FileInputStream(f) ;
+ }
+ else {
+ in = ClassLoader.getSystemResourceAsStream(fileName) ;
+ }
+ return in ;
+ }
+
+ public static String getAgentName(String aUrl) {
+ String hostName = null ;
+ String repoName = null ;
+ try {
+ hostName = InetAddress.getLocalHost().getHostName() ;
+ } catch (UnknownHostException e) {
+ LOG.error("ERROR: Unable to find hostname for the agent ", e);
+ hostName = "unknownHost" ;
+ }
+
+ String[] tokens = aUrl.split("/") ;
+
+ if ( tokens.length > 0 ) {
+ repoName = tokens[tokens.length-1] ;
+ }
+ else {
+ repoName = "unknownRepo" ;
+ }
+
+ String agentName = hostName + "-" + repoName ;
+
+ if (agentName.length() > MAX_AGENT_NAME_LEN ) {
+ agentName = agentName.substring(0,MAX_AGENT_NAME_LEN) ;
+ }
+
+ return agentName ;
+ }
+
+ private boolean fetchPolicyfromCahce( boolean responsePresent, int responseStatus, String lastStoredFileName){
+
+ boolean cacheFound = false;
+
+ if ( ( responsePresent == false ) || ( responseStatus != 200 && responseStatus != 304) ) {
+
+ /* Policy Manager not available read the policy from the last enforced one */
+
+ if (policyCacheLoadedOnce) {
+ cacheFound = true;
+ return cacheFound;
+ }
+
+ try {
+ /* read the last stored policy file and load the PolicyContainer */
+ LOG.info("Policy Manager not available, using the last stored Policy File" + this.lastStoredFileName );
+ LOG.debug("LastStoredFileName when policymgr was available" + this.lastStoredFileName);
+
+ BufferedReader jsonString = new BufferedReader(new FileReader(this.lastStoredFileName));
+ Gson gson = new GsonBuilder().setPrettyPrinting().addDeserializationExclusionStrategy(policyExclusionStrategy).create();
+ PolicyContainer newPolicyContainer = gson.fromJson(jsonString, PolicyContainer.class);
+ policyContainer = newPolicyContainer;
+ lastModifiedTime = policyContainer.getLastUpdatedTimeInEpoc();
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Policy Manager not available.Got response =" + responseStatus +"\n" + gson.toJson(newPolicyContainer));
+ }
+
+ cacheFound = true;
+ policyCacheLoadedOnce = true;
+
+ } catch( FileNotFoundException fe ){
+
+ /* unable to get the last stored policy, raise warning for unavailability of policy cache file and continue...*/
+ if ( this.lastStoredFileName == null ) {
+ LOG.info("Policy cache file not found...XAagent authorization not enabled");
+ }
+ else {
+ LOG.info("Unable to access Policy cache file...XAagent authorization not enabled");
+ }
+ }
+
+ }
+
+ return cacheFound;
+ }
+
+ private char[] getCredential(String url, String alias) {
+ char[] credStr=rangerCp.getCredentialString(url,alias);
+ return credStr;
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/config/Jersey2ConfigWatcher.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/config/Jersey2ConfigWatcher.java b/agents-impl/src/main/java/org/apache/ranger/pdp/config/Jersey2ConfigWatcher.java
new file mode 100644
index 0000000..4fcb489
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/config/Jersey2ConfigWatcher.java
@@ -0,0 +1,565 @@
+/**
+ * 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.pdp.config;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.security.KeyManagementException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.CertificateException;
+
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+import javax.ws.rs.client.Client;
+import javax.ws.rs.client.ClientBuilder;
+import javax.ws.rs.client.WebTarget;
+import javax.ws.rs.core.Response;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.ranger.authorization.hadoop.utils.RangerCredentialProvider;
+import org.apache.ranger.pdp.config.gson.PolicyExclusionStrategy;
+import org.apache.ranger.pdp.constants.RangerConstants;
+import org.apache.ranger.pdp.model.PolicyContainer;
+import org.glassfish.jersey.client.ClientConfig;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.sun.jersey.client.urlconnection.HTTPSProperties;
+
+public abstract class Jersey2ConfigWatcher extends Thread {
+
+ private static final Log LOG = LogFactory.getLog(Jersey2ConfigWatcher.class);
+
+ public static final String EXPECTED_MIME_TYPE = "application/json" ;
+
+ // public static final String EXPECTED_MIME_TYPE = "application/octet-stream";
+
+ private static final String LASTUPDATED_PARAM = "epoch";
+ private static final String POLICY_COUNT_PARAM = "policyCount";
+ private static final String AGENT_NAME_PARAM = "agentId" ;
+
+ private static final int MAX_AGENT_NAME_LEN = 255 ;
+
+ private static final String RANGER_KNOX_CREDENTIAL_PROVIDER_FILE
+ = "xasecure.knox.credential.provider.file";
+
+ private String url;
+
+ private long intervalInMilliSeconds;
+
+ private long lastModifiedTime = 0;
+
+ private boolean shutdownFlag = false;
+
+ private String lastStoredFileName = null;
+
+ protected PolicyContainer policyContainer = null;
+
+ private static PolicyExclusionStrategy policyExclusionStrategy = new PolicyExclusionStrategy();
+
+ private static RangerCredentialProvider rangerCp = null;
+
+ public abstract void doOnChange();
+
+ private String credentialProviderFile = null;
+ private String keyStoreFile = null ;
+ private String keyStorePassword = null;
+ private String trustStoreFile = null ;
+ private String trustStorePassword = null ;
+ private String keyStoreType = null ;
+ private String trustStoreType = null ;
+ private SSLContext sslContext = null ;
+ private HostnameVerifier hv = null ;
+ private String agentName = "unknown" ;
+
+ private String sslConfigFileName = null ;
+
+ boolean policyCacheLoadedOnce = false;
+
+ public Jersey2ConfigWatcher(String url, long aIntervalInMilliSeconds,String sslConfigFileName,String lastStoredFileName) {
+ super("RangerConfigURLWatcher");
+ setDaemon(true);
+ this.url = url;
+ intervalInMilliSeconds = aIntervalInMilliSeconds;
+ this.sslConfigFileName = sslConfigFileName ;
+ this.agentName = getAgentName(this.url) ;
+ this.lastStoredFileName = lastStoredFileName;
+ if (LOG.isInfoEnabled()) {
+ LOG.info("Creating PolicyRefreshser with url: " + url +
+ ", refreshInterval(milliSeconds): " + aIntervalInMilliSeconds +
+ ", sslConfigFileName: " + sslConfigFileName +
+ ", lastStoredFileName: " + lastStoredFileName);
+ }
+ init();
+ validateAndRun();
+ LOG.debug("Created new ConfigWatcher for URL [" + url + "]");
+ }
+
+
+ public void init() {
+ if (sslConfigFileName != null) {
+ LOG.debug("Loading SSL Configuration from [" + sslConfigFileName
+ + "]");
+ InputStream in = null;
+ try {
+ Configuration conf = new Configuration();
+ in = getFileInputStream(sslConfigFileName);
+ if (in != null) {
+ conf.addResource(in);
+ }
+
+ if (url.startsWith("https")) {
+ rangerCp = RangerCredentialProvider.getInstance();
+
+ keyStoreFile = conf
+ .get(RangerConstants.RANGER_POLICYMGR_CLIENT_KEY_FILE);
+
+ credentialProviderFile = conf
+ .get(RANGER_KNOX_CREDENTIAL_PROVIDER_FILE);
+ String keyStorePasswordAlias = RangerConstants.RANGER_POLICYMGR_CLIENT_KEY_FILE_CREDENTIAL_ALIAS;
+
+ char[] v_keyStorePassword = getCredential(credentialProviderFile,
+ keyStorePasswordAlias);
+ if (v_keyStorePassword == null) {
+ keyStorePassword = null;
+ } else {
+ keyStorePassword = new String(v_keyStorePassword);
+ }
+
+ trustStoreFile = conf
+ .get(RangerConstants.RANGER_POLICYMGR_TRUSTSTORE_FILE);
+
+ //trustStoreURL = conf
+ // .get(RangerConstants.RANGER_POLICYMGR_TRUSTSTORE_FILE_CREDENTIAL);
+ String trustStorePasswordAlias = RangerConstants.RANGER_POLICYMGR_TRUSTSTORE_FILE_CREDENTIAL_ALIAS;
+
+ char[] v_trustStorePassword = getCredential(credentialProviderFile,
+ trustStorePasswordAlias);
+ if (v_trustStorePassword == null) {
+ trustStorePassword = null;
+ } else {
+ trustStorePassword = new String(v_trustStorePassword);
+ }
+
+ keyStoreType = conf
+ .get(RangerConstants.RANGER_POLICYMGR_CLIENT_KEY_FILE_TYPE,
+ RangerConstants.RANGER_POLICYMGR_CLIENT_KEY_FILE_TYPE_DEFAULT);
+ trustStoreType = conf
+ .get(RangerConstants.RANGER_POLICYMGR_TRUSTSTORE_FILE_TYPE,
+ RangerConstants.RANGER_POLICYMGR_TRUSTSTORE_FILE_TYPE_DEFAULT);
+ }
+ } catch (IOException ioe) {
+ LOG.error("Unable to load SSL Config FileName: ["
+ + sslConfigFileName + "]", ioe);
+ } finally {
+ if (in != null) {
+ try {
+ in.close();
+ } catch (IOException e) {
+ LOG.error("Unable to close SSL Config FileName: ["
+ + sslConfigFileName + "]", e);
+ }
+ }
+ }
+
+ LOG.debug("Keystore filename:[" + keyStoreFile + "]");
+ LOG.debug("TrustStore filename:[" + trustStoreFile + "]");
+
+ }
+ }
+
+ public String getURL() {
+ return url;
+ }
+
+ public long getIntervalInMilliSeconds() {
+ return intervalInMilliSeconds;
+ }
+
+ public long getLastModifiedTime() {
+ return lastModifiedTime;
+ }
+
+ public void run() {
+ while (!shutdownFlag) {
+ validateAndRun();
+ try {
+ Thread.sleep(intervalInMilliSeconds);
+ } catch (InterruptedException e) {
+ LOG.error("Unable to complete sleep for [" + intervalInMilliSeconds + "]", e);
+ }
+ }
+ }
+
+ private void validateAndRun() {
+ if (isFileChanged()) {
+ LOG.debug("Policy has been changed from " + url + " ... RELOADING");
+ try {
+ doOnChange();
+ } catch (Exception e) {
+ LOG.error("Unable to complete doOnChange() method on file change [" + url + "]", e);
+ }
+ } else {
+ LOG.debug("No Change found in the policy from " + url);
+ }
+ }
+
+ private boolean isFileChanged() {
+ boolean isChanged = false;
+
+
+ try {
+
+ Client client = null;
+ Response response = null;
+
+ try {
+
+ int policyCount = getPolicyCount(policyContainer);
+
+ if (url.contains("https")) {
+ // build SSL Client
+ client = buildSSLClient();
+ }
+
+ if (client == null) {
+ client = ClientBuilder.newClient();
+ }
+
+ WebTarget webTarget = client.target(url)
+ .queryParam(LASTUPDATED_PARAM, String.valueOf(lastModifiedTime))
+ .queryParam(POLICY_COUNT_PARAM, String.valueOf(policyCount))
+ .queryParam(AGENT_NAME_PARAM, agentName);
+
+ response = webTarget.request().accept(EXPECTED_MIME_TYPE).get();
+
+
+ if (response != null) {
+
+ Boolean responsePresent = true;
+ int responseStatus = response.getStatus();
+
+ if ( fetchPolicyfromCahce(responsePresent,responseStatus,lastStoredFileName) ) {
+ /* If the response is other than 200 and 304 load the policy from the cache */
+ isChanged = true;
+
+ } else {
+ /*
+ * If Policy Manager is available fetch the policy from
+ * it
+ */
+ if (response.getStatus() == 200) {
+
+ String entityString = response
+ .readEntity(String.class);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("JSON response from server: "
+ + entityString);
+ }
+
+ Gson gson = new GsonBuilder()
+ .setPrettyPrinting()
+ .addDeserializationExclusionStrategy(
+ policyExclusionStrategy).create();
+ PolicyContainer newPolicyContainer = gson.fromJson(
+ entityString, PolicyContainer.class);
+ if ((newPolicyContainer.getLastUpdatedTimeInEpoc() > lastModifiedTime)
+ || (getPolicyCount(newPolicyContainer) != policyCount)) {
+ policyContainer = newPolicyContainer;
+ lastModifiedTime = policyContainer
+ .getLastUpdatedTimeInEpoc();
+ isChanged = true;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Got response: 200 with {change in lastupdatedTime}\n"
+ + gson.toJson(newPolicyContainer));
+ }
+ } else {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Got response: 200 with {no-change in lastupdatedTime}\n"
+ + gson.toJson(newPolicyContainer));
+ }
+ isChanged = false;
+ }
+ } else if (response.getStatus() == 304) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Got response: 304 ");
+ }
+ isChanged = false; // No Change has been there since
+ // our
+ // earlier request
+ } else {
+ LOG.error("Unable to get a valid response for isFileChanged() call for ["
+ + url
+ + "] = response code found ["
+ + response.getStatus() + "]");
+ }
+ }
+
+ } else {
+ LOG.error("Unable to get a valid response for isFileChanged() call for [" + url + "] - got null response.");
+ // force the policy update to get fresh copy
+ lastModifiedTime = 0;
+ }
+
+ } finally {
+ if (response != null) {
+ response.close();
+ }
+ if (client != null) {
+ client.close();
+ }
+ }
+ } catch (Throwable t) {
+
+ Boolean responsePresent = false;
+ int responseStatus = -1;
+
+ if ( fetchPolicyfromCahce(responsePresent,responseStatus,lastStoredFileName) ) {
+ /* Successfully found the Policy Cache file and loaded */
+ isChanged = true;
+ } else {
+ LOG.error("Unable to complete isFileChanged() call for [" + url + "]", t);
+ // force the policy update to get fresh copy
+ lastModifiedTime = 0;
+ LOG.error("Policy file Cache not found..");
+ throw new RuntimeException("Unable to find Enterprise Policy Storage");
+ }
+
+ } finally {
+ if (isChanged) {
+ LOG.info("URL: [" + url + "], isModified: " + isChanged + ", lastModifiedTime:" + lastModifiedTime);
+ } else if (LOG.isDebugEnabled()) {
+ LOG.debug("URL: [" + url + "], isModified: " + isChanged + ", lastModifiedTime:" + lastModifiedTime);
+ }
+ }
+ return isChanged;
+ }
+
+ public PolicyContainer getPolicyContainer() {
+ return policyContainer;
+ }
+
+ private int getPolicyCount(PolicyContainer aPolicyContainer) {
+ return (aPolicyContainer == null ? 0 : (aPolicyContainer.getAcl() == null ? 0 : aPolicyContainer.getAcl().size()));
+ }
+
+
+ public synchronized Client buildSSLClient() {
+ Client client = null;
+ try {
+
+ ClientConfig config = new ClientConfig();
+
+ if (sslContext == null) {
+
+ KeyManager[] kmList = null;
+ TrustManager[] tmList = null;
+
+ if (keyStoreFile != null && keyStorePassword != null) {
+
+ KeyStore keyStore = KeyStore.getInstance(keyStoreType);
+ InputStream in = null ;
+ try {
+ in = getFileInputStream(keyStoreFile) ;
+ if (in == null) {
+ LOG.error("Unable to obtain keystore from file [" + keyStoreFile + "]");
+ return client ;
+ }
+ keyStore.load(in, keyStorePassword.toCharArray());
+ KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(RangerConstants.RANGER_SSL_KEYMANAGER_ALGO_TYPE);
+ keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
+ kmList = keyManagerFactory.getKeyManagers();
+ }
+ finally {
+ if (in != null) {
+ in.close();
+ }
+ }
+
+ }
+
+ if (trustStoreFile != null && trustStorePassword != null) {
+
+ KeyStore trustStore = KeyStore.getInstance(trustStoreType);
+ InputStream in = null ;
+ try {
+ in = getFileInputStream(trustStoreFile) ;
+ if (in == null) {
+ LOG.error("Unable to obtain keystore from file [" + trustStoreFile + "]");
+ return client ;
+ }
+ trustStore.load(in, trustStorePassword.toCharArray());
+ TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(RangerConstants.RANGER_SSL_TRUSTMANAGER_ALGO_TYPE);
+ trustManagerFactory.init(trustStore);
+ tmList = trustManagerFactory.getTrustManagers();
+ }
+ finally {
+ if (in != null) {
+ in.close() ;
+ }
+ }
+ }
+
+ sslContext = SSLContext.getInstance(RangerConstants.RANGER_SSL_CONTEXT_ALGO_TYPE);
+
+ sslContext.init(kmList, tmList, new SecureRandom());
+
+ hv = new HostnameVerifier() {
+ public boolean verify(String urlHostName, SSLSession session) {
+ return session.getPeerHost().equals(urlHostName);
+ }
+ };
+
+ }
+
+ config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(hv, sslContext));
+
+ client = ClientBuilder.newClient(config);
+
+ } catch (KeyStoreException e) {
+ LOG.error("Unable to obtain from KeyStore", e);
+ } catch (NoSuchAlgorithmException e) {
+ LOG.error("SSL algorithm is available in the environment", e);
+ } catch (CertificateException e) {
+ LOG.error("Unable to obtain the requested certification ", e);
+ } catch (FileNotFoundException e) {
+ LOG.error("Unable to find the necessary SSL Keystore and TrustStore Files", e);
+ } catch (IOException e) {
+ LOG.error("Unable to read the necessary SSL Keystore and TrustStore Files", e);
+ } catch (KeyManagementException e) {
+ LOG.error("Unable to initials the SSLContext", e);
+ } catch (UnrecoverableKeyException e) {
+ LOG.error("Unable to recover the key from keystore", e);
+ }
+ return client;
+ }
+
+ private InputStream getFileInputStream(String fileName) throws IOException {
+ InputStream in = null ;
+
+ File f = new File(fileName) ;
+
+ if (f.exists()) {
+ in = new FileInputStream(f) ;
+ }
+ else {
+ in = ClassLoader.getSystemResourceAsStream(fileName) ;
+ }
+ return in ;
+ }
+
+ public static String getAgentName(String aUrl) {
+ String hostName = null ;
+ String repoName = null ;
+ try {
+ hostName = InetAddress.getLocalHost().getHostName() ;
+ } catch (UnknownHostException e) {
+ LOG.error("ERROR: Unable to find hostname for the agent ", e);
+ hostName = "unknownHost" ;
+ }
+
+ String[] tokens = aUrl.split("/") ;
+
+ if ( tokens.length > 0 ) {
+ repoName = tokens[tokens.length-1] ;
+ }
+ else {
+ repoName = "unknownRepo" ;
+ }
+
+ String agentName = hostName + "-" + repoName ;
+
+ if (agentName.length() > MAX_AGENT_NAME_LEN ) {
+ agentName = agentName.substring(0,MAX_AGENT_NAME_LEN) ;
+ }
+
+ return agentName ;
+ }
+
+ private boolean fetchPolicyfromCahce( Boolean responsePresent, int responseStatus, String lastStoredFileName){
+
+ boolean cacheFound = false;
+
+ if ( ( responsePresent == false ) || ( responseStatus != 200 && responseStatus != 304) ) {
+
+ /* Policy Manager not available read the policy from the last enforced one */
+
+ if (policyCacheLoadedOnce) {
+ cacheFound = true;
+ return cacheFound;
+ }
+
+ try {
+ /* read the last stored policy file and load the PolicyContainer */
+ LOG.info("Policy Manager not available, using the last stored Policy File" + this.lastStoredFileName );
+ LOG.debug("LastStoredFileName when policymgr was available" + this.lastStoredFileName);
+
+ BufferedReader jsonString = new BufferedReader(new FileReader(this.lastStoredFileName));
+ Gson gson = new GsonBuilder().setPrettyPrinting().addDeserializationExclusionStrategy(policyExclusionStrategy).create();
+ PolicyContainer newPolicyContainer = gson.fromJson(jsonString, PolicyContainer.class);
+ policyContainer = newPolicyContainer;
+ lastModifiedTime = policyContainer.getLastUpdatedTimeInEpoc();
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Policy Manager not available.Got response =" + responseStatus +"\n" + gson.toJson(newPolicyContainer));
+ }
+
+ cacheFound = true;
+ policyCacheLoadedOnce = true;
+
+ } catch( FileNotFoundException fe ){
+
+ /* unable to get the last stored policy, raise warning for unavailability of policy cache file and continue...*/
+ if ( this.lastStoredFileName == null ) {
+ LOG.info("Policy cache file not found...XAagent authorization not enabled");
+ }
+ else {
+ LOG.info("Unable to access Policy cache file...XAagent authorization not enabled");
+ }
+ }
+
+ }
+
+ return cacheFound;
+ }
+
+ private char[] getCredential(String url, String alias) {
+ char[] credStr=rangerCp.getCredentialString(url,alias);
+ return credStr;
+ }
+
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/config/Jersey2PolicyRefresher.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/config/Jersey2PolicyRefresher.java b/agents-impl/src/main/java/org/apache/ranger/pdp/config/Jersey2PolicyRefresher.java
new file mode 100644
index 0000000..112b89a
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/config/Jersey2PolicyRefresher.java
@@ -0,0 +1,207 @@
+/*
+ * 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.pdp.config;
+
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.pdp.config.gson.PolicyExclusionStrategy;
+import org.apache.ranger.pdp.model.PolicyContainer;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+public class Jersey2PolicyRefresher {
+
+ private static final Log LOG = LogFactory.getLog(Jersey2PolicyRefresher.class);
+
+ private String url ;
+ private long refreshInterval ;
+
+ private Jersey2ConfigWatcher watcherDaemon = null;
+
+ protected PolicyContainer policyContainer = null ;
+
+ private PolicyChangeListener policyChangeListener = null ;
+
+ private String saveAsFileName = null ;
+
+ private String sslConfigFileName = null ;
+
+ private String lastStoredFileName = null;
+
+ private PolicyExclusionStrategy policyExclusionStrategy = new PolicyExclusionStrategy() ;
+
+ public Jersey2PolicyRefresher(String url, long refreshInterval, String sslConfigFileName, String lastStoredFileName) {
+ if (LOG.isInfoEnabled()) {
+ LOG.info("Creating PolicyRefreshser with url: " + url +
+ ", refreshInterval: " + refreshInterval +
+ ", sslConfigFileName: " + sslConfigFileName +
+ ", lastStoredFileName: " + lastStoredFileName);
+ }
+ this.url = url ;
+ this.refreshInterval = refreshInterval ;
+ this.sslConfigFileName = sslConfigFileName ;
+ this.lastStoredFileName = lastStoredFileName;
+ checkFileWatchDogThread();
+ }
+
+ public PolicyChangeListener getPolicyChangeListener() {
+ return policyChangeListener;
+ }
+
+ public synchronized void setPolicyChangeListener(PolicyChangeListener policyChangeListener) {
+ this.policyChangeListener = policyChangeListener;
+ if (this.policyContainer != null) {
+ savePolicyToFile() ;
+ notifyPolicyChange() ;
+ }
+ }
+
+ private void setPolicyContainer(PolicyContainer aPolicyContainer) {
+ this.policyContainer = aPolicyContainer ;
+ }
+
+ public PolicyContainer getPolicyContainer() {
+ return policyContainer ;
+ }
+
+ public String getSaveAsFileName() {
+ return saveAsFileName;
+ }
+
+ public void setSaveAsFileName(String saveAsFileName) {
+ this.saveAsFileName = saveAsFileName;
+ }
+
+ public String getSslConfigFileName() {
+ return sslConfigFileName;
+ }
+
+ public String getLastStoredFileName() {
+ return lastStoredFileName;
+ }
+
+ public void setLastStoredFileName(String lastStoredFileName) {
+ this.lastStoredFileName = lastStoredFileName;
+ }
+
+ public void setSslConfigFileName(String sslConfigFileName) {
+ this.sslConfigFileName = sslConfigFileName;
+ }
+
+
+ private synchronized void checkFileWatchDogThread() {
+ if (watcherDaemon == null) {
+ try {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Starting WatchDog for the Path [" + url + "] ....");
+ }
+ watcherDaemon = new Jersey2ConfigWatcher(url, refreshInterval,sslConfigFileName,this.getLastStoredFileName()) {
+ public void doOnChange() {
+ PolicyContainer newPolicyContainer = getPolicyContainer() ;
+ setPolicyContainer(newPolicyContainer) ;
+ savePolicyToFile() ;
+ notifyPolicyChange();
+ };
+ };
+ watcherDaemon.start();
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Completed kick-off of FileWatchDog for the Path [" + url + "] interval in millisecond:" + refreshInterval);
+ }
+ } catch (Throwable t) {
+ LOG.error("Unable to start the FileWatchDog for path [" + url + "]", t);
+ }
+ }
+ }
+
+ private void notifyPolicyChange() {
+ if (policyChangeListener != null) {
+ try {
+ policyChangeListener.OnPolicyChange(policyContainer);
+ }
+ catch(Throwable t) {
+ LOG.error("Error during notification of policy changes to listener [" + policyChangeListener + "]", t) ;
+ }
+ finally {
+ LOG.debug("Completed notification of policy changes to listener [" + policyChangeListener + "]") ;
+ }
+ }
+ }
+
+
+ private void savePolicyToFile() {
+
+ LOG.debug("savePolicyToFile() is called with [" + saveAsFileName + "] - START") ;
+ String fileName = null;
+ if (saveAsFileName != null) {
+ String currentDateTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) ;
+ fileName = saveAsFileName + "." + currentDateTime ;
+ File saveFile = new File(fileName) ;
+ Gson gson = new GsonBuilder().setPrettyPrinting().setExclusionStrategies(policyExclusionStrategy).create() ;
+ String policyAsJson = gson.toJson(policyContainer) ;
+ PrintWriter writer = null ;
+ try {
+ writer = new PrintWriter(new FileWriter(saveFile)) ;
+ writer.println(policyAsJson) ;
+ }
+ catch(IOException ioe) {
+ LOG.error("Unable to save policy into file: [" + saveFile.getAbsolutePath() + "]", ioe);
+ }
+ finally {
+ if (writer != null) {
+ writer.close();
+ }
+ }
+
+ if (lastStoredFileName != null) {
+ File lastSaveFileName = new File(lastStoredFileName);
+
+ try {
+ writer = new PrintWriter(new FileWriter(lastSaveFileName));
+ writer.println(policyAsJson);
+
+ }
+ catch(IOException ioe){
+ LOG.error("Unable to save the policy into Last Stored Policy File [" + lastSaveFileName.getAbsolutePath() + "]", ioe );
+ }
+ finally {
+ //make the policy file cache to be 600 permission when it gets created and updated
+ lastSaveFileName.setReadable(false,false);
+ lastSaveFileName.setReadable(true,true);
+ if (writer != null) {
+ writer.close();
+ }
+ }
+
+ }
+ }
+
+ LOG.debug("savePolicyToFile() is called with [" + fileName + "] - END") ;
+
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/config/PolicyChangeListener.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/config/PolicyChangeListener.java b/agents-impl/src/main/java/org/apache/ranger/pdp/config/PolicyChangeListener.java
new file mode 100644
index 0000000..a403e54
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/config/PolicyChangeListener.java
@@ -0,0 +1,26 @@
+/*
+ * 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.pdp.config;
+
+import org.apache.ranger.pdp.model.PolicyContainer;
+
+public interface PolicyChangeListener {
+ public void OnPolicyChange(PolicyContainer aPolicyContainer) ;
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/config/PolicyRefresher.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/config/PolicyRefresher.java b/agents-impl/src/main/java/org/apache/ranger/pdp/config/PolicyRefresher.java
new file mode 100644
index 0000000..eed7c8d
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/config/PolicyRefresher.java
@@ -0,0 +1,229 @@
+/*
+ * 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.pdp.config;
+
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.pdp.config.gson.PolicyExclusionStrategy;
+import org.apache.ranger.pdp.model.PolicyContainer;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+public class PolicyRefresher {
+
+ private static final Log LOG = LogFactory.getLog(PolicyRefresher.class);
+
+ private String url ;
+ private long refreshInterval ;
+
+ private ConfigWatcher watcherDaemon = null;
+
+ protected PolicyContainer policyContainer = null ;
+
+ private PolicyChangeListener policyChangeListener = null ;
+
+ private String saveAsFileName = null ;
+
+ private String sslConfigFileName = null ;
+
+ private String lastStoredFileName = null;
+
+ private PolicyExclusionStrategy policyExclusionStrategy = new PolicyExclusionStrategy() ;
+
+ public PolicyRefresher(String url, long refreshInterval, String sslConfigFileName, String lastStoredFileName) {
+ if (LOG.isInfoEnabled()) {
+ LOG.info("Creating PolicyRefreshser with url: " + url +
+ ", refreshInterval: " + refreshInterval +
+ ", sslConfigFileName: " + sslConfigFileName +
+ ", lastStoredFileName: " + lastStoredFileName);
+ }
+ this.url = url ;
+ this.refreshInterval = refreshInterval ;
+ this.sslConfigFileName = sslConfigFileName ;
+ this.lastStoredFileName = lastStoredFileName;
+ checkFileWatchDogThread();
+ }
+
+ public PolicyChangeListener getPolicyChangeListener() {
+ return policyChangeListener;
+ }
+
+ public synchronized void setPolicyChangeListener(PolicyChangeListener policyChangeListener) {
+ this.policyChangeListener = policyChangeListener;
+ if (this.policyContainer != null) {
+ savePolicyToFile() ;
+ savePolicyToCacheFile();
+ notifyPolicyChange() ;
+ }
+ }
+
+ public void setPolicyContainer(PolicyContainer aPolicyContainer) {
+ this.policyContainer = aPolicyContainer ;
+ }
+
+ public PolicyContainer getPolicyContainer() {
+ return policyContainer ;
+ }
+
+ public String getSaveAsFileName() {
+ return saveAsFileName;
+ }
+
+ public void setSaveAsFileName(String saveAsFileName) {
+ this.saveAsFileName = saveAsFileName;
+ }
+
+ public String getSslConfigFileName() {
+ return sslConfigFileName;
+ }
+
+ public String getLastStoredFileName() {
+ return lastStoredFileName;
+ }
+
+ public void setLastStoredFileName(String lastStoredFileName) {
+ this.lastStoredFileName = lastStoredFileName;
+ }
+
+ public void setSslConfigFileName(String sslConfigFileName) {
+ this.sslConfigFileName = sslConfigFileName;
+ }
+
+
+ private synchronized void checkFileWatchDogThread() {
+ if (watcherDaemon == null) {
+ try {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Starting WatchDog for the Path [" + url + "] ....");
+ }
+ watcherDaemon = new ConfigWatcher(url, refreshInterval,sslConfigFileName,this.getLastStoredFileName()) {
+ public void doOnChange() {
+ PolicyContainer newPolicyContainer = getPolicyContainer() ;
+ setPolicyContainer(newPolicyContainer) ;
+ savePolicyToFile() ;
+ savePolicyToCacheFile();
+ notifyPolicyChange();
+ };
+ };
+ watcherDaemon.start();
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Completed kick-off of FileWatchDog for the Path [" + url + "] interval in millisecond:" + refreshInterval);
+ }
+ } catch (Throwable t) {
+ LOG.error("Unable to start the FileWatchDog for path [" + url + "]", t);
+ }
+ }
+ }
+
+ private void notifyPolicyChange() {
+ if (policyChangeListener != null) {
+ try {
+ policyChangeListener.OnPolicyChange(policyContainer);
+ }
+ catch(Throwable t) {
+ LOG.error("Error during notification of policy changes to listener [" + policyChangeListener + "]", t) ;
+ }
+ finally {
+ LOG.debug("Completed notification of policy changes to listener [" + policyChangeListener + "]") ;
+ }
+ }
+ }
+
+
+ private void savePolicyToFile() {
+ if (watcherDaemon != null && !watcherDaemon.iscacheModfied()) {
+ // Do not Save the file if the policy is not modified.
+ return;
+ }
+ LOG.debug("savePolicyToFile() is called with [" + saveAsFileName + "] - START") ;
+ String fileName = null;
+ if (saveAsFileName != null) {
+ String currentDateTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) ;
+ fileName = saveAsFileName + "." + currentDateTime ;
+ File saveFile = new File(fileName) ;
+ Gson gson = new GsonBuilder().setPrettyPrinting().setExclusionStrategies(policyExclusionStrategy).create() ;
+ String policyAsJson = gson.toJson(policyContainer) ;
+ PrintWriter writer = null ;
+ try {
+ writer = new PrintWriter(new FileWriter(saveFile)) ;
+ writer.println(policyAsJson) ;
+ }
+ catch(IOException ioe) {
+ LOG.warn("Unable to save policy into file: [" + saveFile.getAbsolutePath() + "]");
+ }
+ finally {
+ if (writer != null) {
+ writer.close();
+ }
+ }
+ LOG.debug("savePolicyToFile() is called with [" + fileName + "] - END") ;
+ }
+ }
+
+ private void savePolicyToCacheFile() {
+
+ if (watcherDaemon != null && !watcherDaemon.iscacheModfied()) {
+ // Don't Save the file if the policy is not modified.
+ return;
+ }
+
+ LOG.debug("savePolicyToCacheFile() is called with [" + lastStoredFileName + "] - START") ;
+
+ if (lastStoredFileName != null) {
+
+ File lastSaveFile = new File(lastStoredFileName) ;
+ Gson gson = new GsonBuilder().setPrettyPrinting().setExclusionStrategies(policyExclusionStrategy).create() ;
+ String policyAsJson = gson.toJson(policyContainer) ;
+ PrintWriter writer = null ;
+
+ try {
+ writer = new PrintWriter(new FileWriter(lastSaveFile));
+ writer.println(policyAsJson);
+
+ }
+ catch(IOException ioe){
+ LOG.warn("Unable to save the policy into Last Stored Policy File [" + lastSaveFile.getAbsolutePath() + "]");
+ }
+ finally {
+ //make the policy file cache to be 600 permission when it gets created and updated
+ lastSaveFile.setReadable(false,false);
+ lastSaveFile.setWritable(false,false);
+ lastSaveFile.setReadable(true,true);
+ lastSaveFile.setWritable(true,true);
+ if (writer != null) {
+ writer.close();
+ }
+ }
+
+ }
+
+ LOG.debug("savePolicyToCacheFile() is called with [" + lastStoredFileName + "] - END") ;
+
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/config/gson/ExcludeSerialization.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/config/gson/ExcludeSerialization.java b/agents-impl/src/main/java/org/apache/ranger/pdp/config/gson/ExcludeSerialization.java
new file mode 100644
index 0000000..cbb460e
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/config/gson/ExcludeSerialization.java
@@ -0,0 +1,32 @@
+/*
+ * 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.pdp.config.gson;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.FIELD})
+
+public @interface ExcludeSerialization {
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/config/gson/PolicyExclusionStrategy.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/config/gson/PolicyExclusionStrategy.java b/agents-impl/src/main/java/org/apache/ranger/pdp/config/gson/PolicyExclusionStrategy.java
new file mode 100644
index 0000000..ad3a354
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/config/gson/PolicyExclusionStrategy.java
@@ -0,0 +1,37 @@
+/*
+ * 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.pdp.config.gson;
+
+import com.google.gson.ExclusionStrategy;
+import com.google.gson.FieldAttributes;
+
+public class PolicyExclusionStrategy implements ExclusionStrategy {
+
+ @Override
+ public boolean shouldSkipClass(Class<?> objectClass) {
+ return (objectClass.getAnnotation(ExcludeSerialization.class) != null) ;
+ }
+
+ @Override
+ public boolean shouldSkipField(FieldAttributes aFieldAttributes) {
+ return (aFieldAttributes.getAnnotation(ExcludeSerialization.class) != null) ;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/constants/RangerConstants.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/constants/RangerConstants.java b/agents-impl/src/main/java/org/apache/ranger/pdp/constants/RangerConstants.java
new file mode 100644
index 0000000..466e00f
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/constants/RangerConstants.java
@@ -0,0 +1,89 @@
+/*
+ * 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.pdp.constants;
+
+public class RangerConstants {
+ public static final String PUBLIC_ACCESS_ROLE = "public" ;
+
+ public static final String RANGER_HBASE_POLICYMGR_URL_PROP = "xasecure.hbase.policymgr.url";
+ public static final String RANGER_HBASE_POLICYMGR_URL_SAVE_FILE_PROP = "xasecure.hbase.policymgr.url.saveAsFile";
+ public static final String RANGER_HBASE_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_PROP = "xasecure.hbase.policymgr.url.reloadIntervalInMillis";
+ public static final String RANGER_HBASE_POLICYMGR_SSL_CONFIG_FILE_PROP = "xasecure.hbase.policymgr.ssl.config";
+ public static final long RANGER_HBASE_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_DEFAULT = 60000L ;
+ public static final String RANGER_HBASE_LAST_SAVED_POLICY_FILE_PROP = "xasecure.hbase.policymgr.url.laststoredfile";
+
+ public static final String RANGER_HDFS_POLICYMGR_URL_PROP = "xasecure.hdfs.policymgr.url";
+ public static final String RANGER_HDFS_POLICYMGR_URL_SAVE_FILE_PROP = "xasecure.hdfs.policymgr.url.saveAsFile";
+ public static final String RANGER_HDFS_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_PROP = "xasecure.hdfs.policymgr.url.reloadIntervalInMillis";
+ public static final String RANGER_HDFS_POLICYMGR_SSL_CONFIG_FILE_PROP = "xasecure.hdfs.policymgr.ssl.config";
+ public static final long RANGER_HDFS_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_DEFAULT = 60000L ;
+ public static final String RANGER_HDFS_LAST_SAVED_POLICY_FILE_PROP = "xasecure.hdfs.policymgr.url.laststoredfile";
+
+
+ public static final String RANGER_KNOX_POLICYMGR_URL_PROP = "xasecure.knox.policymgr.url";
+ public static final String RANGER_KNOX_POLICYMGR_URL_SAVE_FILE_PROP = "xasecure.knox.policymgr.url.saveAsFile";
+ public static final String RANGER_KNOX_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_PROP = "xasecure.knox.policymgr.url.reloadIntervalInMillis";
+ public static final String RANGER_KNOX_POLICYMGR_SSL_CONFIG_FILE_PROP = "xasecure.knox.policymgr.ssl.config";
+ public static final long RANGER_KNOX_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_DEFAULT = 60000L ;
+ public static final String RANGER_KNOX_LAST_SAVED_POLICY_FILE_PROP = "xasecure.knox.policymgr.url.laststoredfile";
+
+
+ public static final String RANGER_HIVE_POLICYMGR_URL_PROP = "xasecure.hive.policymgr.url";
+ public static final String RANGER_HIVE_POLICYMGR_URL_SAVE_FILE_PROP = "xasecure.hive.policymgr.url.saveAsFile";
+ public static final String RANGER_HIVE_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_PROP = "xasecure.hive.policymgr.url.reloadIntervalInMillis";
+ public static final String RANGER_HIVE_POLICYMGR_SSL_CONFIG_FILE_PROP = "xasecure.hive.policymgr.ssl.config";
+ public static final long RANGER_HIVE_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_DEFAULT = 60000L ;
+ public static final String RANGER_HIVE_LAST_SAVED_POLICY_FILE_PROP = "xasecure.hive.policymgr.url.laststoredfile";
+
+
+ // xasecure 2-way ssl configuration
+
+ public static final String RANGER_POLICYMGR_CLIENT_KEY_FILE = "xasecure.policymgr.clientssl.keystore";
+ public static final String RANGER_POLICYMGR_CLIENT_KEY_FILE_PASSWORD = "xasecure.policymgr.clientssl.keystore.password";
+ public static final String RANGER_POLICYMGR_CLIENT_KEY_FILE_TYPE = "xasecure.policymgr.clientssl.keystore.type";
+ public static final String RANGER_POLICYMGR_CLIENT_KEY_FILE_CREDENTIAL = "xasecure.policymgr.clientssl.keystore.credential.file";
+ public static final String RANGER_POLICYMGR_CLIENT_KEY_FILE_CREDENTIAL_ALIAS = "sslKeyStore";
+
+ public static final String RANGER_POLICYMGR_CLIENT_KEY_FILE_TYPE_DEFAULT = "jks";
+
+ public static final String RANGER_POLICYMGR_TRUSTSTORE_FILE = "xasecure.policymgr.clientssl.truststore";
+ public static final String RANGER_POLICYMGR_TRUSTSTORE_FILE_PASSWORD = "xasecure.policymgr.clientssl.truststore.password";
+ public static final String RANGER_POLICYMGR_TRUSTSTORE_FILE_TYPE = "xasecure.policymgr.clientssl.truststore.type";
+ public static final String RANGER_POLICYMGR_TRUSTSTORE_FILE_CREDENTIAL = "xasecure.policymgr.clientssl.truststore.credential.file";
+ public static final String RANGER_POLICYMGR_TRUSTSTORE_FILE_CREDENTIAL_ALIAS = "sslTrustStore";
+
+ public static final String RANGER_POLICYMGR_TRUSTSTORE_FILE_TYPE_DEFAULT = "jks";
+
+
+ public static final String RANGER_SSL_KEYMANAGER_ALGO_TYPE = "SunX509" ;
+ public static final String RANGER_SSL_TRUSTMANAGER_ALGO_TYPE = "SunX509" ;
+ public static final String RANGER_SSL_CONTEXT_ALGO_TYPE = "SSL" ;
+
+
+
+ public static final String RANGER_STORM_POLICYMGR_URL_PROP = "xasecure.storm.policymgr.url";
+ public static final String RANGER_STORM_POLICYMGR_URL_SAVE_FILE_PROP = "xasecure.storm.policymgr.url.saveAsFile";
+ public static final String RANGER_STORM_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_PROP = "xasecure.storm.policymgr.url.reloadIntervalInMillis";
+ public static final String RANGER_STORM_POLICYMGR_SSL_CONFIG_FILE_PROP = "xasecure.storm.policymgr.ssl.config";
+ public static final long RANGER_STORM_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_DEFAULT = 60000L ;
+ public static final String RANGER_STORM_LAST_SAVED_POLICY_FILE_PROP = "xasecure.storm.policymgr.url.laststoredfile";
+
+
+}
[12/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXAccessAudit.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXAccessAudit.java b/security-admin/src/main/java/com/xasecure/view/VXAccessAudit.java
deleted file mode 100644
index 688534c..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXAccessAudit.java
+++ /dev/null
@@ -1,473 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * Access Audit
- *
- */
-
-import java.util.*;
-
-import com.xasecure.common.*;
-import com.xasecure.common.view.*;
-
-import com.xasecure.common.*;
-import com.xasecure.json.JsonDateSerializer;
-
-import com.xasecure.view.*;
-
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@JsonIgnoreProperties(ignoreUnknown=true)
-@XmlRootElement
-public class VXAccessAudit extends VXDataObject implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- /**
- * Repository Type
- */
- protected int auditType;
- /**
- * Access Result
- * This attribute is of type enum CommonEnums::AccessResult
- */
- protected int accessResult = XAConstants.ACCESS_RESULT_DENIED;
- /**
- * Access Type
- */
- protected String accessType;
- /**
- * Acl Enforcer
- */
- protected String aclEnforcer;
- /**
- * Agent Id
- */
- protected String agentId;
- /**
- * Client Ip
- */
- protected String clientIP;
- /**
- * Client Type
- */
- protected String clientType;
- /**
- * Policy Id
- */
- protected long policyId;
- /**
- * Repository Name
- */
- protected String repoName;
- /**
- * Repository Type
- */
- protected int repoType;
- /**
- * Reason of result
- */
- protected String resultReason;
- /**
- * Session Id
- */
- protected String sessionId;
- /**
- * Event Time
- */
- @JsonSerialize(using=JsonDateSerializer.class)
- protected Date eventTime = DateUtil.getUTCDate();
- /**
- * Requesting User
- */
- protected String requestUser;
- /**
- * Action
- */
- protected String action;
- /**
- * Requesting Data
- */
- protected String requestData;
- /**
- * Resource Path
- */
- protected String resourcePath;
- /**
- * Resource Type
- */
- protected String resourceType;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VXAccessAudit ( ) {
- accessResult = XAConstants.ACCESS_RESULT_DENIED;
- }
-
- /**
- * This method sets the value to the member attribute <b>auditType</b>.
- * You cannot set null to the attribute.
- * @param auditType Value to set member attribute <b>auditType</b>
- */
- public void setAuditType( int auditType ) {
- this.auditType = auditType;
- }
-
- /**
- * Returns the value for the member attribute <b>auditType</b>
- * @return int - value of member attribute <b>auditType</b>.
- */
- public int getAuditType( ) {
- return this.auditType;
- }
-
- /**
- * This method sets the value to the member attribute <b>accessResult</b>.
- * You cannot set null to the attribute.
- * @param accessResult Value to set member attribute <b>accessResult</b>
- */
- public void setAccessResult( int accessResult ) {
- this.accessResult = accessResult;
- }
-
- /**
- * Returns the value for the member attribute <b>accessResult</b>
- * @return int - value of member attribute <b>accessResult</b>.
- */
- public int getAccessResult( ) {
- return this.accessResult;
- }
-
- /**
- * This method sets the value to the member attribute <b>accessType</b>.
- * You cannot set null to the attribute.
- * @param accessType Value to set member attribute <b>accessType</b>
- */
- public void setAccessType( String accessType ) {
- this.accessType = accessType;
- }
-
- /**
- * Returns the value for the member attribute <b>accessType</b>
- * @return String - value of member attribute <b>accessType</b>.
- */
- public String getAccessType( ) {
- return this.accessType;
- }
-
- /**
- * This method sets the value to the member attribute <b>aclEnforcer</b>.
- * You cannot set null to the attribute.
- * @param aclEnforcer Value to set member attribute <b>aclEnforcer</b>
- */
- public void setAclEnforcer( String aclEnforcer ) {
- this.aclEnforcer = aclEnforcer;
- }
-
- /**
- * Returns the value for the member attribute <b>aclEnforcer</b>
- * @return String - value of member attribute <b>aclEnforcer</b>.
- */
- public String getAclEnforcer( ) {
- return this.aclEnforcer;
- }
-
- /**
- * This method sets the value to the member attribute <b>agentId</b>.
- * You cannot set null to the attribute.
- * @param agentId Value to set member attribute <b>agentId</b>
- */
- public void setAgentId( String agentId ) {
- this.agentId = agentId;
- }
-
- /**
- * Returns the value for the member attribute <b>agentId</b>
- * @return String - value of member attribute <b>agentId</b>.
- */
- public String getAgentId( ) {
- return this.agentId;
- }
-
- /**
- * This method sets the value to the member attribute <b>clientIP</b>.
- * You cannot set null to the attribute.
- * @param clientIP Value to set member attribute <b>clientIP</b>
- */
- public void setClientIP( String clientIP ) {
- this.clientIP = clientIP;
- }
-
- /**
- * Returns the value for the member attribute <b>clientIP</b>
- * @return String - value of member attribute <b>clientIP</b>.
- */
- public String getClientIP( ) {
- return this.clientIP;
- }
-
- /**
- * This method sets the value to the member attribute <b>clientType</b>.
- * You cannot set null to the attribute.
- * @param clientType Value to set member attribute <b>clientType</b>
- */
- public void setClientType( String clientType ) {
- this.clientType = clientType;
- }
-
- /**
- * Returns the value for the member attribute <b>clientType</b>
- * @return String - value of member attribute <b>clientType</b>.
- */
- public String getClientType( ) {
- return this.clientType;
- }
-
- /**
- * This method sets the value to the member attribute <b>policyId</b>.
- * You cannot set null to the attribute.
- * @param policyId Value to set member attribute <b>policyId</b>
- */
- public void setPolicyId( long policyId ) {
- this.policyId = policyId;
- }
-
- /**
- * Returns the value for the member attribute <b>policyId</b>
- * @return long - value of member attribute <b>policyId</b>.
- */
- public long getPolicyId( ) {
- return this.policyId;
- }
-
- /**
- * This method sets the value to the member attribute <b>repoName</b>.
- * You cannot set null to the attribute.
- * @param repoName Value to set member attribute <b>repoName</b>
- */
- public void setRepoName( String repoName ) {
- this.repoName = repoName;
- }
-
- /**
- * Returns the value for the member attribute <b>repoName</b>
- * @return String - value of member attribute <b>repoName</b>.
- */
- public String getRepoName( ) {
- return this.repoName;
- }
-
- /**
- * This method sets the value to the member attribute <b>repoType</b>.
- * You cannot set null to the attribute.
- * @param repoType Value to set member attribute <b>repoType</b>
- */
- public void setRepoType( int repoType ) {
- this.repoType = repoType;
- }
-
- /**
- * Returns the value for the member attribute <b>repoType</b>
- * @return int - value of member attribute <b>repoType</b>.
- */
- public int getRepoType( ) {
- return this.repoType;
- }
-
- /**
- * This method sets the value to the member attribute <b>resultReason</b>.
- * You cannot set null to the attribute.
- * @param resultReason Value to set member attribute <b>resultReason</b>
- */
- public void setResultReason( String resultReason ) {
- this.resultReason = resultReason;
- }
-
- /**
- * Returns the value for the member attribute <b>resultReason</b>
- * @return String - value of member attribute <b>resultReason</b>.
- */
- public String getResultReason( ) {
- return this.resultReason;
- }
-
- /**
- * This method sets the value to the member attribute <b>sessionId</b>.
- * You cannot set null to the attribute.
- * @param sessionId Value to set member attribute <b>sessionId</b>
- */
- public void setSessionId( String sessionId ) {
- this.sessionId = sessionId;
- }
-
- /**
- * Returns the value for the member attribute <b>sessionId</b>
- * @return String - value of member attribute <b>sessionId</b>.
- */
- public String getSessionId( ) {
- return this.sessionId;
- }
-
- /**
- * This method sets the value to the member attribute <b>eventTime</b>.
- * You cannot set null to the attribute.
- * @param eventTime Value to set member attribute <b>eventTime</b>
- */
- public void setEventTime( Date eventTime ) {
- this.eventTime = eventTime;
- }
-
- /**
- * Returns the value for the member attribute <b>eventTime</b>
- * @return Date - value of member attribute <b>eventTime</b>.
- */
- public Date getEventTime( ) {
- return this.eventTime;
- }
-
- /**
- * This method sets the value to the member attribute <b>requestUser</b>.
- * You cannot set null to the attribute.
- * @param requestUser Value to set member attribute <b>requestUser</b>
- */
- public void setRequestUser( String requestUser ) {
- this.requestUser = requestUser;
- }
-
- /**
- * Returns the value for the member attribute <b>requestUser</b>
- * @return String - value of member attribute <b>requestUser</b>.
- */
- public String getRequestUser( ) {
- return this.requestUser;
- }
-
- /**
- * This method sets the value to the member attribute <b>action</b>.
- * You cannot set null to the attribute.
- * @param action Value to set member attribute <b>action</b>
- */
- public void setAction( String action ) {
- this.action = action;
- }
-
- /**
- * Returns the value for the member attribute <b>action</b>
- * @return String - value of member attribute <b>action</b>.
- */
- public String getAction( ) {
- return this.action;
- }
-
- /**
- * This method sets the value to the member attribute <b>requestData</b>.
- * You cannot set null to the attribute.
- * @param requestData Value to set member attribute <b>requestData</b>
- */
- public void setRequestData( String requestData ) {
- this.requestData = requestData;
- }
-
- /**
- * Returns the value for the member attribute <b>requestData</b>
- * @return String - value of member attribute <b>requestData</b>.
- */
- public String getRequestData( ) {
- return this.requestData;
- }
-
- /**
- * This method sets the value to the member attribute <b>resourcePath</b>.
- * You cannot set null to the attribute.
- * @param resourcePath Value to set member attribute <b>resourcePath</b>
- */
- public void setResourcePath( String resourcePath ) {
- this.resourcePath = resourcePath;
- }
-
- /**
- * Returns the value for the member attribute <b>resourcePath</b>
- * @return String - value of member attribute <b>resourcePath</b>.
- */
- public String getResourcePath( ) {
- return this.resourcePath;
- }
-
- /**
- * This method sets the value to the member attribute <b>resourceType</b>.
- * You cannot set null to the attribute.
- * @param resourceType Value to set member attribute <b>resourceType</b>
- */
- public void setResourceType( String resourceType ) {
- this.resourceType = resourceType;
- }
-
- /**
- * Returns the value for the member attribute <b>resourceType</b>
- * @return String - value of member attribute <b>resourceType</b>.
- */
- public String getResourceType( ) {
- return this.resourceType;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_XA_ACCESS_AUDIT;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- public String toString( ) {
- String str = "VXAccessAudit={";
- str += super.toString();
- str += "auditType={" + auditType + "} ";
- str += "accessResult={" + accessResult + "} ";
- str += "accessType={" + accessType + "} ";
- str += "aclEnforcer={" + aclEnforcer + "} ";
- str += "agentId={" + agentId + "} ";
- str += "clientIP={" + clientIP + "} ";
- str += "clientType={" + clientType + "} ";
- str += "policyId={" + policyId + "} ";
- str += "repoName={" + repoName + "} ";
- str += "repoType={" + repoType + "} ";
- str += "resultReason={" + resultReason + "} ";
- str += "sessionId={" + sessionId + "} ";
- str += "eventTime={" + eventTime + "} ";
- str += "requestUser={" + requestUser + "} ";
- str += "action={" + action + "} ";
- str += "requestData={" + requestData + "} ";
- str += "resourcePath={" + resourcePath + "} ";
- str += "resourceType={" + resourceType + "} ";
- str += "}";
- return str;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXAccessAuditList.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXAccessAuditList.java b/security-admin/src/main/java/com/xasecure/view/VXAccessAuditList.java
deleted file mode 100644
index 1e2a59e..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXAccessAuditList.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * List wrapper class for VXAccessAudit
- *
- */
-
-import java.util.*;
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-import com.xasecure.common.view.*;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.FIELD)
-public class VXAccessAuditList extends VList {
- private static final long serialVersionUID = 1L;
- List<VXAccessAudit> vXAccessAudits = new ArrayList<VXAccessAudit>();
-
- public VXAccessAuditList() {
- super();
- }
-
- public VXAccessAuditList(List<VXAccessAudit> objList) {
- super(objList);
- this.vXAccessAudits = objList;
- }
-
- /**
- * @return the vXAccessAudits
- */
- public List<VXAccessAudit> getVXAccessAudits() {
- return vXAccessAudits;
- }
-
- /**
- * @param vXAccessAudits
- * the vXAccessAudits to set
- */
- public void setVXAccessAudits(List<VXAccessAudit> vXAccessAudits) {
- this.vXAccessAudits = vXAccessAudits;
- }
-
- @Override
- public int getListSize() {
- if (vXAccessAudits != null) {
- return vXAccessAudits.size();
- }
- return 0;
- }
-
- @Override
- public List<VXAccessAudit> getList() {
- return vXAccessAudits;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXAsset.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXAsset.java b/security-admin/src/main/java/com/xasecure/view/VXAsset.java
deleted file mode 100644
index 8875684..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXAsset.java
+++ /dev/null
@@ -1,210 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * Asset
- *
- */
-
-import java.util.*;
-
-import com.xasecure.common.*;
-import com.xasecure.common.view.*;
-
-import com.xasecure.common.*;
-import com.xasecure.json.JsonDateSerializer;
-
-import com.xasecure.view.*;
-
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@JsonIgnoreProperties(ignoreUnknown=true)
-@XmlRootElement
-public class VXAsset extends VXDataObject implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- /**
- * Name
- */
- protected String name;
- /**
- * Description
- */
- protected String description;
- /**
- * Status
- * This attribute is of type enum CommonEnums::ActiveStatus
- */
- protected int activeStatus;
- /**
- * Type of asset
- * This attribute is of type enum CommonEnums::AssetType
- */
- protected int assetType = AppConstants.ASSET_UNKNOWN;
- /**
- * Config in json format
- */
- protected String config;
- /**
- * Support native authorization
- */
- protected boolean supportNative = false;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VXAsset ( ) {
- activeStatus = 0;
- assetType = AppConstants.ASSET_UNKNOWN;
- }
-
- /**
- * This method sets the value to the member attribute <b>name</b>.
- * You cannot set null to the attribute.
- * @param name Value to set member attribute <b>name</b>
- */
- public void setName( String name ) {
- this.name = name;
- }
-
- /**
- * Returns the value for the member attribute <b>name</b>
- * @return String - value of member attribute <b>name</b>.
- */
- public String getName( ) {
- return this.name;
- }
-
- /**
- * This method sets the value to the member attribute <b>description</b>.
- * You cannot set null to the attribute.
- * @param description Value to set member attribute <b>description</b>
- */
- public void setDescription( String description ) {
- this.description = description;
- }
-
- /**
- * Returns the value for the member attribute <b>description</b>
- * @return String - value of member attribute <b>description</b>.
- */
- public String getDescription( ) {
- return this.description;
- }
-
- /**
- * This method sets the value to the member attribute <b>activeStatus</b>.
- * You cannot set null to the attribute.
- * @param activeStatus Value to set member attribute <b>activeStatus</b>
- */
- public void setActiveStatus( int activeStatus ) {
- this.activeStatus = activeStatus;
- }
-
- /**
- * Returns the value for the member attribute <b>activeStatus</b>
- * @return int - value of member attribute <b>activeStatus</b>.
- */
- public int getActiveStatus( ) {
- return this.activeStatus;
- }
-
- /**
- * This method sets the value to the member attribute <b>assetType</b>.
- * You cannot set null to the attribute.
- * @param assetType Value to set member attribute <b>assetType</b>
- */
- public void setAssetType( int assetType ) {
- this.assetType = assetType;
- }
-
- /**
- * Returns the value for the member attribute <b>assetType</b>
- * @return int - value of member attribute <b>assetType</b>.
- */
- public int getAssetType( ) {
- return this.assetType;
- }
-
- /**
- * This method sets the value to the member attribute <b>config</b>.
- * You cannot set null to the attribute.
- * @param config Value to set member attribute <b>config</b>
- */
- public void setConfig( String config ) {
- this.config = config;
- }
-
- /**
- * Returns the value for the member attribute <b>config</b>
- * @return String - value of member attribute <b>config</b>.
- */
- public String getConfig( ) {
- return this.config;
- }
-
- /**
- * This method sets the value to the member attribute <b>supportNative</b>.
- * You cannot set null to the attribute.
- * @param supportNative Value to set member attribute <b>supportNative</b>
- */
- public void setSupportNative( boolean supportNative ) {
- this.supportNative = supportNative;
- }
-
- /**
- * Returns the value for the member attribute <b>supportNative</b>
- * @return boolean - value of member attribute <b>supportNative</b>.
- */
- public boolean isSupportNative( ) {
- return this.supportNative;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_XA_ASSET;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- public String toString( ) {
- String str = "VXAsset={";
- str += super.toString();
- str += "name={" + name + "} ";
- str += "description={" + description + "} ";
- str += "activeStatus={" + activeStatus + "} ";
- str += "assetType={" + assetType + "} ";
- str += "config={" + config + "} ";
- str += "supportNative={" + supportNative + "} ";
- str += "}";
- return str;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXAssetList.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXAssetList.java b/security-admin/src/main/java/com/xasecure/view/VXAssetList.java
deleted file mode 100644
index 2d954bf..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXAssetList.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * List wrapper class for VXAsset
- *
- */
-
-import java.util.*;
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-import com.xasecure.common.view.*;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.FIELD)
-public class VXAssetList extends VList {
- private static final long serialVersionUID = 1L;
- List<VXAsset> vXAssets = new ArrayList<VXAsset>();
-
- public VXAssetList() {
- super();
- }
-
- public VXAssetList(List<VXAsset> objList) {
- super(objList);
- this.vXAssets = objList;
- }
-
- /**
- * @return the vXAssets
- */
- public List<VXAsset> getVXAssets() {
- return vXAssets;
- }
-
- /**
- * @param vXAssets
- * the vXAssets to set
- */
- public void setVXAssets(List<VXAsset> vXAssets) {
- this.vXAssets = vXAssets;
- }
-
- @Override
- public int getListSize() {
- if (vXAssets != null) {
- return vXAssets.size();
- }
- return 0;
- }
-
- @Override
- public List<VXAsset> getList() {
- return vXAssets;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXAuditMap.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXAuditMap.java b/security-admin/src/main/java/com/xasecure/view/VXAuditMap.java
deleted file mode 100644
index 184cca3..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXAuditMap.java
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * Audi map
- *
- */
-
-import java.util.*;
-
-import com.xasecure.common.*;
-import com.xasecure.common.view.*;
-
-import com.xasecure.common.*;
-import com.xasecure.json.JsonDateSerializer;
-
-import com.xasecure.view.*;
-
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@JsonIgnoreProperties(ignoreUnknown=true)
-@XmlRootElement
-public class VXAuditMap extends VXDataObject implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- /**
- * Id of the resource
- */
- protected Long resourceId;
- /**
- * Id of the group
- */
- protected Long groupId;
- /**
- * Id of the user
- */
- protected Long userId;
- /**
- * Type of audit
- * This attribute is of type enum CommonEnums::XAAuditType
- */
- protected int auditType = AppConstants.XA_AUDIT_TYPE_UNKNOWN;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VXAuditMap ( ) {
- auditType = AppConstants.XA_AUDIT_TYPE_UNKNOWN;
- }
-
- /**
- * This method sets the value to the member attribute <b>resourceId</b>.
- * You cannot set null to the attribute.
- * @param resourceId Value to set member attribute <b>resourceId</b>
- */
- public void setResourceId( Long resourceId ) {
- this.resourceId = resourceId;
- }
-
- /**
- * Returns the value for the member attribute <b>resourceId</b>
- * @return Long - value of member attribute <b>resourceId</b>.
- */
- public Long getResourceId( ) {
- return this.resourceId;
- }
-
- /**
- * This method sets the value to the member attribute <b>groupId</b>.
- * You cannot set null to the attribute.
- * @param groupId Value to set member attribute <b>groupId</b>
- */
- public void setGroupId( Long groupId ) {
- this.groupId = groupId;
- }
-
- /**
- * Returns the value for the member attribute <b>groupId</b>
- * @return Long - value of member attribute <b>groupId</b>.
- */
- public Long getGroupId( ) {
- return this.groupId;
- }
-
- /**
- * This method sets the value to the member attribute <b>userId</b>.
- * You cannot set null to the attribute.
- * @param userId Value to set member attribute <b>userId</b>
- */
- public void setUserId( Long userId ) {
- this.userId = userId;
- }
-
- /**
- * Returns the value for the member attribute <b>userId</b>
- * @return Long - value of member attribute <b>userId</b>.
- */
- public Long getUserId( ) {
- return this.userId;
- }
-
- /**
- * This method sets the value to the member attribute <b>auditType</b>.
- * You cannot set null to the attribute.
- * @param auditType Value to set member attribute <b>auditType</b>
- */
- public void setAuditType( int auditType ) {
- this.auditType = auditType;
- }
-
- /**
- * Returns the value for the member attribute <b>auditType</b>
- * @return int - value of member attribute <b>auditType</b>.
- */
- public int getAuditType( ) {
- return this.auditType;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_XA_AUDIT_MAP;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- public String toString( ) {
- String str = "VXAuditMap={";
- str += super.toString();
- str += "resourceId={" + resourceId + "} ";
- str += "groupId={" + groupId + "} ";
- str += "userId={" + userId + "} ";
- str += "auditType={" + auditType + "} ";
- str += "}";
- return str;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXAuditMapList.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXAuditMapList.java b/security-admin/src/main/java/com/xasecure/view/VXAuditMapList.java
deleted file mode 100644
index faf4500..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXAuditMapList.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * List wrapper class for VXAuditMap
- *
- */
-
-import java.util.*;
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-import com.xasecure.common.view.*;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.FIELD)
-public class VXAuditMapList extends VList {
- private static final long serialVersionUID = 1L;
- List<VXAuditMap> vXAuditMaps = new ArrayList<VXAuditMap>();
-
- public VXAuditMapList() {
- super();
- }
-
- public VXAuditMapList(List<VXAuditMap> objList) {
- super(objList);
- this.vXAuditMaps = objList;
- }
-
- /**
- * @return the vXAuditMaps
- */
- public List<VXAuditMap> getVXAuditMaps() {
- return vXAuditMaps;
- }
-
- /**
- * @param vXAuditMaps
- * the vXAuditMaps to set
- */
- public void setVXAuditMaps(List<VXAuditMap> vXAuditMaps) {
- this.vXAuditMaps = vXAuditMaps;
- }
-
- @Override
- public int getListSize() {
- if (vXAuditMaps != null) {
- return vXAuditMaps.size();
- }
- return 0;
- }
-
- @Override
- public List<VXAuditMap> getList() {
- return vXAuditMaps;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXAuditRecord.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXAuditRecord.java b/security-admin/src/main/java/com/xasecure/view/VXAuditRecord.java
deleted file mode 100644
index cf6c778..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXAuditRecord.java
+++ /dev/null
@@ -1,239 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-import java.util.Date;
-
-import javax.xml.bind.annotation.XmlRootElement;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-import com.xasecure.common.AppConstants;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@XmlRootElement
-public class VXAuditRecord {
-
- /**
- * Date of audit log
- */
- protected Date date;
-
- /**
- * Name of the resource
- */
- protected String resource;
-
- /**
- * Action which was audited
- */
- protected String action;
-
- /**
- * Result of the policy enforced
- */
- protected String result;
-
- /**
- * User name whose action was audited
- */
- protected String user;
-
- /**
- * Name of the policy enforcer
- */
- protected String enforcer;
-
- /**
- * Type of resource for which the audit was done
- */
- protected int resourceType = AppConstants.RESOURCE_UNKNOWN;
-
- /**
- * Type of asset for which the audit was done
- * This attribute is of type enum AppCommonEnums::AssetType
- */
- protected int assetType = AppConstants.ASSET_UNKNOWN;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VXAuditRecord() {
- resourceType = AppConstants.RESOURCE_UNKNOWN;
- assetType = AppConstants.ASSET_UNKNOWN;
- }
-
- /**
- * Returns the value for the member attribute <b>date</b>
- * @return Date - value of member attribute <b>date</b>.
- */
- public Date getDate() {
- return date;
- }
-
- /**
- * This method sets the value to the member attribute <b>date</b>.
- * You cannot set null to the attribute.
- * @param date Value to set member attribute <b>date</b>
- */
- public void setDate(Date date) {
- this.date = date;
- }
-
- /**
- * Returns the value for the member attribute <b>resource</b>
- * @return String - value of member attribute <b>resource</b>.
- */
- public String getResource() {
- return resource;
- }
-
- /**
- * This method sets the value to the member attribute <b>resource</b>.
- * You cannot set null to the attribute.
- * @param resource Value to set member attribute <b>resource</b>
- */
- public void setResource(String resource) {
- this.resource = resource;
- }
-
- /**
- * Returns the value for the member attribute <b>action</b>
- * @return String - value of member attribute <b>action</b>.
- */
- public String getAction() {
- return action;
- }
-
- /**
- * This method sets the value to the member attribute <b>action</b>.
- * You cannot set null to the attribute.
- * @param action Value to set member attribute <b>action</b>
- */
- public void setAction(String action) {
- this.action = action;
- }
-
- /**
- * Returns the value for the member attribute <b>result</b>
- * @return String - value of member attribute <b>result</b>.
- */
- public String getResult() {
- return result;
- }
-
- /**
- * This method sets the value to the member attribute <b>result</b>.
- * You cannot set null to the attribute.
- * @param result Value to set member attribute <b>result</b>
- */
- public void setResult(String result) {
- this.result = result;
- }
-
- /**
- * Returns the value for the member attribute <b>user</b>
- * @return String - value of member attribute <b>user</b>.
- */
- public String getUser() {
- return user;
- }
-
- /**
- * This method sets the value to the member attribute <b>user</b>.
- * You cannot set null to the attribute.
- * @param user Value to set member attribute <b>user</b>
- */
- public void setUser(String user) {
- this.user = user;
- }
-
- public String getEnforcer() {
- return enforcer;
- }
-
- /**
- * This method sets the value to the member attribute <b>enforcer</b>.
- * You cannot set null to the attribute.
- * @param enforcer Value to set member attribute <b>enforcer</b>
- */
- public void setEnforcer(String enforcer) {
- this.enforcer = enforcer;
- }
-
- /**
- * Returns the value for the member attribute <b>resourceType</b>
- * @return int - value of member attribute <b>resourceType</b>.
- */
- public int getResourceType( ) {
- return this.resourceType;
- }
-
- /**
- * This method sets the value to the member attribute <b>resourceType</b>.
- * You cannot set null to the attribute.
- * @param resourceType Value to set member attribute <b>resourceType</b>
- */
- public void setResourceType( int resourceType ) {
- this.resourceType = resourceType;
- }
-
- /**
- * Returns the value for the member attribute <b>assetType</b>
- * @return int - value of member attribute <b>assetType</b>.
- */
- public int getAssetType() {
- return assetType;
- }
-
- /**
- * This method sets the value to the member attribute <b>assetType</b>.
- * You cannot set null to the attribute.
- * @param assetType Value to set member attribute <b>assetType</b>
- */
- public void setAssetType(int assetType) {
- this.assetType = assetType;
- }
-
- /**
- * This return the bean content in string format
- *
- * @return formatedStr
- */
-
- public String toString() {
- String str = "XVAuditRecord={";
- str += super.toString();
- str += "date={" + date + "} ";
- str += "resource={" + resource + "} ";
- str += "action={" + action + "} ";
- str += "result={" + result + "} ";
- str += "user={" + user + "} ";
- str += "enforcer={" + enforcer + "} ";
- str += "resourceType={" + resourceType + "} ";
- str += "assetType={" + assetType + "} ";
- str += "}";
- return str;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXAuditRecordList.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXAuditRecordList.java b/security-admin/src/main/java/com/xasecure/view/VXAuditRecordList.java
deleted file mode 100644
index 5ed75a8..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXAuditRecordList.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-import java.util.*;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlRootElement;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-import com.xasecure.common.view.VList;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.FIELD)
-public class VXAuditRecordList extends VList {
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- List<VXAuditRecord> vXAuditRecords = new ArrayList<VXAuditRecord>();
-
- public List<VXAuditRecord> getvAudits() {
- return vXAuditRecords;
- }
-
- public void setvAudits(List<VXAuditRecord> vXAuditRecords) {
- this.vXAuditRecords = vXAuditRecords;
- }
-
- public VXAuditRecordList() {
- super();
- }
-
- @Override
- public int getListSize() {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @Override
- public List<?> getList() {
- // TODO Auto-generated method stub
- return null;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXAuthSession.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXAuthSession.java b/security-admin/src/main/java/com/xasecure/view/VXAuthSession.java
deleted file mode 100644
index 5239ece..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXAuthSession.java
+++ /dev/null
@@ -1,501 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * Authentication sessions
- *
- */
-
-import java.util.*;
-
-import com.xasecure.common.*;
-import com.xasecure.common.view.*;
-
-import com.xasecure.common.*;
-import com.xasecure.json.JsonDateSerializer;
-
-import com.xasecure.view.*;
-
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@JsonIgnoreProperties(ignoreUnknown=true)
-@XmlRootElement
-public class VXAuthSession extends VXDataObject implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- /**
- * Login ID of the user
- */
- protected String loginId;
- /**
- * Id of the user
- */
- protected Long userId;
- /**
- * Email address of the user
- */
- protected String emailAddress;
- /**
- * Is this user a test user?
- */
- protected boolean isTestUser = false;
- /**
- * First name of the user
- */
- protected String firstName;
- /**
- * Last name of the user
- */
- protected String lastName;
- /**
- * Public name of the user
- */
- protected String publicScreenName;
- /**
- * Family name of the user
- */
- protected String familyScreenName;
- /**
- * External session id. Mostly Spring/HTTP session
- */
- protected String extSessionId;
- /**
- * Date and time of authentication
- */
- @JsonSerialize(using=JsonDateSerializer.class)
- protected Date authTime;
- /**
- * Authentication status
- * This attribute is of type enum XXAuthSession::AuthStatus
- */
- protected int authStatus;
- /**
- * Authentication type
- * This attribute is of type enum XXAuthSession::AuthType
- */
- protected int authType;
- /**
- * Authentication provider
- * This attribute is of type enum XXAuthSession::AuthType
- */
- protected int authProvider;
- /**
- * Type of the device
- * This attribute is of type enum CommonEnums::DeviceType
- */
- protected int deviceType;
- /**
- * IP where the request came from
- */
- protected String requestIP;
- /**
- * City name
- */
- protected String cityName;
- /**
- * State name
- */
- protected String stateName;
- /**
- * Country name
- */
- protected String countryName;
- /**
- * UserAgent of the requesting device
- */
- protected String requestUserAgent;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VXAuthSession ( ) {
- authStatus = 0;
- authType = 0;
- authProvider = 0;
- deviceType = 0;
- }
-
- /**
- * This method sets the value to the member attribute <b>loginId</b>.
- * You cannot set null to the attribute.
- * @param loginId Value to set member attribute <b>loginId</b>
- */
- public void setLoginId( String loginId ) {
- this.loginId = loginId;
- }
-
- /**
- * Returns the value for the member attribute <b>loginId</b>
- * @return String - value of member attribute <b>loginId</b>.
- */
- public String getLoginId( ) {
- return this.loginId;
- }
-
- /**
- * This method sets the value to the member attribute <b>userId</b>.
- * You cannot set null to the attribute.
- * @param userId Value to set member attribute <b>userId</b>
- */
- public void setUserId( Long userId ) {
- this.userId = userId;
- }
-
- /**
- * Returns the value for the member attribute <b>userId</b>
- * @return Long - value of member attribute <b>userId</b>.
- */
- public Long getUserId( ) {
- return this.userId;
- }
-
- /**
- * This method sets the value to the member attribute <b>emailAddress</b>.
- * You cannot set null to the attribute.
- * @param emailAddress Value to set member attribute <b>emailAddress</b>
- */
- public void setEmailAddress( String emailAddress ) {
- this.emailAddress = emailAddress;
- }
-
- /**
- * Returns the value for the member attribute <b>emailAddress</b>
- * @return String - value of member attribute <b>emailAddress</b>.
- */
- public String getEmailAddress( ) {
- return this.emailAddress;
- }
-
- /**
- * This method sets the value to the member attribute <b>isTestUser</b>.
- * You cannot set null to the attribute.
- * @param isTestUser Value to set member attribute <b>isTestUser</b>
- */
- public void setIsTestUser( boolean isTestUser ) {
- this.isTestUser = isTestUser;
- }
-
- /**
- * Returns the value for the member attribute <b>isTestUser</b>
- * @return boolean - value of member attribute <b>isTestUser</b>.
- */
- public boolean isIsTestUser( ) {
- return this.isTestUser;
- }
-
- /**
- * This method sets the value to the member attribute <b>firstName</b>.
- * You cannot set null to the attribute.
- * @param firstName Value to set member attribute <b>firstName</b>
- */
- public void setFirstName( String firstName ) {
- this.firstName = firstName;
- }
-
- /**
- * Returns the value for the member attribute <b>firstName</b>
- * @return String - value of member attribute <b>firstName</b>.
- */
- public String getFirstName( ) {
- return this.firstName;
- }
-
- /**
- * This method sets the value to the member attribute <b>lastName</b>.
- * You cannot set null to the attribute.
- * @param lastName Value to set member attribute <b>lastName</b>
- */
- public void setLastName( String lastName ) {
- this.lastName = lastName;
- }
-
- /**
- * Returns the value for the member attribute <b>lastName</b>
- * @return String - value of member attribute <b>lastName</b>.
- */
- public String getLastName( ) {
- return this.lastName;
- }
-
- /**
- * This method sets the value to the member attribute <b>publicScreenName</b>.
- * You cannot set null to the attribute.
- * @param publicScreenName Value to set member attribute <b>publicScreenName</b>
- */
- public void setPublicScreenName( String publicScreenName ) {
- this.publicScreenName = publicScreenName;
- }
-
- /**
- * Returns the value for the member attribute <b>publicScreenName</b>
- * @return String - value of member attribute <b>publicScreenName</b>.
- */
- public String getPublicScreenName( ) {
- return this.publicScreenName;
- }
-
- /**
- * This method sets the value to the member attribute <b>familyScreenName</b>.
- * You cannot set null to the attribute.
- * @param familyScreenName Value to set member attribute <b>familyScreenName</b>
- */
- public void setFamilyScreenName( String familyScreenName ) {
- this.familyScreenName = familyScreenName;
- }
-
- /**
- * Returns the value for the member attribute <b>familyScreenName</b>
- * @return String - value of member attribute <b>familyScreenName</b>.
- */
- public String getFamilyScreenName( ) {
- return this.familyScreenName;
- }
-
- /**
- * This method sets the value to the member attribute <b>extSessionId</b>.
- * You cannot set null to the attribute.
- * @param extSessionId Value to set member attribute <b>extSessionId</b>
- */
- public void setExtSessionId( String extSessionId ) {
- this.extSessionId = extSessionId;
- }
-
- /**
- * Returns the value for the member attribute <b>extSessionId</b>
- * @return String - value of member attribute <b>extSessionId</b>.
- */
- public String getExtSessionId( ) {
- return this.extSessionId;
- }
-
- /**
- * This method sets the value to the member attribute <b>authTime</b>.
- * You cannot set null to the attribute.
- * @param authTime Value to set member attribute <b>authTime</b>
- */
- public void setAuthTime( Date authTime ) {
- this.authTime = authTime;
- }
-
- /**
- * Returns the value for the member attribute <b>authTime</b>
- * @return Date - value of member attribute <b>authTime</b>.
- */
- public Date getAuthTime( ) {
- return this.authTime;
- }
-
- /**
- * This method sets the value to the member attribute <b>authStatus</b>.
- * You cannot set null to the attribute.
- * @param authStatus Value to set member attribute <b>authStatus</b>
- */
- public void setAuthStatus( int authStatus ) {
- this.authStatus = authStatus;
- }
-
- /**
- * Returns the value for the member attribute <b>authStatus</b>
- * @return int - value of member attribute <b>authStatus</b>.
- */
- public int getAuthStatus( ) {
- return this.authStatus;
- }
-
- /**
- * This method sets the value to the member attribute <b>authType</b>.
- * You cannot set null to the attribute.
- * @param authType Value to set member attribute <b>authType</b>
- */
- public void setAuthType( int authType ) {
- this.authType = authType;
- }
-
- /**
- * Returns the value for the member attribute <b>authType</b>
- * @return int - value of member attribute <b>authType</b>.
- */
- public int getAuthType( ) {
- return this.authType;
- }
-
- /**
- * This method sets the value to the member attribute <b>authProvider</b>.
- * You cannot set null to the attribute.
- * @param authProvider Value to set member attribute <b>authProvider</b>
- */
- public void setAuthProvider( int authProvider ) {
- this.authProvider = authProvider;
- }
-
- /**
- * Returns the value for the member attribute <b>authProvider</b>
- * @return int - value of member attribute <b>authProvider</b>.
- */
- public int getAuthProvider( ) {
- return this.authProvider;
- }
-
- /**
- * This method sets the value to the member attribute <b>deviceType</b>.
- * You cannot set null to the attribute.
- * @param deviceType Value to set member attribute <b>deviceType</b>
- */
- public void setDeviceType( int deviceType ) {
- this.deviceType = deviceType;
- }
-
- /**
- * Returns the value for the member attribute <b>deviceType</b>
- * @return int - value of member attribute <b>deviceType</b>.
- */
- public int getDeviceType( ) {
- return this.deviceType;
- }
-
- /**
- * This method sets the value to the member attribute <b>requestIP</b>.
- * You cannot set null to the attribute.
- * @param requestIP Value to set member attribute <b>requestIP</b>
- */
- public void setRequestIP( String requestIP ) {
- this.requestIP = requestIP;
- }
-
- /**
- * Returns the value for the member attribute <b>requestIP</b>
- * @return String - value of member attribute <b>requestIP</b>.
- */
- public String getRequestIP( ) {
- return this.requestIP;
- }
-
- /**
- * This method sets the value to the member attribute <b>cityName</b>.
- * You cannot set null to the attribute.
- * @param cityName Value to set member attribute <b>cityName</b>
- */
- public void setCityName( String cityName ) {
- this.cityName = cityName;
- }
-
- /**
- * Returns the value for the member attribute <b>cityName</b>
- * @return String - value of member attribute <b>cityName</b>.
- */
- public String getCityName( ) {
- return this.cityName;
- }
-
- /**
- * This method sets the value to the member attribute <b>stateName</b>.
- * You cannot set null to the attribute.
- * @param stateName Value to set member attribute <b>stateName</b>
- */
- public void setStateName( String stateName ) {
- this.stateName = stateName;
- }
-
- /**
- * Returns the value for the member attribute <b>stateName</b>
- * @return String - value of member attribute <b>stateName</b>.
- */
- public String getStateName( ) {
- return this.stateName;
- }
-
- /**
- * This method sets the value to the member attribute <b>countryName</b>.
- * You cannot set null to the attribute.
- * @param countryName Value to set member attribute <b>countryName</b>
- */
- public void setCountryName( String countryName ) {
- this.countryName = countryName;
- }
-
- /**
- * Returns the value for the member attribute <b>countryName</b>
- * @return String - value of member attribute <b>countryName</b>.
- */
- public String getCountryName( ) {
- return this.countryName;
- }
-
- /**
- * This method sets the value to the member attribute <b>requestUserAgent</b>.
- * You cannot set null to the attribute.
- * @param requestUserAgent Value to set member attribute <b>requestUserAgent</b>
- */
- public void setRequestUserAgent( String requestUserAgent ) {
- this.requestUserAgent = requestUserAgent;
- }
-
- /**
- * Returns the value for the member attribute <b>requestUserAgent</b>
- * @return String - value of member attribute <b>requestUserAgent</b>.
- */
- public String getRequestUserAgent( ) {
- return this.requestUserAgent;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_AUTH_SESS;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- public String toString( ) {
- String str = "VXAuthSession={";
- str += super.toString();
- str += "loginId={" + loginId + "} ";
- str += "userId={" + userId + "} ";
- str += "emailAddress={" + emailAddress + "} ";
- str += "isTestUser={" + isTestUser + "} ";
- str += "firstName={" + firstName + "} ";
- str += "lastName={" + lastName + "} ";
- str += "publicScreenName={" + publicScreenName + "} ";
- str += "familyScreenName={" + familyScreenName + "} ";
- str += "extSessionId={" + extSessionId + "} ";
- str += "authTime={" + authTime + "} ";
- str += "authStatus={" + authStatus + "} ";
- str += "authType={" + authType + "} ";
- str += "authProvider={" + authProvider + "} ";
- str += "deviceType={" + deviceType + "} ";
- str += "requestIP={" + requestIP + "} ";
- str += "cityName={" + cityName + "} ";
- str += "stateName={" + stateName + "} ";
- str += "countryName={" + countryName + "} ";
- str += "requestUserAgent={" + requestUserAgent + "} ";
- str += "}";
- return str;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXAuthSessionList.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXAuthSessionList.java b/security-admin/src/main/java/com/xasecure/view/VXAuthSessionList.java
deleted file mode 100644
index b4cb86f..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXAuthSessionList.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * List wrapper class for VXAuthSession
- *
- */
-
-import java.util.*;
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-import com.xasecure.common.view.*;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.FIELD)
-public class VXAuthSessionList extends VList {
- private static final long serialVersionUID = 1L;
- List<VXAuthSession> vXAuthSessions = new ArrayList<VXAuthSession>();
-
- public VXAuthSessionList() {
- super();
- }
-
- public VXAuthSessionList(List<VXAuthSession> objList) {
- super(objList);
- this.vXAuthSessions = objList;
- }
-
- /**
- * @return the vXAuthSessions
- */
- public List<VXAuthSession> getVXAuthSessions() {
- return vXAuthSessions;
- }
-
- /**
- * @param vXAuthSessions
- * the vXAuthSessions to set
- */
- public void setVXAuthSessions(List<VXAuthSession> vXAuthSessions) {
- this.vXAuthSessions = vXAuthSessions;
- }
-
- @Override
- public int getListSize() {
- if (vXAuthSessions != null) {
- return vXAuthSessions.size();
- }
- return 0;
- }
-
- @Override
- public List<VXAuthSession> getList() {
- return vXAuthSessions;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXCredentialStore.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXCredentialStore.java b/security-admin/src/main/java/com/xasecure/view/VXCredentialStore.java
deleted file mode 100644
index 1350da4..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXCredentialStore.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * Credential Store
-
- */
-
-import java.util.*;
-
-import com.xasecure.common.*;
-import com.xasecure.common.view.*;
-
-import com.xasecure.common.*;
-import com.xasecure.json.JsonDateSerializer;
-
-import com.xasecure.view.*;
-
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@JsonIgnoreProperties(ignoreUnknown=true)
-@XmlRootElement
-public class VXCredentialStore extends VXDataObject implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- /**
- * Name
- */
- protected String name;
- /**
- * Description
- */
- protected String description;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VXCredentialStore ( ) {
- }
-
- /**
- * This method sets the value to the member attribute <b>name</b>.
- * You cannot set null to the attribute.
- * @param name Value to set member attribute <b>name</b>
- */
- public void setName( String name ) {
- this.name = name;
- }
-
- /**
- * Returns the value for the member attribute <b>name</b>
- * @return String - value of member attribute <b>name</b>.
- */
- public String getName( ) {
- return this.name;
- }
-
- /**
- * This method sets the value to the member attribute <b>description</b>.
- * You cannot set null to the attribute.
- * @param description Value to set member attribute <b>description</b>
- */
- public void setDescription( String description ) {
- this.description = description;
- }
-
- /**
- * Returns the value for the member attribute <b>description</b>
- * @return String - value of member attribute <b>description</b>.
- */
- public String getDescription( ) {
- return this.description;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_XA_CRED_STORE;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- public String toString( ) {
- String str = "VXCredentialStore={";
- str += super.toString();
- str += "name={" + name + "} ";
- str += "description={" + description + "} ";
- str += "}";
- return str;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXCredentialStoreList.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXCredentialStoreList.java b/security-admin/src/main/java/com/xasecure/view/VXCredentialStoreList.java
deleted file mode 100644
index 290aaf5..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXCredentialStoreList.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * List wrapper class for VXCredentialStore
-
- */
-
-import java.util.*;
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-import com.xasecure.common.view.*;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.FIELD)
-public class VXCredentialStoreList extends VList {
- private static final long serialVersionUID = 1L;
- List<VXCredentialStore> vXCredentialStores = new ArrayList<VXCredentialStore>();
-
- public VXCredentialStoreList() {
- super();
- }
-
- public VXCredentialStoreList(List<VXCredentialStore> objList) {
- super(objList);
- this.vXCredentialStores = objList;
- }
-
- /**
- * @return the vXCredentialStores
- */
- public List<VXCredentialStore> getVXCredentialStores() {
- return vXCredentialStores;
- }
-
- /**
- * @param vXCredentialStores
- * the vXCredentialStores to set
- */
- public void setVXCredentialStores(List<VXCredentialStore> vXCredentialStores) {
- this.vXCredentialStores = vXCredentialStores;
- }
-
- @Override
- public int getListSize() {
- if (vXCredentialStores != null) {
- return vXCredentialStores.size();
- }
- return 0;
- }
-
- @Override
- public List<VXCredentialStore> getList() {
- return vXCredentialStores;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXDataObject.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXDataObject.java b/security-admin/src/main/java/com/xasecure/view/VXDataObject.java
deleted file mode 100644
index 90c287c..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXDataObject.java
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * Base object class
- *
- */
-
-import java.util.*;
-
-import com.xasecure.common.*;
-import com.xasecure.common.view.*;
-
-import com.xasecure.common.*;
-import com.xasecure.json.JsonDateSerializer;
-
-import com.xasecure.view.*;
-
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@JsonIgnoreProperties(ignoreUnknown=true)
-@XmlRootElement
-public class VXDataObject extends ViewBaseBean implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- /**
- * Id of the data
- */
- protected Long id;
- /**
- * Date when this data was created
- */
- @JsonSerialize(using=JsonDateSerializer.class)
- protected Date createDate;
- /**
- * Date when this data was updated
- */
- @JsonSerialize(using=JsonDateSerializer.class)
- protected Date updateDate;
- /**
- * Owner
- */
- protected String owner;
- /**
- * Updated By
- */
- protected String updatedBy;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VXDataObject ( ) {
- }
-
- /**
- * This method sets the value to the member attribute <b>id</b>.
- * You cannot set null to the attribute.
- * @param id Value to set member attribute <b>id</b>
- */
- public void setId( Long id ) {
- this.id = id;
- }
-
- /**
- * Returns the value for the member attribute <b>id</b>
- * @return Long - value of member attribute <b>id</b>.
- */
- public Long getId( ) {
- return this.id;
- }
-
- /**
- * This method sets the value to the member attribute <b>createDate</b>.
- * You cannot set null to the attribute.
- * @param createDate Value to set member attribute <b>createDate</b>
- */
- public void setCreateDate( Date createDate ) {
- this.createDate = createDate;
- }
-
- /**
- * Returns the value for the member attribute <b>createDate</b>
- * @return Date - value of member attribute <b>createDate</b>.
- */
- public Date getCreateDate( ) {
- return this.createDate;
- }
-
- /**
- * This method sets the value to the member attribute <b>updateDate</b>.
- * You cannot set null to the attribute.
- * @param updateDate Value to set member attribute <b>updateDate</b>
- */
- public void setUpdateDate( Date updateDate ) {
- this.updateDate = updateDate;
- }
-
- /**
- * Returns the value for the member attribute <b>updateDate</b>
- * @return Date - value of member attribute <b>updateDate</b>.
- */
- public Date getUpdateDate( ) {
- return this.updateDate;
- }
-
- /**
- * This method sets the value to the member attribute <b>owner</b>.
- * You cannot set null to the attribute.
- * @param owner Value to set member attribute <b>owner</b>
- */
- public void setOwner( String owner ) {
- this.owner = owner;
- }
-
- /**
- * Returns the value for the member attribute <b>owner</b>
- * @return String - value of member attribute <b>owner</b>.
- */
- public String getOwner( ) {
- return this.owner;
- }
-
- /**
- * This method sets the value to the member attribute <b>updatedBy</b>.
- * You cannot set null to the attribute.
- * @param updatedBy Value to set member attribute <b>updatedBy</b>
- */
- public void setUpdatedBy( String updatedBy ) {
- this.updatedBy = updatedBy;
- }
-
- /**
- * Returns the value for the member attribute <b>updatedBy</b>
- * @return String - value of member attribute <b>updatedBy</b>.
- */
- public String getUpdatedBy( ) {
- return this.updatedBy;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_DATA_OBJECT;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- public String toString( ) {
- String str = "VXDataObject={";
- str += super.toString();
- str += "id={" + id + "} ";
- str += "createDate={" + createDate + "} ";
- str += "updateDate={" + updateDate + "} ";
- str += "owner={" + owner + "} ";
- str += "updatedBy={" + updatedBy + "} ";
- str += "}";
- return str;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXGroup.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXGroup.java b/security-admin/src/main/java/com/xasecure/view/VXGroup.java
deleted file mode 100644
index bfd5b8c..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXGroup.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * Group
- *
- */
-
-import java.util.*;
-
-import com.xasecure.common.*;
-import com.xasecure.common.view.*;
-
-import com.xasecure.common.*;
-import com.xasecure.json.JsonDateSerializer;
-
-import com.xasecure.view.*;
-
-import javax.persistence.Column;
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@JsonIgnoreProperties(ignoreUnknown=true)
-@XmlRootElement
-public class VXGroup extends VXDataObject implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- /**
- * Name
- */
- protected String name;
- /**
- * Description
- */
- protected String description;
- /**
- * Type of group
- * This attribute is of type enum CommonEnums::XAGroupType
- */
- protected int groupType = AppConstants.XA_GROUP_UNKNOWN;
-
- protected int groupSource = XACommonEnums.GROUP_INTERNAL;
- /**
- * Id of the credential store
- */
- protected Long credStoreId;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VXGroup ( ) {
- groupType = AppConstants.XA_GROUP_UNKNOWN;
- }
-
- /**
- * This method sets the value to the member attribute <b>name</b>.
- * You cannot set null to the attribute.
- * @param name Value to set member attribute <b>name</b>
- */
- public void setName( String name ) {
- this.name = name;
- }
-
- /**
- * Returns the value for the member attribute <b>name</b>
- * @return String - value of member attribute <b>name</b>.
- */
- public String getName( ) {
- return this.name;
- }
-
- /**
- * This method sets the value to the member attribute <b>description</b>.
- * You cannot set null to the attribute.
- * @param description Value to set member attribute <b>description</b>
- */
- public void setDescription( String description ) {
- this.description = description;
- }
-
- /**
- * Returns the value for the member attribute <b>description</b>
- * @return String - value of member attribute <b>description</b>.
- */
- public String getDescription( ) {
- return this.description;
- }
-
- /**
- * This method sets the value to the member attribute <b>groupType</b>.
- * You cannot set null to the attribute.
- * @param groupType Value to set member attribute <b>groupType</b>
- */
- public void setGroupType( int groupType ) {
- this.groupType = groupType;
- }
-
- /**
- * Returns the value for the member attribute <b>groupType</b>
- * @return int - value of member attribute <b>groupType</b>.
- */
- public int getGroupType( ) {
- return this.groupType;
- }
-
- /**
- * This method sets the value to the member attribute <b>credStoreId</b>.
- * You cannot set null to the attribute.
- * @param credStoreId Value to set member attribute <b>credStoreId</b>
- */
- public void setCredStoreId( Long credStoreId ) {
- this.credStoreId = credStoreId;
- }
-
- /**
- * Returns the value for the member attribute <b>credStoreId</b>
- * @return Long - value of member attribute <b>credStoreId</b>.
- */
- public Long getCredStoreId( ) {
- return this.credStoreId;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_XA_GROUP;
- }
-
-
-
-
- public int getGroupSource() {
- return groupSource;
- }
-
- public void setGroupSource(int groupSource) {
- this.groupSource = groupSource;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- public String toString( ) {
- String str = "VXGroup={";
- str += super.toString();
- str += "name={" + name + "} ";
- str += "description={" + description + "} ";
- str += "groupType={" + groupType + "} ";
- str += "credStoreId={" + credStoreId + "} ";
- str += "groupSrc={" + groupSource + "} ";
- str += "}";
- return str;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXGroupGroup.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXGroupGroup.java b/security-admin/src/main/java/com/xasecure/view/VXGroupGroup.java
deleted file mode 100644
index 6edb8bf..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXGroupGroup.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * Group of groups
- *
- */
-
-import java.util.*;
-
-import com.xasecure.common.*;
-import com.xasecure.common.view.*;
-
-import com.xasecure.common.*;
-import com.xasecure.json.JsonDateSerializer;
-
-import com.xasecure.view.*;
-
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@JsonIgnoreProperties(ignoreUnknown=true)
-@XmlRootElement
-public class VXGroupGroup extends VXDataObject implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- /**
- * Name
- */
- protected String name;
- /**
- * Id of the parent group
- */
- protected Long parentGroupId;
- /**
- * Id of the group
- */
- protected Long groupId;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VXGroupGroup ( ) {
- }
-
- /**
- * This method sets the value to the member attribute <b>name</b>.
- * You cannot set null to the attribute.
- * @param name Value to set member attribute <b>name</b>
- */
- public void setName( String name ) {
- this.name = name;
- }
-
- /**
- * Returns the value for the member attribute <b>name</b>
- * @return String - value of member attribute <b>name</b>.
- */
- public String getName( ) {
- return this.name;
- }
-
- /**
- * This method sets the value to the member attribute <b>parentGroupId</b>.
- * You cannot set null to the attribute.
- * @param parentGroupId Value to set member attribute <b>parentGroupId</b>
- */
- public void setParentGroupId( Long parentGroupId ) {
- this.parentGroupId = parentGroupId;
- }
-
- /**
- * Returns the value for the member attribute <b>parentGroupId</b>
- * @return Long - value of member attribute <b>parentGroupId</b>.
- */
- public Long getParentGroupId( ) {
- return this.parentGroupId;
- }
-
- /**
- * This method sets the value to the member attribute <b>groupId</b>.
- * You cannot set null to the attribute.
- * @param groupId Value to set member attribute <b>groupId</b>
- */
- public void setGroupId( Long groupId ) {
- this.groupId = groupId;
- }
-
- /**
- * Returns the value for the member attribute <b>groupId</b>
- * @return Long - value of member attribute <b>groupId</b>.
- */
- public Long getGroupId( ) {
- return this.groupId;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_XA_GROUP_GROUP;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- public String toString( ) {
- String str = "VXGroupGroup={";
- str += super.toString();
- str += "name={" + name + "} ";
- str += "parentGroupId={" + parentGroupId + "} ";
- str += "groupId={" + groupId + "} ";
- str += "}";
- return str;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXGroupGroupList.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXGroupGroupList.java b/security-admin/src/main/java/com/xasecure/view/VXGroupGroupList.java
deleted file mode 100644
index 72a77ca..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXGroupGroupList.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * List wrapper class for VXGroupGroup
- *
- */
-
-import java.util.*;
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-import com.xasecure.common.view.*;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.FIELD)
-public class VXGroupGroupList extends VList {
- private static final long serialVersionUID = 1L;
- List<VXGroupGroup> vXGroupGroups = new ArrayList<VXGroupGroup>();
-
- public VXGroupGroupList() {
- super();
- }
-
- public VXGroupGroupList(List<VXGroupGroup> objList) {
- super(objList);
- this.vXGroupGroups = objList;
- }
-
- /**
- * @return the vXGroupGroups
- */
- public List<VXGroupGroup> getVXGroupGroups() {
- return vXGroupGroups;
- }
-
- /**
- * @param vXGroupGroups
- * the vXGroupGroups to set
- */
- public void setVXGroupGroups(List<VXGroupGroup> vXGroupGroups) {
- this.vXGroupGroups = vXGroupGroups;
- }
-
- @Override
- public int getListSize() {
- if (vXGroupGroups != null) {
- return vXGroupGroups.size();
- }
- return 0;
- }
-
- @Override
- public List<VXGroupGroup> getList() {
- return vXGroupGroups;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXGroupList.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXGroupList.java b/security-admin/src/main/java/com/xasecure/view/VXGroupList.java
deleted file mode 100644
index 442ad19..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXGroupList.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * List wrapper class for VXGroup
- *
- */
-
-import java.util.*;
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-import com.xasecure.common.view.*;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.FIELD)
-public class VXGroupList extends VList {
- private static final long serialVersionUID = 1L;
- List<VXGroup> vXGroups = new ArrayList<VXGroup>();
-
- public VXGroupList() {
- super();
- }
-
- public VXGroupList(List<VXGroup> objList) {
- super(objList);
- this.vXGroups = objList;
- }
-
- /**
- * @return the vXGroups
- */
- public List<VXGroup> getVXGroups() {
- return vXGroups;
- }
-
- /**
- * @param vXGroups
- * the vXGroups to set
- */
- public void setVXGroups(List<VXGroup> vXGroups) {
- this.vXGroups = vXGroups;
- }
-
- @Override
- public int getListSize() {
- if (vXGroups != null) {
- return vXGroups.size();
- }
- return 0;
- }
-
- @Override
- public List<VXGroup> getList() {
- return vXGroups;
- }
-
-}
[42/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/hdfs/URLBasedAuthDB.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/hdfs/URLBasedAuthDB.java b/agents-impl/src/main/java/com/xasecure/pdp/hdfs/URLBasedAuthDB.java
deleted file mode 100644
index 29f2c22..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/hdfs/URLBasedAuthDB.java
+++ /dev/null
@@ -1,480 +0,0 @@
-/*
- * 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 com.xasecure.pdp.hdfs;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.TreeSet;
-
-import org.apache.commons.io.FilenameUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.security.UserGroupInformation;
-import org.apache.log4j.Level;
-import org.apache.log4j.LogManager;
-
-import com.xasecure.authorization.hadoop.HDFSAccessVerifier;
-import com.xasecure.authorization.hadoop.config.XaSecureConfiguration;
-import com.xasecure.pdp.config.PolicyChangeListener;
-import com.xasecure.pdp.config.PolicyRefresher;
-import com.xasecure.pdp.constants.XaSecureConstants;
-import com.xasecure.pdp.model.Policy;
-import com.xasecure.pdp.model.PolicyContainer;
-import com.xasecure.pdp.model.ResourcePath;
-import com.xasecure.pdp.model.RolePermission;
-
-public class URLBasedAuthDB implements HDFSAccessVerifier, PolicyChangeListener {
-
- private static final Log LOG = LogFactory.getLog(URLBasedAuthDB.class) ;
-
- private static URLBasedAuthDB me = null;
-
- private PolicyRefresher refresher = null ;
-
- private PolicyContainer policyContainer = null;
-
- private HashMap<String,Boolean> cachedAuditFlag = new HashMap<String,Boolean>() ; // needs to be cleaned when ruleList changes
-
- private static final long MAX_NO_OF_AUDIT_CACHE_ENTRIES = 1000L ;
-
-
- public static URLBasedAuthDB getInstance() {
- if (me == null) {
- synchronized (URLBasedAuthDB.class) {
- URLBasedAuthDB temp = me;
- if (temp == null) {
- me = new URLBasedAuthDB();
- me.init() ;
- }
- }
- }
- return me;
- }
-
- private URLBasedAuthDB() {
- String url = XaSecureConfiguration.getInstance().get(XaSecureConstants.XASECURE_HDFS_POLICYMGR_URL_PROP);
- long refreshInMilli = XaSecureConfiguration.getInstance().getLong(
- XaSecureConstants.XASECURE_HDFS_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_PROP ,
- XaSecureConstants.XASECURE_HDFS_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_DEFAULT);
- String sslConfigFileName = XaSecureConfiguration.getInstance().get(XaSecureConstants.XASECURE_HDFS_POLICYMGR_SSL_CONFIG_FILE_PROP) ;
-
- String lastStoredFileName = XaSecureConfiguration.getInstance().get(XaSecureConstants.XASECURE_HDFS_LAST_SAVED_POLICY_FILE_PROP) ;
-
- refresher = new PolicyRefresher(url, refreshInMilli,sslConfigFileName,lastStoredFileName) ;
-
- String saveAsFileName = XaSecureConfiguration.getInstance().get(XaSecureConstants.XASECURE_HDFS_POLICYMGR_URL_SAVE_FILE_PROP) ;
- if (saveAsFileName != null) {
- refresher.setSaveAsFileName(saveAsFileName) ;
- }
-
- if (lastStoredFileName != null) {
- refresher.setLastStoredFileName(lastStoredFileName);
- }
- }
-
- private void init() {
- refresher.setPolicyChangeListener(this);
- }
-
- @Override
- public void OnPolicyChange(PolicyContainer aPolicyContainer) {
- setPolicyContainer(aPolicyContainer);
- }
-
-
- @Override
- public boolean isAccessGranted(String aPathName, String pathOwnerName, String access, String username, Set<String> groups) {
-
- PolicyContainer pc = getPolicyContainer() ;
-
- if (pc == null) {
- return false ;
- }
-
- for(Policy acl : pc.getAcl()) {
-
- if (! acl.isEnabled()) {
- LOG.debug("Diabled acl found [" + acl + "]. Skipping this acl ...") ;
- continue ;
- }
-
- for(ResourcePath resource : acl.getResourceList()) {
-
- String path = resource.getPath() ;
-
- boolean rulePathMatched = false ;
-
- if (acl.getRecursiveInd() == 1) {
- if (resource.isWildcardPath()) {
- rulePathMatched = isRecursiveWildCardMatch(aPathName, path) ;
- }
- else {
- rulePathMatched = aPathName.startsWith(path) ;
- }
- }
- else {
- if (resource.isWildcardPath()) {
- rulePathMatched = FilenameUtils.wildcardMatch(aPathName, path) ;
- }
- else {
- rulePathMatched = aPathName.equals(path) ;
- }
- }
-
-
- if (rulePathMatched) {
- for (RolePermission rp : acl.getPermissions()) {
- if (rp.getAccess().contains(access)) {
- if ( rp.getUsers().contains(username) ) {
- return true ;
- }
- for(String ug : groups) {
- if ( rp.getGroups().contains(ug)) {
- return true ;
- }
- }
- if (rp.getGroups().contains(XaSecureConstants.PUBLIC_ACCESS_ROLE)) {
- return true ;
- }
- }
- }
- }
-
- }
- }
-
- return false ;
-
- }
-
- public static boolean isRecursiveWildCardMatch(String pathToCheck, String wildcardPath) {
- if (pathToCheck != null) {
- StringBuilder sb = new StringBuilder() ;
- for(String p : pathToCheck.split(File.separator) ) {
- sb.append(p) ;
- boolean matchFound = FilenameUtils.wildcardMatch(sb.toString(), wildcardPath) ;
- if (matchFound) {
- return true ;
- }
- sb.append(File.separator) ;
- }
- sb = null;
- }
- return false;
- }
-
- public PolicyContainer getPolicyContainer() {
- return policyContainer;
- }
-
- private synchronized void setPolicyContainer(PolicyContainer aPolicyContainer) {
-
- for(Policy p : aPolicyContainer.getAcl()) {
- for(RolePermission rp : p.getPermissions()) {
- List<String> rpaccess = rp.getAccess() ;
- if (rpaccess != null && rpaccess.size() > 0) {
- List<String> temp = new ArrayList<String>() ;
- for(String s : rpaccess) {
- temp.add(s.toLowerCase()) ;
- }
- rp.setAccess(temp);
- }
- }
- }
-
- this.policyContainer = aPolicyContainer ;
- this.cachedAuditFlag.clear();
- }
-
-
-
- public UserPermission printPermissionInfo(UserGroupInformation ugi) {
- return printPermissionInfo(ugi, null) ;
- }
-
- public UserPermission printPermissionInfo(UserGroupInformation ugi, String aPathName) {
-
- String username = ugi.getShortUserName() ;
-
- String[] groups = ugi.getGroupNames() ;
-
- UserPermission up = new UserPermission(username,groups, aPathName) ;
-
- PolicyContainer pc = getPolicyContainer() ;
-
- if (pc != null) {
-
- for(Policy acl : pc.getAcl()) {
-
- for(ResourcePath resource : acl.getResourceList()) {
-
- String path = resource.getPath() ;
-
- boolean rulePathMatched = false ;
-
- if (acl.getRecursiveInd() == 1) {
- if (resource.isWildcardPath()) {
- rulePathMatched = isRecursiveWildCardMatch(aPathName, path) ;
- }
- else {
- rulePathMatched = aPathName.startsWith(path) ;
- }
- }
- else {
- if (resource.isWildcardPath()) {
- rulePathMatched = FilenameUtils.wildcardMatch(aPathName, path) ;
- }
- else {
- rulePathMatched = aPathName.equals(path) ;
- }
- }
-
-
- if (rulePathMatched) {
- for (RolePermission rp : acl.getPermissions()) {
- boolean isAccessGranted = false ;
- if (! isAccessGranted ) {
- if ( rp.getUsers().contains(username) ) {
- up.add(resource, acl.getRecursiveInd(), username, null, rp.getAccess());
- isAccessGranted = true ;
- }
- }
- if ( ! isAccessGranted ) {
- for(String ug : groups) {
- if ( rp.getGroups().contains(ug)) {
- up.add(resource, acl.getRecursiveInd(), null, ug, rp.getAccess());
- }
- }
- }
- if (! isAccessGranted ) {
- if (rp.getGroups().contains(XaSecureConstants.PUBLIC_ACCESS_ROLE)) {
- up.add(resource, acl.getRecursiveInd(), null, XaSecureConstants.PUBLIC_ACCESS_ROLE, rp.getAccess());
- }
- }
- }
- }
- }
- }
- }
-
- return up ;
- }
-
-
- class UserPermission {
-
- private String userName ;
- private String groups ;
- private String pathName ;
- private HashMap<String,HashSet<String>> userPermissionMap = new HashMap<String,HashSet<String>>() ;
-
- public UserPermission(String userName, String[] groupList, String pathName) {
- this.userName = userName ;
- this.pathName = pathName ;
- StringBuilder sb = new StringBuilder() ;
- boolean first = true ;
- TreeSet<String> gl = new TreeSet<String>() ;
- for(String g : groupList) {
- gl.add(g) ;
- }
- for(String group : gl) {
- if (first) {
- first = false ;
- }
- else {
- sb.append(",") ;
- }
- sb.append(group) ;
- }
- this.groups = sb.toString() ;
- }
-
-
- public void add(ResourcePath resource, int recursiveInd, String userName, String groupName, List<String> accessList) {
-
- String path = resource.getPath() ;
-
- if (recursiveInd == 1) {
- if (path.endsWith("/")) {
- path = path + "**" ;
- }
- else {
- path = path + "/" + "**" ;
- }
- }
-
- HashSet<String> permMap = userPermissionMap.get(path) ;
-
- if (permMap == null) {
- permMap = new HashSet<String>() ;
- userPermissionMap.put(path,permMap) ;
- }
-
- for(String access : accessList) {
- if (! permMap.contains(access)) {
- permMap.add(access) ;
- }
- }
-
- }
-
- public void printUserInfo() {
- System.out.println("# USER INFORMATION") ;
- System.out.println("USER: " + userName ) ;
- System.out.println("GROUPS: " + groups ) ;
- }
-
- public void print() {
- if (pathName != null) {
- System.out.println("# PERMISSION INFORMATION FOR PATH [" + pathName + "]" + (userPermissionMap.size() == 0 ? " - NO RULES FOUND" : "")) ;
- }
- else {
- System.out.println("# PERMISSION INFORMATION" + (userPermissionMap.size() == 0 ? " - NO RULES FOUND" : "")) ;
- }
-
-
- if (userPermissionMap.size() > 0) {
- TreeSet<String> pathSet = new TreeSet<String>() ;
- pathSet.addAll(userPermissionMap.keySet()) ;
- StringBuilder sb = new StringBuilder();
- for(String path : pathSet) {
- sb.setLength(0) ;
- sb.append(String.format("%-50s", path)).append("|") ;
- TreeSet<String> permSet = new TreeSet<String>() ;
- permSet.addAll(userPermissionMap.get(path)) ;
- boolean first = true ;
- for(String perm: permSet) {
- if (! first) {
- sb.append(",") ;
- }
- else {
- first = false ;
- }
- sb.append(perm) ;
- }
- System.out.println(sb.toString()) ;
- }
- }
-
- }
- }
-
-
- @Override
- public boolean isAuditLogEnabled(String aPathName) {
- boolean ret = false ;
-
- HashMap<String,Boolean> tempCachedAuditFlag = cachedAuditFlag ;
-
- Boolean auditResult = (tempCachedAuditFlag == null ? null : tempCachedAuditFlag.get(aPathName)) ;
-
- if (auditResult != null) {
- ret = auditResult ;
- }
- else {
- ret = isAuditLogEnabledByACL(aPathName) ;
- if (tempCachedAuditFlag != null) {
- // tempCachedAuditFlag.put(aPathName,Boolean.valueOf(ret)) ;
- synchronized(tempCachedAuditFlag) {
- if (tempCachedAuditFlag.size() > MAX_NO_OF_AUDIT_CACHE_ENTRIES) {
- tempCachedAuditFlag.clear();
- }
- tempCachedAuditFlag.put(aPathName,Boolean.valueOf(ret)) ;
- }
- }
- }
-
- return ret ;
-
- }
-
-
- public boolean isAuditLogEnabledByACL(String aPathName) {
-
- boolean ret = false ;
-
- PolicyContainer pc = getPolicyContainer() ;
-
- if (pc == null) {
- return false ;
- }
-
- for(Policy acl : pc.getAcl()) {
-
- for(ResourcePath resource : acl.getResourceList()) {
-
- String path = resource.getPath() ;
-
- boolean rulePathMatched = false ;
-
- if (acl.getRecursiveInd() == 1) {
- if (resource.isWildcardPath()) {
- rulePathMatched = isRecursiveWildCardMatch(aPathName, path) ;
- }
- else {
- rulePathMatched = aPathName.startsWith(path) ;
- }
- }
- else {
- if (resource.isWildcardPath()) {
- rulePathMatched = FilenameUtils.wildcardMatch(aPathName, path) ;
- }
- else {
- rulePathMatched = aPathName.equals(path) ;
- }
- }
-
-
- if (rulePathMatched) {
- ret = ( acl.getAuditInd() == 1) ;
- break ;
- }
- }
- }
-
- return ret ;
- }
-
- public static void main(String[] args) throws Throwable {
- LogManager.getLogger(URLBasedAuthDB.class).setLevel(Level.ERROR);
- URLBasedAuthDB authDB = URLBasedAuthDB.getInstance() ;
- UserPermission up = null;
- if (args.length == 0) {
- up = authDB.printPermissionInfo(UserGroupInformation.getCurrentUser());
- up.printUserInfo() ;
- up.print();
- }
- else {
- up = authDB.printPermissionInfo(UserGroupInformation.getCurrentUser());
- up.printUserInfo() ;
- for(String path : args) {
- up = authDB.printPermissionInfo(UserGroupInformation.getCurrentUser(), path);
- up.print();
- System.out.println();
- }
- }
- System.exit(0);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/hdfs/XASecureAuthorizer.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/hdfs/XASecureAuthorizer.java b/agents-impl/src/main/java/com/xasecure/pdp/hdfs/XASecureAuthorizer.java
deleted file mode 100644
index c29dd7c..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/hdfs/XASecureAuthorizer.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * 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 com.xasecure.pdp.hdfs;
-
-import java.util.Set;
-
-import com.xasecure.authorization.hadoop.HDFSAccessVerifier;
-
-public class XASecureAuthorizer implements HDFSAccessVerifier {
-
- private static URLBasedAuthDB authDB = URLBasedAuthDB.getInstance() ;
-
- @Override
- public boolean isAccessGranted(String aPathName, String aPathOwnerName, String access, String username, Set<String> groups) {
- return authDB.isAccessGranted(aPathName, aPathOwnerName, access, username, groups);
- }
-
- @Override
- public boolean isAuditLogEnabled(String aPathName) {
- return authDB.isAuditLogEnabled(aPathName) ;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/hive/HiveAuthDB.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/hive/HiveAuthDB.java b/agents-impl/src/main/java/com/xasecure/pdp/hive/HiveAuthDB.java
deleted file mode 100644
index e64c3e9..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/hive/HiveAuthDB.java
+++ /dev/null
@@ -1,307 +0,0 @@
-/*
- * 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 com.xasecure.pdp.hive;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.security.UserGroupInformation;
-
-import com.xasecure.authorization.hive.XaHiveObjectAccessInfo;
-import com.xasecure.authorization.hive.XaHiveObjectAccessInfo.HiveAccessType;
-import com.xasecure.authorization.hive.XaHiveObjectAccessInfo.HiveObjectType;
-import com.xasecure.authorization.utils.StringUtil;
-
-public class HiveAuthDB {
-
- private static final Log LOG = LogFactory.getLog(HiveAuthDB.class);
-
- private ArrayList<HiveAuthRule> allRuleList = null;
- private ArrayList<HiveAuthRule> tblRuleList = null;
- private ArrayList<HiveAuthRule> colRuleList = null;
-
- public HiveAuthDB() {
- this(null) ;
- }
-
-
- public HiveAuthDB(ArrayList<HiveAuthRule> aRuleList) {
-
- if (aRuleList == null) {
- aRuleList = new ArrayList<HiveAuthRule>() ;
- }
-
- LOG.info("Number of Rules in the PolicyContainer: " + ((aRuleList == null) ? 0 : aRuleList.size()) ) ;
-
- allRuleList = new ArrayList<HiveAuthRule>() ;
- colRuleList = new ArrayList<HiveAuthRule>();
- tblRuleList = new ArrayList<HiveAuthRule>() ;
-
- allRuleList = aRuleList ;
-
- for (HiveAuthRule rule : aRuleList) {
- if (rule.isTableRule()) {
- this.tblRuleList.add(rule);
- } else {
- this.colRuleList.add(rule);
- }
- }
-
- }
-
- public boolean isAccessAllowed(UserGroupInformation ugi, XaHiveObjectAccessInfo objAccessInfo) {
- boolean ret = false;
-
- if(objAccessInfo.getAccessType() == HiveAccessType.NONE || objAccessInfo.getObjectType() == HiveObjectType.NONE) {
- return true;
- }
-
- String accessType = objAccessInfo.getAccessType().name();
-
- switch(objAccessInfo.getObjectType()) {
- case DATABASE:
- ret = isAccessAllowed(ugi, accessType, objAccessInfo.getDatabase());
- break;
-
- case TABLE:
- case INDEX:
- case PARTITION:
- ret = isAccessAllowed(ugi, accessType, objAccessInfo.getDatabase(), objAccessInfo.getTable());
- break;
-
- case VIEW:
- ret = isAccessAllowed(ugi, accessType, objAccessInfo.getDatabase(), objAccessInfo.getView());
- break;
-
- case COLUMN:
- {
- String deniedColumn = findDeniedColumn(ugi, accessType, objAccessInfo.getDatabase(), objAccessInfo.getTable(), objAccessInfo.getColumns());
-
- ret = StringUtil.isEmpty(deniedColumn);
-
- if(! ret) {
- objAccessInfo.setDeinedObjectName(XaHiveObjectAccessInfo.getObjectName(objAccessInfo.getDatabase(), objAccessInfo.getTable(), deniedColumn));
- }
- }
- break;
-
- case FUNCTION:
- ret = isUDFAccessAllowed(ugi, accessType, objAccessInfo.getDatabase(), objAccessInfo.getFunction());
- break;
-
- case URI:
- // Handled in XaSecureHiveAuthorizer
- break;
-
- case NONE:
- break;
- }
-
- return ret;
- }
-
- public boolean isAudited(XaHiveObjectAccessInfo objAccessInfo) {
- boolean ret = false;
-
- if( objAccessInfo.getAccessType() == HiveAccessType.NONE
- || objAccessInfo.getObjectType() == HiveObjectType.NONE
- || objAccessInfo.getObjectType() == HiveObjectType.URI
- ) {
- return false;
- }
-
- String database = null;
- String table = null;
- List<String> columns = null;
- boolean isUDF = false;
-
- switch(objAccessInfo.getObjectType()) {
- case DATABASE:
- database = objAccessInfo.getDatabase();
- break;
-
- case TABLE:
- case INDEX:
- case PARTITION:
- database = objAccessInfo.getDatabase();
- table = objAccessInfo.getTable();
- break;
-
- case VIEW:
- database = objAccessInfo.getDatabase();
- table = objAccessInfo.getView();
- break;
-
- case COLUMN:
- database = objAccessInfo.getDatabase();
- table = objAccessInfo.getTable();
- columns = objAccessInfo.getColumns();
- break;
-
- case FUNCTION:
- database = objAccessInfo.getDatabase();
- table = objAccessInfo.getFunction();
- isUDF = true;
- break;
-
- case NONE:
- case URI:
- break;
- }
-
- if(StringUtil.isEmpty(columns)) {
- for (HiveAuthRule rule : allRuleList) {
- if(isUDF != rule.isUdf()) {
- continue;
- }
-
- if (rule.isTableMatch(database, table)) {
- ret = rule.isAudited() ;
-
- if (ret) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("isAudited(database=" + database + ", table=" + table + ", columns=" + StringUtil.toString(columns) + ") => [" + ret + "] as matched for rule: " + rule);
- }
-
- break ;
- }
- }
- }
- } else {
- // is audit enabled for any one column being accessed?
- for(String colName : columns) {
- for (HiveAuthRule rule : allRuleList) {
- if(isUDF != rule.isUdf()) {
- continue;
- }
-
- ret = rule.isMatched(database, table, colName) && rule.isAudited();
-
- if (ret) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("isAudited(database=" + database + ", table=" + table + ", columns=" + StringUtil.toString(columns) + ") => [" + ret + "] as matched for rule: " + rule);
- }
-
- break ;
- }
- }
-
- if(ret) {
- break;
- }
- }
- }
-
- return ret ;
- }
-
- private boolean isAccessAllowed(UserGroupInformation ugi, String accessType, String database) {
- boolean ret = false;
-
- for (HiveAuthRule rule : allRuleList) {
- ret = rule.isMatched(database, ugi.getShortUserName(), ugi.getGroupNames(), accessType);
-
- if(ret) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("isAccessAllowed(user=" + ugi.getShortUserName() + ", groups=" + StringUtil.toString(ugi.getGroupNames()) + ", accessType=" + accessType + ", database=" + database + ") => [" + ret + "] as matched for rule: " + rule);
- }
-
- break;
- }
- }
-
- return ret;
- }
-
- private boolean isAccessAllowed(UserGroupInformation ugi, String accessType, String database, String tableOrView) {
- boolean ret = false;
-
- for (HiveAuthRule rule : tblRuleList) {
- ret = rule.isMatched(database, tableOrView, ugi.getShortUserName(), ugi.getGroupNames(), accessType);
-
- if(ret) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("isAccessAllowed(user=" + ugi.getShortUserName() + ", groups=" + StringUtil.toString(ugi.getGroupNames()) + ", accessType=" + accessType + ", database=" + database + ", tableOrView=" + tableOrView + ") => [" + ret + "] as matched for rule: " + rule);
- }
-
- break;
- }
- }
-
- return ret;
- }
-
- private String findDeniedColumn(UserGroupInformation ugi, String accessType, String database, String tableOrView, List<String> columns) {
- String deinedColumn = null;
-
- boolean isAllowed = isAccessAllowed(ugi, accessType, database, tableOrView); // check if access is allowed at the table level
-
- if(!isAllowed && !StringUtil.isEmpty(columns)) {
- for(String column : columns) {
- for (HiveAuthRule rule : colRuleList) {
- isAllowed = rule.isMatched(database, tableOrView, column, ugi.getShortUserName(), ugi.getGroupNames(), accessType);
-
- if(isAllowed) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("isAccessAllowed(user=" + ugi.getShortUserName() + ", groups=" + StringUtil.toString(ugi.getGroupNames()) + ", accessType=" + accessType + ", database=" + database + ", tableOrView=" + tableOrView + ", column=" + column + ") => [" + isAllowed + "] as matched for rule: " + rule);
- }
-
- break;
- }
- }
-
- if(!isAllowed) {
- deinedColumn = column;
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("isAccessAllowed(user=" + ugi.getShortUserName() + ", groups=" + StringUtil.toString(ugi.getGroupNames()) + ", accessType=" + accessType + ", database=" + database + ", tableOrView=" + tableOrView + ", column=" + column + ") => [" + isAllowed + "]");
- }
- break;
- }
- }
- }
-
- return deinedColumn;
- }
-
- private boolean isUDFAccessAllowed(UserGroupInformation ugi, String accessType, String database, String udfName) {
- boolean ret = false;
-
- for (HiveAuthRule rule : tblRuleList) {
- if(! rule.isUdf()) {
- continue;
- }
-
- ret = rule.isMatched(database, udfName, ugi.getShortUserName(), ugi.getGroupNames(), accessType);
-
- if(ret) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("isAccessAllowed(user=" + ugi.getShortUserName() + ", groups=" + StringUtil.toString(ugi.getGroupNames()) + ", accessType=" + accessType + ", database=" + database + ", udfName=" + udfName + ") => [" + ret + "] as matched for rule: " + rule);
- }
-
- break;
- }
- }
-
- return ret;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/hive/HiveAuthRule.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/hive/HiveAuthRule.java b/agents-impl/src/main/java/com/xasecure/pdp/hive/HiveAuthRule.java
deleted file mode 100644
index 984b680..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/hive/HiveAuthRule.java
+++ /dev/null
@@ -1,223 +0,0 @@
-/*
- * 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 com.xasecure.pdp.hive;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import com.xasecure.authorization.hive.XaHiveObjectAccessInfo.HiveAccessType;
-import com.xasecure.authorization.hive.constants.XaSecureHiveConstants;
-import com.xasecure.authorization.utils.StringUtil;
-
-
-public class HiveAuthRule {
-
- private static final Log LOG = LogFactory.getLog(HiveAuthRule.class) ;
-
- public static final String WILDCARD_OBJECT = ".*" ;
-
- private String databaseName;
- private String tableName;
- private String columnName;
- private String accessType;
- private String group;
- private String user;
- private boolean tableRule = false;
- private boolean allGranted = false;
- private boolean udf = false;
- private boolean tableExcluded = false;
- private boolean columnExcluded = false;
- private boolean audited = false;
- private boolean encrypted = false;
-
- public HiveAuthRule(String dbName, String tableName, String colName, String permission, String user, String group) {
- this(false, dbName,tableName,colName,permission,user,group, false, false) ;
- }
-
- public HiveAuthRule(boolean udfInd, String dbName, String tableName, String colName, String permission, String user, String group, boolean tableExclusionFlag, boolean columnExclusionFlag) {
- this.udf = udfInd ;
- this.databaseName = StringUtil.toLower(dbName);
- this.tableName = StringUtil.toLower(tableName);
- this.columnName = StringUtil.toLower(colName);
- this.accessType = permission ;
- this.user = user;
- this.group = group ;
- this.tableExcluded = tableExclusionFlag ;
- this.columnExcluded = columnExclusionFlag ;
-
- this.allGranted = StringUtil.equalsIgnoreCase(HiveAccessType.ALL.name(), accessType);
-
- tableRule = StringUtil.isEmpty(columnName) || WILDCARD_OBJECT.matches(columnName) ;
- }
-
- @Override
- public String toString() {
- return "db:" + databaseName + ", table: " + tableName + ", columnName: " + columnName + ", accessType: " + accessType + ",user: " + user + ", group: " + group + ",isTable:" + tableRule + ",audited:" + audited + ",encrypted:" + encrypted ;
- }
-
- public boolean isMatched(String user, String[] groups, String accessType) {
- String dbName = null;
- String tblName = null;
- String colName = null;
-
- return isMatched(dbName, tblName, colName, user, groups, accessType) ;
- }
-
- public boolean isMatched(String dbName, String user, String[] groups, String accessType) {
- String tblName = null;
- String colName = null;
-
- return isMatched(dbName, tblName, colName, user, groups, accessType) ;
- }
-
- public boolean isMatched(String dbName, String tblName, String user, String[] groups, String accessType) {
- String colName = null;
-
- return isMatched(dbName, tblName, colName, user, groups, accessType) ;
- }
-
- public boolean isMatched(String dbName, String tblName, String colName, String user, String[] groups, String accessType) {
- boolean ret = isMatched(dbName, tblName, colName);
-
- if(ret) {
- // does accessType match?
- ret = StringUtil.equalsIgnoreCase(accessType, this.accessType);
-
- if(! ret && !StringUtil.equalsIgnoreCase(accessType, HiveAccessType.ADMIN.name())) {
- ret = this.isAllGranted() || StringUtil.equalsIgnoreCase(accessType, "USE");
- }
-
- if(ret) {
- // does user/group match?
- ret = StringUtil.equals(user, this.user) ||
- StringUtil.equals(XaSecureHiveConstants.PUBLIC_ACCESS_ROLE, this.group) ||
- StringUtil.contains(groups, this.group);
- }
- }
-
- if(LOG.isDebugEnabled()) {
- LOG.debug("isMatched(db=" + dbName + ", table=" + tblName + ", col=" + colName + ", user=" + user + ", groups=" + StringUtil.toString(groups) + ", accessType=" + accessType + ") => rule[" + this.databaseName + ":" + this.tableName + ":" + this.columnName + ":" + this.user + ":" + this.group + ":" + this.accessType + "] returns [" + ret + "]");
- }
-
- return ret ;
- }
-
- public boolean isMatched(String dbName, String tblName, String colName) {
- boolean ret = isTableMatch(dbName, tblName);
-
- if (ret) {
- colName = StringUtil.toLower(colName);
-
- if (colName != null) {
- ret = colName.matches(this.columnName);
-
- if (columnExcluded) {
- ret = (! ret) ;
- }
- }
- }
-
- if(LOG.isDebugEnabled()) {
- LOG.debug("isMatched(db=" + dbName + ", table=" + tblName + ", col=" + colName + ") => rule[" + this.databaseName + ":" + this.tableName + ":" + this.columnName + "] returns [" + ret + "]");
- }
-
- return ret ;
- }
-
- public boolean isTableMatch(String dbName, String tblName) {
- boolean ret = isDBMatch(dbName);
-
- if(ret) {
- tblName = StringUtil.toLower(tblName);
-
- if(tblName != null) {
- ret = tblName.matches(this.tableName);
-
- if(tableExcluded) {
- ret = !ret;
- }
- }
- }
-
- return ret;
- }
-
- public boolean isDBMatch(String dbName) {
- boolean ret = false;
-
- dbName = StringUtil.toLower(dbName);
-
- ret = dbName == null || dbName.matches(this.databaseName);
-
- return ret;
- }
-
- public String getDbName() {
- return databaseName;
- }
-
- public String getTableName() {
- return tableName;
- }
-
- public String getColumnName() {
- return columnName;
- }
-
- public String getAccessType() {
- return accessType;
- }
-
- public String getUser() {
- return user;
- }
-
- public String getGroup() {
- return group;
- }
-
- public boolean isTableRule() {
- return tableRule;
- }
-
- public boolean isAllGranted() {
- return allGranted ;
- }
-
- public boolean isUdf() {
- return udf;
- }
-
- public boolean isAudited() {
- return audited;
- }
-
- public void setAudited(boolean audited) {
- this.audited = audited;
- }
-
- public boolean isEncrypted() {
- return encrypted;
- }
-
- public void setEncrypted(boolean encrypted) {
- this.encrypted = encrypted;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/hive/HiveAuthorizationProviderBase.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/hive/HiveAuthorizationProviderBase.java b/agents-impl/src/main/java/com/xasecure/pdp/hive/HiveAuthorizationProviderBase.java
deleted file mode 100644
index 3fd845e..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/hive/HiveAuthorizationProviderBase.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * 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 com.xasecure.pdp.hive;
-
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.hive.ql.metadata.AuthorizationException;
-import org.apache.hadoop.security.UserGroupInformation;
-
-import com.xasecure.authorization.hive.XaHiveAccessVerifier;
-import com.xasecure.authorization.hive.XaHiveObjectAccessInfo;
-
-public class HiveAuthorizationProviderBase implements XaHiveAccessVerifier {
-
- private static final Log LOG = LogFactory.getLog(HiveAuthorizationProviderBase.class);
-
- protected HiveAuthDB authDB = new HiveAuthDB() ;
-
-
- public HiveAuthDB getAuthDB() {
- return authDB ;
- }
-
- @Override
- public boolean isAccessAllowed(UserGroupInformation ugi, XaHiveObjectAccessInfo objAccessInfo) {
- HiveAuthDB ldb = authDB ;
-
- if (ldb == null) {
- throw new AuthorizationException("No Authorization Agent is available for AuthorizationCheck") ;
- }
-
- boolean ret = ldb.isAccessAllowed(ugi, objAccessInfo);
-
- return ret;
- }
-
- @Override
- public boolean isAudited(XaHiveObjectAccessInfo objAccessInfo) {
- HiveAuthDB ldb = authDB ;
-
- if (ldb == null) {
- throw new AuthorizationException("No Authorization Agent is available for AuthorizationCheck") ;
- }
-
- return ldb.isAudited(objAccessInfo) ;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/hive/URLBasedAuthDB.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/hive/URLBasedAuthDB.java b/agents-impl/src/main/java/com/xasecure/pdp/hive/URLBasedAuthDB.java
deleted file mode 100644
index fc07c6e..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/hive/URLBasedAuthDB.java
+++ /dev/null
@@ -1,222 +0,0 @@
-/*
- * 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 com.xasecure.pdp.hive;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import com.xasecure.authorization.hadoop.config.XaSecureConfiguration;
-import com.xasecure.pdp.config.PolicyChangeListener;
-import com.xasecure.pdp.config.PolicyRefresher;
-import com.xasecure.pdp.constants.XaSecureConstants;
-import com.xasecure.pdp.model.Policy;
-import com.xasecure.pdp.model.PolicyContainer;
-import com.xasecure.pdp.model.RolePermission;
-
-public class URLBasedAuthDB extends HiveAuthorizationProviderBase implements PolicyChangeListener {
-
- private static final Log LOG = LogFactory.getLog(URLBasedAuthDB.class) ;
-
- private static URLBasedAuthDB me = null ;
-
- private PolicyContainer policyContainer = null ;
-
- private PolicyRefresher refresher = null ;
-
-
- public static URLBasedAuthDB getInstance() {
- if (me == null) {
- synchronized(URLBasedAuthDB.class) {
- URLBasedAuthDB temp = me ;
- if (temp == null) {
- me = new URLBasedAuthDB() ;
- me.init() ;
- }
- }
- }
- return me ;
- }
-
- private URLBasedAuthDB() {
- String url = XaSecureConfiguration.getInstance().get(XaSecureConstants.XASECURE_HIVE_POLICYMGR_URL_PROP);
- long refreshInMilli = XaSecureConfiguration.getInstance().getLong(
- XaSecureConstants.XASECURE_HIVE_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_PROP ,
- XaSecureConstants.XASECURE_HIVE_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_DEFAULT);
-
- String lastStoredFileName = XaSecureConfiguration.getInstance().get(XaSecureConstants.XASECURE_HIVE_LAST_SAVED_POLICY_FILE_PROP) ;
-
- String sslConfigFileName = XaSecureConfiguration.getInstance().get(XaSecureConstants.XASECURE_HIVE_POLICYMGR_SSL_CONFIG_FILE_PROP) ;
- refresher = new PolicyRefresher(url, refreshInMilli,sslConfigFileName,lastStoredFileName) ;
-
- String saveAsFileName = XaSecureConfiguration.getInstance().get(XaSecureConstants.XASECURE_HIVE_POLICYMGR_URL_SAVE_FILE_PROP) ;
- if (saveAsFileName != null) {
- refresher.setSaveAsFileName(saveAsFileName) ;
- }
-
- if (lastStoredFileName != null) {
- refresher.setLastStoredFileName(lastStoredFileName);
- }
-
- }
-
- private void init() {
- refresher.setPolicyChangeListener(this);
- }
-
- public PolicyContainer getPolicyContainer() {
- return policyContainer;
- }
-
- @Override
- public void OnPolicyChange(PolicyContainer policyContainer) {
-
- LOG.debug("OnPolicyChange() has been called with new PolicyContainer .....") ;
-
- try {
-
- ArrayList<HiveAuthRule> ruleListTemp = new ArrayList<HiveAuthRule>();
-
- this.policyContainer = policyContainer;
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Number of acl found (before isEnabled check): " + ( policyContainer.getAcl() == null ? 0 : policyContainer.getAcl().size() ) );
- }
-
- for(Policy acl : policyContainer.getAcl()) {
-
- if (! acl.isEnabled()) {
- LOG.debug("Diabled acl found [" + acl + "]. Skipping this acl ...") ;
- continue ;
- }
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Number of database found in acl [" + acl + "] " + ( acl.getDatabaseList() == null ? 0 : acl.getDatabaseList().size() ) );
- LOG.debug("Number of Tables found in acl [" + acl + "] " + ( acl.getTableList() == null ? 0 : acl.getTableList().size() ) );
- LOG.debug("Number of Columns found in acl [" + acl + "] " + ( acl.getColumnList()== null ? 0 : acl.getColumnList().size() ) );
- }
-
- boolean isUDF = false ;
-
- List<String> dbList = new ArrayList<String>() ;
- String dbs = replaceFileBasedRegEx(acl.getDatabases()) ;
- dbList.add(getRegExFormatted(dbs)) ;
-
- List<String> tableList = new ArrayList<String>() ;
- String udfs = acl.getUdfs() ;
- if (udfs != null) {
- isUDF = true ;
- dbList.clear();
- dbList.add(HiveAuthRule.WILDCARD_OBJECT) ;
- tableList.clear();
- udfs = replaceFileBasedRegEx(udfs) ;
- tableList.add(getRegExFormatted(udfs)) ;
- }
- else {
- String tables = replaceFileBasedRegEx(acl.getTables()) ;
- tableList.add(getRegExFormatted(tables)) ;
- }
-
- List<String> columnList = new ArrayList<String>() ;
- String columns = replaceFileBasedRegEx(acl.getColumns()) ;
- columnList.add(getRegExFormatted(columns)) ;
-
-
- boolean isAudited = (acl.getAuditInd() == 1) ;
-
- boolean isEncrypted = (acl.getEncryptInd() == 1) ;
-
- for(String db : dbList) {
-
- for(String table : tableList) {
-
- for(String col : columnList) {
-
- for(RolePermission rp : acl.getPermissions()) {
- for (String accessLevel : rp.getAccess() ) {
- for (String group : rp.getGroups()) {
- HiveAuthRule rule = new HiveAuthRule(isUDF, db, table, col, accessLevel.toLowerCase(), null, group, acl.isTableSelectionExcluded(), acl.isColumnSelectionExcluded());
- rule.setAudited(isAudited);
- rule.setEncrypted(isEncrypted);
- LOG.debug("Adding rule [" + rule + "] to the authdb.");
- ruleListTemp.add(rule);
- }
- for (String user : rp.getUsers()) {
- HiveAuthRule rule = new HiveAuthRule(isUDF, db, table, col, accessLevel.toLowerCase(), user, null,acl.isTableSelectionExcluded(), acl.isColumnSelectionExcluded());
- rule.setAudited(isAudited);
- rule.setEncrypted(isEncrypted);
- LOG.debug("Adding rule [" + rule + "] to the authdb.");
- ruleListTemp.add(rule);
- }
- }
- }
-
-
- }
- }
- }
- }
- HiveAuthDB authDBTemp = new HiveAuthDB(ruleListTemp);
- authDB = authDBTemp;
- }
- catch(Throwable t) {
- LOG.error("OnPolicyChange has failed with an exception", t);
- }
- }
-
- public static String getRegExFormatted(String userEnteredStr) {
-
- if (userEnteredStr == null || userEnteredStr.trim().length() == 0) {
- return HiveAuthRule.WILDCARD_OBJECT ;
- }
-
- StringBuilder sb = new StringBuilder() ;
-
- for(String s : userEnteredStr.split(",")) {
- if (sb.length() == 0) {
- sb.append("(") ;
- }
- else {
- sb.append("|") ;
- }
- sb.append(s.trim()) ;
- }
-
- if (sb.length() > 0) {
- sb.append(")") ;
- }
-
- return sb.toString() ;
- }
-
-
- public static String replaceFileBasedRegEx(String userEnteredStr) {
- if (userEnteredStr != null) {
- userEnteredStr = userEnteredStr.replaceAll("\\.", "\\.")
- .replaceAll("\\?", "\\.")
- .replaceAll("\\*", ".*") ;
- }
- return userEnteredStr ;
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/hive/XASecureAuthorizer.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/hive/XASecureAuthorizer.java b/agents-impl/src/main/java/com/xasecure/pdp/hive/XASecureAuthorizer.java
deleted file mode 100644
index 2eca90f..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/hive/XASecureAuthorizer.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * 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 com.xasecure.pdp.hive;
-
-import org.apache.hadoop.hive.ql.metadata.AuthorizationException;
-import org.apache.hadoop.security.UserGroupInformation;
-
-import com.xasecure.authorization.hive.XaHiveAccessVerifier;
-import com.xasecure.authorization.hive.XaHiveObjectAccessInfo;
-
-public class XASecureAuthorizer implements XaHiveAccessVerifier {
-
- private XaHiveAccessVerifier authDB = URLBasedAuthDB.getInstance() ;
-
-
- @Override
- public boolean isAccessAllowed(UserGroupInformation ugi, XaHiveObjectAccessInfo objAccessInfo) {
- if (authDB == null) {
- throw new AuthorizationException("No Authorization Agent is available for AuthorizationCheck") ;
- }
- return authDB.isAccessAllowed(ugi, objAccessInfo);
- }
-
- @Override
- public boolean isAudited(XaHiveObjectAccessInfo objAccessInfo) {
- if (authDB == null) {
- throw new AuthorizationException("No Authorization Agent is available for AuthorizationCheck") ;
- }
- return authDB.isAudited(objAccessInfo) ;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/knox/URLBasedAuthDB.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/knox/URLBasedAuthDB.java b/agents-impl/src/main/java/com/xasecure/pdp/knox/URLBasedAuthDB.java
deleted file mode 100644
index fb147b3..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/knox/URLBasedAuthDB.java
+++ /dev/null
@@ -1,453 +0,0 @@
-/**
- * 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 com.xasecure.pdp.knox;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Set;
-
-import org.apache.commons.io.FilenameUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import com.xasecure.authorization.hadoop.config.XaSecureConfiguration;
-import com.xasecure.pdp.config.Jersey2PolicyRefresher;
-import com.xasecure.pdp.config.PolicyChangeListener;
-import com.xasecure.pdp.constants.XaSecureConstants;
-import com.xasecure.pdp.model.Policy;
-import com.xasecure.pdp.model.PolicyContainer;
-import com.xasecure.pdp.model.RolePermission;
-
-public class URLBasedAuthDB implements PolicyChangeListener {
-
- private static final Log LOG = LogFactory.getLog(URLBasedAuthDB.class) ;
-
- private static URLBasedAuthDB me = null;
-
- private Jersey2PolicyRefresher refresher = null ;
-
- private PolicyContainer policyContainer = null;
-
- private HashMap<String,Boolean> cachedAuditFlag = new HashMap<String,Boolean>() ; // needs to be cleaned when ruleList changes
-
- public static URLBasedAuthDB getInstance() {
- if (me == null) {
- synchronized (URLBasedAuthDB.class) {
- URLBasedAuthDB temp = me;
- if (temp == null) {
- me = new URLBasedAuthDB();
- me.init() ;
- }
- }
- }
- return me;
- }
-
- public static URLBasedAuthDB getInstanceWithBackEndMocked() {
- return new URLBasedAuthDB("instanceWithBackednMocked");
- }
-
- private URLBasedAuthDB() {
- String url = XaSecureConfiguration.getInstance().get(XaSecureConstants.XASECURE_KNOX_POLICYMGR_URL_PROP);
- long refreshInMilli = XaSecureConfiguration.getInstance().getLong(
- XaSecureConstants.XASECURE_KNOX_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_PROP ,
- XaSecureConstants.XASECURE_KNOX_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_DEFAULT);
- String sslConfigFileName = XaSecureConfiguration.getInstance().get(XaSecureConstants.XASECURE_KNOX_POLICYMGR_SSL_CONFIG_FILE_PROP) ;
-
- String lastStoredFileName = XaSecureConfiguration.getInstance().get(XaSecureConstants.XASECURE_KNOX_LAST_SAVED_POLICY_FILE_PROP) ;
-
- refresher = new Jersey2PolicyRefresher(url, refreshInMilli,sslConfigFileName,lastStoredFileName) ;
-
- String saveAsFileName = XaSecureConfiguration.getInstance().get(XaSecureConstants.XASECURE_KNOX_POLICYMGR_URL_SAVE_FILE_PROP) ;
- if (saveAsFileName != null) {
- refresher.setSaveAsFileName(saveAsFileName) ;
- }
-
- if (lastStoredFileName != null) {
- refresher.setLastStoredFileName(lastStoredFileName);
- }
- }
-
- private URLBasedAuthDB(String mockName) {
- }
-
- private void init() {
- refresher.setPolicyChangeListener(this);
- }
-
-
- @Override
- public void OnPolicyChange(PolicyContainer aPolicyContainer) {
- setPolicyContainer(aPolicyContainer);
- }
-
-
- public boolean isAccessGranted(String topology, String service, String access, String userName, Set<String> groups,
- String requestIp) {
-
- boolean accessGranted = false;
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Evaluating access for topology: " + topology +
- ", service: " + service +
- ", access: " + access +
- ", requestingIp: " +requestIp +
- ", requestingUser: " + userName +
- ", requestingUserGroups: " + groups);
- }
- PolicyContainer policyContainer = getPolicyContainer() ;
-
- if (policyContainer == null) {
- LOG.warn("Denying access: policyContainer is null") ;
- return false ;
- }
-
- for(Policy policy : policyContainer.getAcl()) {
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Evaluating policy: " + policy.toString() ) ;
- }
-
- if (!policy.isEnabled()) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Skipping policy: " + policy + ", policy disabled") ;
- }
- continue; // jump to next policy
- }
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Evaluating topology match for policyTopologyList: " + policy.getTopologyList() +
- ", requestTopology: " + topology) ;
- }
-
- boolean topologyMatched = false;
-
- List<String> topologyList = policy.getTopologyList();
- if (topologyList == null || topologyList.isEmpty()) {
- LOG.debug("Denying access: policy topologyList is empty") ;
- continue; // jump to next policy
- }
-
- if (topologyList.contains("*") || topologyList.contains(topology)) {
- topologyMatched = true;
- LOG.debug("Policy topologyList matches requested topology");
- }
-
- if (!topologyMatched) {
- for (String policyTopology : topologyList) {
- if (FilenameUtils.wildcardMatch(topology, policyTopology)) {
- topologyMatched = true;
- LOG.debug("Policy topologyList matches requested topology");
- break; // break out of topologyList
- }
- }
- }
- if (!topologyMatched) {
- LOG.debug("Denying access: policy topologyList does not match requested topology") ;
- continue; // jump to next policy
- } else {
- LOG.debug("policy topologyList matches requested topology");
- }
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Evaluating service match for policyServiceList: " + policy.getServiceList() +
- ", requestService: " + service) ;
- }
-
- boolean serviceMatched = false;
-
- List<String> serviceList = policy.getServiceList();
- if (serviceList == null || serviceList.isEmpty()) {
- LOG.debug("Denying access: policy serviceList is empty") ;
- continue; // jump to next policy
- }
-
- if (serviceList.contains("*") || serviceList.contains(service)) {
- serviceMatched = true;
- LOG.debug("Policy serviceList matches requested service");
- }
-
- if (!serviceMatched) {
- for (String policyService : serviceList) {
- if (FilenameUtils.wildcardMatch(service, policyService)) {
- serviceMatched = true;
- LOG.debug("Policy serviceList matches requested service");
- break; // break out of serviceList
- }
- }
- }
- if (!serviceMatched) {
- LOG.debug("Denying access: policy serviceList does not match requested service") ;
- continue; // jump to next policy
- } else {
- LOG.debug("Policy serviceList matches requested service");
- }
-
- LOG.debug("Checking accessType, IP, User, Group based permission");
- if ( policy.getPermissions() == null
- || policy.getPermissions().isEmpty()) {
- LOG.debug("Policy not applicable, no user or group based permission");
- }
-
- for (RolePermission rp : policy.getPermissions()) {
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Evaluating RolePermission: " + rp);
- }
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Checking accessTypeMatch for rolePermissionAccesType: "
- + rp.getAccess() + ", requestAccessType: " + access);
- }
-
- if (rp.getAccess().contains(access)) {
-
- LOG.debug("RolePermission accessType matches request accessType");
-
- boolean ipMatched = false;
- List<String> ipList = rp.getIpAddress();
- if (LOG.isDebugEnabled()) {
- LOG.debug("Checking ipMatch for rolePermissionIpList: " + ipList +
- ", requestIP: " + requestIp);
- }
-
- if (ipList == null || ipList.isEmpty()) {
- LOG.debug("RolePermission does not require IP Matching");
- ipMatched = true;
- } else if ( ipList.contains("*") ) {
- LOG.debug("RolePermission allows any IP: *");
- ipMatched = true;
- } else {
- for (String ip : ipList) {
- if (ipMatches(ip, requestIp)) {
- LOG.debug("RolePermission IP matches request IP");
- ipMatched = true;
- break;// break out of ipList
- }
- }
- }
-
- if (!ipMatched) {
- // ip not matched, jump to next RolePermission check
- LOG.debug("Request IP does not match RolePermission");
- continue; // jump to next rolePermission
- } else {
- LOG.debug("Request IP matches RolePermission");
- }
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Checking userMatch for rolePermissionUsers: "
- + rp.getUsers() + ", requestUser: " + userName);
- }
-
- if ( rp.getUsers() != null && rp.getUsers().contains(userName) ) {
- LOG.debug("Request user matches RolePermission");
- return true ;
- }
- LOG.debug("RolePermission does not permit request by request user, would check by groups");
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Checking groupMatch for rolePermissionGroups: "
- + rp.getGroups() + ", requestGroups: " + groups);
- }
-
- for(String ug : groups) {
- if ( rp.getGroups() != null && rp.getGroups().contains(ug)) {
- LOG.debug("Request userGroups matches RolePermission");
- return true ;
- }
- }
- LOG.debug("RolePermission does not permit request by request user groups");
-
- if (rp.getGroups().contains(XaSecureConstants.PUBLIC_ACCESS_ROLE)) {
- LOG.debug("RolePermission applies to public group");
- return true ;
- }
-
- LOG.debug("RolePermission does not permit by users, groups or public group");
- } else {
- LOG.debug("rolePermissionAccessType does not match requestAccessType");
- }
- }
- }
- LOG.debug("No matching policy permission found, denying access");
- return accessGranted;
- }
-
- public boolean isAuditEnabled(String topology, String service) {
-
- boolean auditEnabled = false;
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Checcking whether audit is enabled for topology: " + topology +
- ", service: " + service );
- }
-
- PolicyContainer policyContainer = getPolicyContainer() ;
- if (policyContainer == null) {
- LOG.warn("PolicyContainer is null") ;
- return false ;
- }
-
- for(Policy policy : policyContainer.getAcl()) {
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Evaluating policy: " + policy) ;
- }
-
- if (!policy.isEnabled()) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Skipping policy: " + policy + ", policy disabled") ;
- }
- continue; // jump to next policy
- }
-
- if (policy.getAuditInd() == 0) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Skipping policy: " + policy + ", policy audit disabled") ;
- }
- continue; // jump to next policy
- }
-
- boolean topologyMatched = false;
-
- List<String> topologyList = policy.getTopologyList();
- if (topologyList == null || topologyList.isEmpty()) {
- LOG.debug("Policy not applicable: policy topologyList is empty") ;
- continue; // jump to next policy
- }
-
- if (topologyList.contains("*") || topologyList.contains(topology)) {
- topologyMatched = true;
- LOG.debug("Policy topologyList matches requested topology");
- }
-
- if (!topologyMatched) {
- for (String policyTopology : topologyList) {
- if (FilenameUtils.wildcardMatch(topology, policyTopology)) {
- topologyMatched = true;
- LOG.debug("Policy topologyList matches requested topology");
- break; // break out of topologyList check
- }
- }
- }
- if (!topologyMatched) {
- LOG.debug("Policy not applicable: polocy topologyList does not match requested topology") ;
- continue; // jump to next policy
- } else {
- LOG.debug("Policy topologyList matches requested topology");
- }
-
- boolean serviceMatched = false;
-
- List<String> serviceList = policy.getServiceList();
- if (serviceList == null || serviceList.isEmpty()) {
- LOG.debug("Policy not applicable: serviceList is empty") ;
- continue; // jump to next policy
- }
-
- if (serviceList.contains("*") || serviceList.contains(service)) {
- serviceMatched = true;
- LOG.debug("Policy serviceList matches requested service");
- }
-
- if (!serviceMatched) {
- for (String policyService : serviceList) {
- if (FilenameUtils.wildcardMatch(service, policyService)) {
- serviceMatched = true;
- LOG.debug("Policy serviceList matches requested service");
- break; // break out of serviceList check
- }
- }
- }
- if (!serviceMatched) {
- LOG.debug("Policy not applicable: policy serviceList does not match requested service") ;
- continue; // jump to next policy
- } else {
- LOG.debug("Policy serviceList matches requested service");
- }
- auditEnabled = true;;
- break; // break out of policyList check
- }
- return auditEnabled;
- }
-
- public PolicyContainer getPolicyContainer() {
- return policyContainer;
- }
-
-
- synchronized void setPolicyContainer(PolicyContainer aPolicyContainer) {
-
- for(Policy p : aPolicyContainer.getAcl()) {
- for(RolePermission rp : p.getPermissions()) {
- // lowercase accesType value stings
- List<String> rpaccess = rp.getAccess() ;
- if (rpaccess != null && rpaccess.size() > 0) {
- List<String> temp = new ArrayList<String>() ;
- for(String s : rpaccess) {
- temp.add(s.toLowerCase()) ;
- }
- rp.setAccess(temp);
- }
- }
- }
-
- this.policyContainer = aPolicyContainer ;
- this.cachedAuditFlag.clear();
- }
-
-
- private boolean ipMatches(String policyIp, String requestIp) {
- if (policyIp == null) {
- return false;
- }
- policyIp = policyIp.trim();
- if (policyIp.isEmpty()) {
- return false;
- }
- boolean ipMatched = false;
- boolean wildEnd = false;
- if (policyIp.contains(".")) {
- while (policyIp.endsWith(".*")) {
- wildEnd = true;
- policyIp = policyIp.substring(0, policyIp.lastIndexOf(".*"));
- }
- if (wildEnd) {
- policyIp = policyIp + ".";
- }
- } else if (policyIp.contains(":")) {
- while (policyIp.endsWith(":*")) {
- wildEnd = true;
- policyIp = policyIp.substring(0, policyIp.lastIndexOf(":*"));
- }
- if (wildEnd) {
- policyIp = policyIp + ":";
- }
- }
- if (wildEnd && requestIp.toLowerCase().startsWith(policyIp.toLowerCase())) {
- ipMatched = true;
- } else if (policyIp.equalsIgnoreCase(requestIp)) {
- ipMatched = true;
- }
- return ipMatched;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/knox/XASecureAuthorizer.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/knox/XASecureAuthorizer.java b/agents-impl/src/main/java/com/xasecure/pdp/knox/XASecureAuthorizer.java
deleted file mode 100644
index d3d2500..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/knox/XASecureAuthorizer.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/**
- * 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 com.xasecure.pdp.knox;
-
-import java.util.Set;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import com.xasecure.authorization.knox.KnoxAccessVerifier;
-
-public class XASecureAuthorizer implements KnoxAccessVerifier {
-
- private static final Log LOG = LogFactory.getLog(XASecureAuthorizer.class) ;
-
- private static URLBasedAuthDB authDB = URLBasedAuthDB.getInstance() ;
-
- public XASecureAuthorizer() {
- }
-
- @Override
- public boolean isAccessAllowed(String topologyName, String serviceName, String accessType,
- String userName, Set<String> groups, String requestIp) {
- boolean accessAllowed = authDB.isAccessGranted(topologyName, serviceName, accessType, userName, groups,
- requestIp);
- if (LOG.isDebugEnabled()) {
- LOG.debug("Computed access permission for topology: " + topologyName +
- ", service: " + serviceName +
- ", access: " + accessType +
- ", requestingIp: " +requestIp +
- ", requestingUser: " + userName +
- ", requestingUserGroups: " + groups +
- ", permitted: " + accessAllowed);
- }
- return accessAllowed;
- }
-
- @Override
- public boolean isAuditEnabled(String topologyName, String serviceName) {
- boolean auditEnabled = authDB.isAuditEnabled(topologyName, serviceName);
- if (LOG.isDebugEnabled()) {
- LOG.debug("Computed audit enabled for topology: " + topologyName +
- ", service: " + serviceName +
- ", auditLogEnabled: " + auditEnabled);
- }
- return auditEnabled;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/knox/deploy/XASecurePDPKnoxDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/knox/deploy/XASecurePDPKnoxDeploymentContributor.java b/agents-impl/src/main/java/com/xasecure/pdp/knox/deploy/XASecurePDPKnoxDeploymentContributor.java
deleted file mode 100644
index c851a11..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/knox/deploy/XASecurePDPKnoxDeploymentContributor.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/**
- * 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 com.xasecure.pdp.knox.deploy;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributorBase;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Service;
-
-public class XASecurePDPKnoxDeploymentContributor extends ProviderDeploymentContributorBase {
-
- private static final String FILTER_CLASSNAME = "com.xasecure.pdp.knox.filter.XASecurePDPKnoxFilter";
-
- @Override
- public String getRole() {
- return "authorization";
- }
-
- @Override
- public String getName() {
- return "XASecurePDPKnox";
- }
-
- @Override
- public void initializeContribution(DeploymentContext context) {
- super.initializeContribution(context);
- }
-
- @Override
- public void contributeProvider( DeploymentContext context, Provider provider ) {
- }
-
- @Override
- public void contributeFilter( DeploymentContext context, Provider provider, Service service,
- ResourceDescriptor resource, List<FilterParamDescriptor> params ) {
- if (params == null) {
- params = new ArrayList<FilterParamDescriptor>();
- }
- // add resource role to params so that we can determine the acls to enforce at runtime
- params.add( resource.createFilterParam().name( "resource.role" ).value(resource.role() ) );
-
- // blindly add all the provider params as filter init params
- // this will include any {resource.role}-ACLS parameters to be enforced - such as NAMENODE-ACLS
- Map<String, String> providerParams = provider.getParams();
- for(Entry<String, String> entry : providerParams.entrySet()) {
- params.add( resource.createFilterParam().name( entry.getKey().toLowerCase() ).value( entry.getValue() ) );
- }
-
- resource.addFilter().name( getName() ).role( getRole() ).impl( FILTER_CLASSNAME ).params( params );
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/knox/filter/XASecurePDPKnoxFilter.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/knox/filter/XASecurePDPKnoxFilter.java b/agents-impl/src/main/java/com/xasecure/pdp/knox/filter/XASecurePDPKnoxFilter.java
deleted file mode 100644
index dfa68b5..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/knox/filter/XASecurePDPKnoxFilter.java
+++ /dev/null
@@ -1,215 +0,0 @@
-/**
- * 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 com.xasecure.pdp.knox.filter;
-
-import java.io.IOException;
-import java.security.AccessController;
-import java.security.Principal;
-import java.util.HashSet;
-import java.util.Set;
-
-import javax.security.auth.Subject;
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.gateway.filter.AbstractGatewayFilter;
-import org.apache.hadoop.gateway.security.GroupPrincipal;
-import org.apache.hadoop.gateway.security.ImpersonatedPrincipal;
-import org.apache.hadoop.gateway.security.PrimaryPrincipal;
-
-import com.xasecure.audit.model.EnumRepositoryType;
-import com.xasecure.audit.model.KnoxAuditEvent;
-import com.xasecure.audit.provider.AuditProvider;
-import com.xasecure.audit.provider.AuditProviderFactory;
-import com.xasecure.authorization.hadoop.config.XaSecureConfiguration;
-import com.xasecure.authorization.hadoop.constants.XaSecureHadoopConstants;
-import com.xasecure.authorization.knox.KnoxAccessVerifier;
-import com.xasecure.authorization.knox.KnoxAccessVerifierFactory;
-import com.xasecure.authorization.utils.StringUtil;
-
-public class XASecurePDPKnoxFilter implements Filter {
-
- private static final Log LOG = LogFactory.getLog(XASecurePDPKnoxFilter.class);
- private static final String ACL_ENFORCER = "xasecure-acl";
- private static final String PERM_ALLOW = "allow";
- private String resourceRole = null;
- private KnoxAccessVerifier knoxAccessVerifier;
-
-
- AuditProvider auditProvider = AuditProviderFactory.getAuditProvider();
- private final String REPOSITORY_NAME = XaSecureConfiguration.getInstance().get(XaSecureHadoopConstants.AUDITLOG_REPOSITORY_NAME_PROP);
-
- static {
- XaSecureConfiguration.getInstance().initAudit(AuditProviderFactory.ApplicationType.Knox);
- }
-
- @Override
- public void init(FilterConfig filterConfig) throws ServletException {
- resourceRole = getInitParameter(filterConfig, "resource.role");
- knoxAccessVerifier = KnoxAccessVerifierFactory.getInstance();
- }
-
- private String getInitParameter(FilterConfig filterConfig, String paramName) {
- return filterConfig.getInitParameter(paramName.toLowerCase());
- }
-
- public void destroy() {
- }
-
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
-
- String sourceUrl = (String) request
- .getAttribute(AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME);
- String topologyName = getTopologyName(sourceUrl);
- String serviceName = getServiceName();
-
- Subject subject = Subject.getSubject(AccessController.getContext());
-
- Principal primaryPrincipal = (Principal) subject.getPrincipals(
- PrimaryPrincipal.class).toArray()[0];
- String primaryUser = primaryPrincipal.getName();
-
- String impersonatedUser = null;
- Object[] impersonations = subject.getPrincipals(
- ImpersonatedPrincipal.class).toArray();
- if (impersonations != null && impersonations.length > 0) {
- impersonatedUser = ((Principal) impersonations[0]).getName();
- }
-
- String user = (impersonatedUser != null) ? impersonatedUser
- : primaryUser;
- if (LOG.isDebugEnabled()) {
- LOG.debug("Checking access primaryUser: " + primaryUser + ", impersonatedUser: "
- + impersonatedUser + ", effectiveUser: " + user);
- }
-
- Object[] groupObjects = subject.getPrincipals(GroupPrincipal.class)
- .toArray();
- Set<String> groups = new HashSet<String>();
- for (Object obj : groupObjects) {
- groups.add(((Principal) obj).getName());
- }
-
- String clientIp = request.getRemoteAddr();
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Checking access primaryUser: " + primaryUser + ", impersonatedUser: "
- + impersonatedUser + ", effectiveUser: " + user +
- ", groups: " + groups + ", clientIp: " + clientIp);
- }
- boolean accessAllowed = knoxAccessVerifier.isAccessAllowed(
- topologyName, serviceName, PERM_ALLOW, user, groups, clientIp);
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Access allowed: " + accessAllowed);
- }
- if (accessAllowed) {
- chain.doFilter(request, response);
- if (knoxAccessVerifier.isAuditEnabled(topologyName, serviceName)) {
- LOG.debug("Audit is enabled");
- logAuditEvent(user, clientIp, topologyName, serviceName,
- "allow", true);
- } else {
- LOG.debug("Audit is not enabled");
- }
- } else {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Access is denied");
- }
- if (knoxAccessVerifier.isAuditEnabled(topologyName, serviceName)) {
- LOG.debug("Audit is enabled");
- logAuditEvent(user, clientIp, topologyName, serviceName,
- "allow", false);
- } else {
- LOG.debug("Audit is not enabled");
- }
- sendForbidden((HttpServletResponse) response);
- }
- }
-
- private void sendForbidden(HttpServletResponse res) {
- sendErrorCode(res, 403);
- }
-
- private void sendErrorCode(HttpServletResponse res, int code) {
- try {
- res.sendError(code);
- } catch (IOException e) {
- LOG.error("Error while redireting:", e);
- }
- }
-
- private String getTopologyName(String requestUrl) {
- if (requestUrl == null) {
- return null;
- }
- String url = requestUrl.trim();
- String[] tokens = url.split("/");
- if (tokens.length > 2) {
- return tokens[2];
- } else {
- return null;
- }
- }
-
- private String getServiceName() {
- return resourceRole;
- }
-
- private void logAuditEvent(String userName, String clientIp,
- String topology, String service,
- String accessType, boolean accessGranted) {
-
- KnoxAuditEvent auditEvent = new KnoxAuditEvent();
-
- auditEvent.setUser(userName == null ?
- XaSecureHadoopConstants.AUDITLOG_EMPTY_STRING : userName);
- auditEvent.setResourcePath("/" + topology + "/" + service);
- auditEvent.setResourceType("service");
- auditEvent.setAccessType(accessType);
- auditEvent.setClientIP(clientIp);
- auditEvent.setEventTime(StringUtil.getUTCDate());
- auditEvent.setAccessResult((short) (accessGranted ? 1 : 0));
- auditEvent.setResultReason(null);
- auditEvent.setRepositoryType(EnumRepositoryType.KNOX);
- auditEvent.setRepositoryName(REPOSITORY_NAME);
- auditEvent.setAclEnforcer(ACL_ENFORCER);
-
- try {
- LOG.debug("logEvent [" + auditEvent + "] - START");
-
- AuditProvider ap = AuditProviderFactory.getAuditProvider();
- ap.log(auditEvent);
-
- LOG.debug("logEvent [" + auditEvent + "] - END");
- } catch (Throwable t) {
- LOG.error("ERROR logEvent [" + auditEvent + "]", t);
- }
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/model/Policy.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/model/Policy.java b/agents-impl/src/main/java/com/xasecure/pdp/model/Policy.java
deleted file mode 100644
index a2bace7..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/model/Policy.java
+++ /dev/null
@@ -1,325 +0,0 @@
-/*
- * 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 com.xasecure.pdp.model;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.google.gson.annotations.SerializedName;
-import com.xasecure.pdp.config.gson.ExcludeSerialization;
-
-public class Policy {
-
- public static final String RESOURCE_SPLITER = "," ;
- public static final String POLICY_ENABLED_STATUS = "Enabled" ;
- public static final String SELECTION_TYPE_INCLUSIVE = "Inclusion" ;
- public static final String SELECTION_TYPE_EXCLUSIVE = "Exclusion" ;
-
- //
- // Only for HDFS policies
- //
- private String resource ;
- @SerializedName("isRecursive")
- private int recursiveInd;
-
- // Only for Knox Policies
- //
-
- @SerializedName("topology_name")
- private String topologies ;
-
- @SerializedName("service_name")
- private String services ;
-
-
- //
- // Only for Hive Policies
- //
-
- @SerializedName("database_name")
- private String databases ;
-
- @SerializedName("table_name")
- private String tables ;
-
- @SerializedName("udf_name")
- private String udfs ;
-
- @SerializedName("column_name")
- private String columns ;
-
- @SerializedName("column_families")
- private String columnfamilies ;
-
- //
- // Neede for all Policies
- //
- @SerializedName("permission")
- private List<RolePermission> permissions ;
-
- @SerializedName("audit")
- private int auditInd ;
-
- @SerializedName("encrypt")
- private int encryptInd ;
-
- @SerializedName("policyStatus")
- private String policyStatus;
-
- @SerializedName("tablePolicyType")
- private String tableSelectionType ;
-
- @SerializedName("columnPolicyType")
- private String columnSelectionType ;
-
- // Derived fields for PolicyAnalysis
- @ExcludeSerialization
- private List<ResourcePath> resourceList ;
- @ExcludeSerialization
- private List<String> databaseList ;
- @ExcludeSerialization
- private List<String> tableList ;
- @ExcludeSerialization
- private List<String> udfList ;
- @ExcludeSerialization
- private List<String> columnList ;
- @ExcludeSerialization
- private List<String> columnFamilyList ;
- @ExcludeSerialization
- private List<String> topologyList ;
- @ExcludeSerialization
- private List<String> serviceList ;
-
- public Policy() {
- permissions = new ArrayList<RolePermission>() ;
- }
-
-
- public String getResource() {
- return resource;
- }
-
- public void setResource(String resource) {
- this.resource = resource;
- }
-
- public String getDatabases() {
- return databases;
- }
-
- public void setDatabases(String databases) {
- this.databases = databases;
- }
-
- public String getTables() {
- return tables;
- }
-
- public void setTables(String tables) {
- this.tables = tables;
- }
-
- public String gettopologies() {
- return topologies;
- }
-
- public void setTopologies(String topologies) {
- this.topologies = topologies;
- }
-
- public String getServices() {
- return services;
- }
-
- public void setServices(String services) {
- this.services = services;
- }
- public String getUdfs() {
- return udfs;
- }
-
- public void setUdfs(String udfs) {
- this.udfs = udfs;
- }
-
-
- public String getColumns() {
- return columns;
- }
- public void setColumns(String columns) {
- this.columns = columns;
- }
- public String getColumnfamilies() {
- return columnfamilies;
- }
- public void setColumnfamilies(String columnfamilies) {
- this.columnfamilies = columnfamilies;
- }
-
- public List<RolePermission> getPermissions() {
- return permissions;
- }
- public void setPermissions(List<RolePermission> permissions) {
- this.permissions = permissions;
- }
-
- public int getRecursiveInd() {
- return recursiveInd;
- }
- public void setRecursiveInd(int recursiveInd) {
- this.recursiveInd = recursiveInd;
- }
-
- public int getAuditInd() {
- return auditInd;
- }
-
-
- public void setAuditInd(int auditInd) {
- this.auditInd = auditInd;
- }
-
-
- public int getEncryptInd() {
- return encryptInd;
- }
-
-
- public void setEncryptInd(int encryptInd) {
- this.encryptInd = encryptInd;
- }
-
- public String getPolicyStatus() {
- return policyStatus;
- }
-
-
- public void setPolicyStatus(String policyStatus) {
- this.policyStatus = policyStatus;
- }
-
- public String getTableSelectionType() {
- return tableSelectionType;
- }
-
-
- public void setTableSelectionType(String tableSelectionType) {
- this.tableSelectionType = tableSelectionType;
- }
-
-
- public String getColumnSelectionType() {
- return columnSelectionType;
- }
-
-
- public void setColumnSelectionType(String columnSelectionType) {
- this.columnSelectionType = columnSelectionType;
- }
-
- public boolean isTableSelectionExcluded() {
- return (this.tableSelectionType != null && SELECTION_TYPE_EXCLUSIVE.equalsIgnoreCase(this.tableSelectionType)) ;
- }
-
- public boolean isColumnSelectionExcluded() {
- return (this.columnSelectionType != null && SELECTION_TYPE_EXCLUSIVE.equalsIgnoreCase(this.columnSelectionType)) ;
- }
-
-
- // An older version of policy manager would show policyStatus as NULL (considered that as Enabled)
- public boolean isEnabled() {
- return (this.policyStatus == null || POLICY_ENABLED_STATUS.equalsIgnoreCase(this.policyStatus)) ;
- }
-
- public List<ResourcePath> getResourceList() {
- if (this.resourceList == null) {
- this.resourceList = getResourceList(resource) ;
- }
- return this.resourceList;
- }
- public List<String> getDatabaseList() {
- if (this.databaseList == null) {
- this.databaseList = getList(this.databases) ;
- }
- return this.databaseList;
- }
- public List<String> getTableList() {
- if (this.tableList == null) {
- this.tableList = getList(this.tables) ;
- }
- return this.tableList;
- }
- public List<String> getColumnList() {
- if (this.columnList == null) {
- this.columnList = getList(this.columns) ;
- }
- return this.columnList;
- }
- public List<String> getColumnFamilyList() {
- if (this.columnFamilyList == null) {
- this.columnFamilyList = getList(this.columnfamilies) ;
- }
- return this.columnFamilyList;
- }
- public List<String> getUDFList() {
- if (this.udfList == null && this.udfList != null) {
- this.udfList = getList(this.udfs) ;
- }
- return this.udfList;
- }
-
- public List<String> getTopologyList() {
- if (this.topologyList == null) {
- this.topologyList = getList(this.topologies) ;
- }
- return this.topologyList;
- }
-
- public List<String> getServiceList() {
- if (this.serviceList == null) {
- this.serviceList = getList(this.services) ;
- }
- return this.serviceList;
- }
-
-
- private List<String> getList(String resource) {
- List<String> ret = new ArrayList<String>() ;
- if (resource == null || resource.trim().isEmpty()) {
- resource = "*" ;
- }
- for(String r : resource.split(RESOURCE_SPLITER)) {
- ret.add(r) ;
- }
-
- return ret;
- }
-
- private List<ResourcePath> getResourceList(String resource) {
- List<ResourcePath> ret = new ArrayList<ResourcePath>() ;
- if (resource != null && ! resource.isEmpty()) {
- for(String path : resource.split(RESOURCE_SPLITER)) {
- ret.add(new ResourcePath(path)) ;
- }
- }
- return ret ;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/model/PolicyContainer.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/model/PolicyContainer.java b/agents-impl/src/main/java/com/xasecure/pdp/model/PolicyContainer.java
deleted file mode 100644
index 1675d34..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/model/PolicyContainer.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * 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 com.xasecure.pdp.model;
-
-import java.util.List;
-
-import com.google.gson.annotations.SerializedName;
-
-public class PolicyContainer {
-
- @SerializedName("repository_name")
- private String repositoryName ;
-
- @SerializedName("last_updated")
- private long lastUpdatedTimeInEpoc ;
-
- @SerializedName("acl")
- private List<Policy> acl;
-
- public String getRepositoryName() {
- return repositoryName;
- }
- public void setRepositoryName(String repositoryName) {
- this.repositoryName = repositoryName;
- }
- public long getLastUpdatedTimeInEpoc() {
- return lastUpdatedTimeInEpoc;
- }
- public void setLastUpdatedTimeInEpoc(long lastUpdatedTimeInEpoc) {
- this.lastUpdatedTimeInEpoc = lastUpdatedTimeInEpoc;
- }
- public List<Policy> getAcl() {
- return acl;
- }
- public void setAcl(List<Policy> acl) {
- this.acl = acl;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/model/ResourcePath.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/model/ResourcePath.java b/agents-impl/src/main/java/com/xasecure/pdp/model/ResourcePath.java
deleted file mode 100644
index ff6a754..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/model/ResourcePath.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * 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 com.xasecure.pdp.model;
-
-public class ResourcePath {
-
- String path ;
- boolean wildcardPath ;
-
- public ResourcePath(String path) {
- this.path = path ;
- if (this.path.contains("*") || this.path.contains("?")) {
- this.wildcardPath = true ;
- }
- }
-
- public String getPath() {
- return path;
- }
-
- public boolean isWildcardPath() {
- return wildcardPath;
- }
-
-
-}
[04/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/XACommonEnums.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/XACommonEnums.java b/security-admin/src/main/java/org/apache/ranger/common/XACommonEnums.java
new file mode 100644
index 0000000..bc5d809
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/XACommonEnums.java
@@ -0,0 +1,1444 @@
+/*
+ * 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.*;
+
+import org.apache.ranger.common.*;
+
+public class XACommonEnums {
+
+ /***************************************************************
+ * Enum values for ActiveStatus
+ **************************************************************/
+ /**
+ * STATUS_DISABLED is an element of enum ActiveStatus. Its value is "STATUS_DISABLED".
+ */
+ public static final int STATUS_DISABLED = 0;
+ /**
+ * STATUS_ENABLED is an element of enum ActiveStatus. Its value is "STATUS_ENABLED".
+ */
+ public static final int STATUS_ENABLED = 1;
+ /**
+ * STATUS_DELETED is an element of enum ActiveStatus. Its value is "STATUS_DELETED".
+ */
+ public static final int STATUS_DELETED = 2;
+
+ /**
+ * Max value for enum ActiveStatus_MAX
+ */
+ public static final int ActiveStatus_MAX = 2;
+
+
+ /***************************************************************
+ * Enum values for ActivationStatus
+ **************************************************************/
+ /**
+ * ACT_STATUS_DISABLED is an element of enum ActivationStatus. Its value is "ACT_STATUS_DISABLED".
+ */
+ public static final int ACT_STATUS_DISABLED = 0;
+ /**
+ * ACT_STATUS_ACTIVE is an element of enum ActivationStatus. Its value is "ACT_STATUS_ACTIVE".
+ */
+ public static final int ACT_STATUS_ACTIVE = 1;
+ /**
+ * ACT_STATUS_PENDING_APPROVAL is an element of enum ActivationStatus. Its value is "ACT_STATUS_PENDING_APPROVAL".
+ */
+ public static final int ACT_STATUS_PENDING_APPROVAL = 2;
+ /**
+ * ACT_STATUS_PENDING_ACTIVATION is an element of enum ActivationStatus. Its value is "ACT_STATUS_PENDING_ACTIVATION".
+ */
+ public static final int ACT_STATUS_PENDING_ACTIVATION = 3;
+ /**
+ * ACT_STATUS_REJECTED is an element of enum ActivationStatus. Its value is "ACT_STATUS_REJECTED".
+ */
+ public static final int ACT_STATUS_REJECTED = 4;
+ /**
+ * ACT_STATUS_DEACTIVATED is an element of enum ActivationStatus. Its value is "ACT_STATUS_DEACTIVATED".
+ */
+ public static final int ACT_STATUS_DEACTIVATED = 5;
+ /**
+ * ACT_STATUS_PRE_REGISTRATION is an element of enum ActivationStatus. Its value is "ACT_STATUS_PRE_REGISTRATION".
+ */
+ public static final int ACT_STATUS_PRE_REGISTRATION = 6;
+ /**
+ * ACT_STATUS_NO_LOGIN is an element of enum ActivationStatus. Its value is "ACT_STATUS_NO_LOGIN".
+ */
+ public static final int ACT_STATUS_NO_LOGIN = 7;
+
+ /**
+ * Max value for enum ActivationStatus_MAX
+ */
+ public static final int ActivationStatus_MAX = 7;
+
+
+ /***************************************************************
+ * Enum values for BooleanValue
+ **************************************************************/
+ /**
+ * BOOL_NONE is an element of enum BooleanValue. Its value is "BOOL_NONE".
+ */
+ public static final int BOOL_NONE = 0;
+ /**
+ * BOOL_TRUE is an element of enum BooleanValue. Its value is "BOOL_TRUE".
+ */
+ public static final int BOOL_TRUE = 1;
+ /**
+ * BOOL_FALSE is an element of enum BooleanValue. Its value is "BOOL_FALSE".
+ */
+ public static final int BOOL_FALSE = 2;
+
+ /**
+ * Max value for enum BooleanValue_MAX
+ */
+ public static final int BooleanValue_MAX = 2;
+
+
+ /***************************************************************
+ * Enum values for DataType
+ **************************************************************/
+ /**
+ * DATA_TYPE_UNKNOWN is an element of enum DataType. Its value is "DATA_TYPE_UNKNOWN".
+ */
+ public static final int DATA_TYPE_UNKNOWN = 0;
+ /**
+ * DATA_TYPE_INTEGER is an element of enum DataType. Its value is "DATA_TYPE_INTEGER".
+ */
+ public static final int DATA_TYPE_INTEGER = 1;
+ /**
+ * DATA_TYPE_DOUBLE is an element of enum DataType. Its value is "DATA_TYPE_DOUBLE".
+ */
+ public static final int DATA_TYPE_DOUBLE = 2;
+ /**
+ * DATA_TYPE_STRING is an element of enum DataType. Its value is "DATA_TYPE_STRING".
+ */
+ public static final int DATA_TYPE_STRING = 3;
+ /**
+ * DATA_TYPE_BOOLEAN is an element of enum DataType. Its value is "DATA_TYPE_BOOLEAN".
+ */
+ public static final int DATA_TYPE_BOOLEAN = 4;
+ /**
+ * DATA_TYPE_DATE is an element of enum DataType. Its value is "DATA_TYPE_DATE".
+ */
+ public static final int DATA_TYPE_DATE = 5;
+ /**
+ * DATA_TYPE_STRING_ENUM is an element of enum DataType. Its value is "DATA_TYPE_STRING_ENUM".
+ */
+ public static final int DATA_TYPE_STRING_ENUM = 6;
+ /**
+ * DATA_TYPE_LONG is an element of enum DataType. Its value is "DATA_TYPE_LONG".
+ */
+ public static final int DATA_TYPE_LONG = 7;
+ /**
+ * DATA_TYPE_INTEGER_ENUM is an element of enum DataType. Its value is "DATA_TYPE_INTEGER_ENUM".
+ */
+ public static final int DATA_TYPE_INTEGER_ENUM = 8;
+
+ /**
+ * Max value for enum DataType_MAX
+ */
+ public static final int DataType_MAX = 8;
+
+
+ /***************************************************************
+ * Enum values for DeviceType
+ **************************************************************/
+ /**
+ * DEVICE_UNKNOWN is an element of enum DeviceType. Its value is "DEVICE_UNKNOWN".
+ */
+ public static final int DEVICE_UNKNOWN = 0;
+ /**
+ * DEVICE_BROWSER is an element of enum DeviceType. Its value is "DEVICE_BROWSER".
+ */
+ public static final int DEVICE_BROWSER = 1;
+ /**
+ * DEVICE_IPHONE is an element of enum DeviceType. Its value is "DEVICE_IPHONE".
+ */
+ public static final int DEVICE_IPHONE = 2;
+ /**
+ * DEVICE_IPAD is an element of enum DeviceType. Its value is "DEVICE_IPAD".
+ */
+ public static final int DEVICE_IPAD = 3;
+ /**
+ * DEVICE_IPOD is an element of enum DeviceType. Its value is "DEVICE_IPOD".
+ */
+ public static final int DEVICE_IPOD = 4;
+ /**
+ * DEVICE_ANDROID is an element of enum DeviceType. Its value is "DEVICE_ANDROID".
+ */
+ public static final int DEVICE_ANDROID = 5;
+
+ /**
+ * Max value for enum DeviceType_MAX
+ */
+ public static final int DeviceType_MAX = 5;
+
+
+ /***************************************************************
+ * Enum values for DiffLevel
+ **************************************************************/
+ /**
+ * DIFF_UNKNOWN is an element of enum DiffLevel. Its value is "DIFF_UNKNOWN".
+ */
+ public static final int DIFF_UNKNOWN = 0;
+ /**
+ * DIFF_LOW is an element of enum DiffLevel. Its value is "DIFF_LOW".
+ */
+ public static final int DIFF_LOW = 1;
+ /**
+ * DIFF_MEDIUM is an element of enum DiffLevel. Its value is "DIFF_MEDIUM".
+ */
+ public static final int DIFF_MEDIUM = 2;
+ /**
+ * DIFF_HIGH is an element of enum DiffLevel. Its value is "DIFF_HIGH".
+ */
+ public static final int DIFF_HIGH = 3;
+
+ /**
+ * Max value for enum DiffLevel_MAX
+ */
+ public static final int DiffLevel_MAX = 3;
+
+
+ /***************************************************************
+ * Enum values for FileType
+ **************************************************************/
+ /**
+ * FILE_FILE is an element of enum FileType. Its value is "FILE_FILE".
+ */
+ public static final int FILE_FILE = 0;
+ /**
+ * FILE_DIR is an element of enum FileType. Its value is "FILE_DIR".
+ */
+ public static final int FILE_DIR = 1;
+
+ /**
+ * Max value for enum FileType_MAX
+ */
+ public static final int FileType_MAX = 1;
+
+
+ /***************************************************************
+ * Enum values for FreqType
+ **************************************************************/
+ /**
+ * FREQ_NONE is an element of enum FreqType. Its value is "FREQ_NONE".
+ */
+ public static final int FREQ_NONE = 0;
+ /**
+ * FREQ_MANUAL is an element of enum FreqType. Its value is "FREQ_MANUAL".
+ */
+ public static final int FREQ_MANUAL = 1;
+ /**
+ * FREQ_HOURLY is an element of enum FreqType. Its value is "FREQ_HOURLY".
+ */
+ public static final int FREQ_HOURLY = 2;
+ /**
+ * FREQ_DAILY is an element of enum FreqType. Its value is "FREQ_DAILY".
+ */
+ public static final int FREQ_DAILY = 3;
+ /**
+ * FREQ_WEEKLY is an element of enum FreqType. Its value is "FREQ_WEEKLY".
+ */
+ public static final int FREQ_WEEKLY = 4;
+ /**
+ * FREQ_BI_WEEKLY is an element of enum FreqType. Its value is "FREQ_BI_WEEKLY".
+ */
+ public static final int FREQ_BI_WEEKLY = 5;
+ /**
+ * FREQ_MONTHLY is an element of enum FreqType. Its value is "FREQ_MONTHLY".
+ */
+ public static final int FREQ_MONTHLY = 6;
+
+ /**
+ * Max value for enum FreqType_MAX
+ */
+ public static final int FreqType_MAX = 6;
+
+
+ /***************************************************************
+ * Enum values for MimeType
+ **************************************************************/
+ /**
+ * MIME_UNKNOWN is an element of enum MimeType. Its value is "MIME_UNKNOWN".
+ */
+ public static final int MIME_UNKNOWN = 0;
+ /**
+ * MIME_TEXT is an element of enum MimeType. Its value is "MIME_TEXT".
+ */
+ public static final int MIME_TEXT = 1;
+ /**
+ * MIME_HTML is an element of enum MimeType. Its value is "MIME_HTML".
+ */
+ public static final int MIME_HTML = 2;
+ /**
+ * MIME_PNG is an element of enum MimeType. Its value is "MIME_PNG".
+ */
+ public static final int MIME_PNG = 3;
+ /**
+ * MIME_JPEG is an element of enum MimeType. Its value is "MIME_JPEG".
+ */
+ public static final int MIME_JPEG = 4;
+
+ /**
+ * Max value for enum MimeType_MAX
+ */
+ public static final int MimeType_MAX = 4;
+
+
+ /***************************************************************
+ * Enum values for NumberFormat
+ **************************************************************/
+ /**
+ * NUM_FORMAT_NONE is an element of enum NumberFormat. Its value is "NUM_FORMAT_NONE".
+ */
+ public static final int NUM_FORMAT_NONE = 0;
+ /**
+ * NUM_FORMAT_NUMERIC is an element of enum NumberFormat. Its value is "NUM_FORMAT_NUMERIC".
+ */
+ public static final int NUM_FORMAT_NUMERIC = 1;
+ /**
+ * NUM_FORMAT_ALPHA is an element of enum NumberFormat. Its value is "NUM_FORMAT_ALPHA".
+ */
+ public static final int NUM_FORMAT_ALPHA = 2;
+ /**
+ * NUM_FORMAT_ROMAN is an element of enum NumberFormat. Its value is "NUM_FORMAT_ROMAN".
+ */
+ public static final int NUM_FORMAT_ROMAN = 3;
+
+ /**
+ * Max value for enum NumberFormat_MAX
+ */
+ public static final int NumberFormat_MAX = 3;
+
+
+ /***************************************************************
+ * Enum values for ObjectStatus
+ **************************************************************/
+ /**
+ * OBJ_STATUS_ACTIVE is an element of enum ObjectStatus. Its value is "OBJ_STATUS_ACTIVE".
+ */
+ public static final int OBJ_STATUS_ACTIVE = 0;
+ /**
+ * OBJ_STATUS_DELETED is an element of enum ObjectStatus. Its value is "OBJ_STATUS_DELETED".
+ */
+ public static final int OBJ_STATUS_DELETED = 1;
+ /**
+ * OBJ_STATUS_ARCHIVED is an element of enum ObjectStatus. Its value is "OBJ_STATUS_ARCHIVED".
+ */
+ public static final int OBJ_STATUS_ARCHIVED = 2;
+
+ /**
+ * Max value for enum ObjectStatus_MAX
+ */
+ public static final int ObjectStatus_MAX = 2;
+
+
+ /***************************************************************
+ * Enum values for PasswordResetStatus
+ **************************************************************/
+ /**
+ * PWD_RESET_ACTIVE is an element of enum PasswordResetStatus. Its value is "PWD_RESET_ACTIVE".
+ */
+ public static final int PWD_RESET_ACTIVE = 0;
+ /**
+ * PWD_RESET_USED is an element of enum PasswordResetStatus. Its value is "PWD_RESET_USED".
+ */
+ public static final int PWD_RESET_USED = 1;
+ /**
+ * PWD_RESET_EXPIRED is an element of enum PasswordResetStatus. Its value is "PWD_RESET_EXPIRED".
+ */
+ public static final int PWD_RESET_EXPIRED = 2;
+ /**
+ * PWD_RESET_DISABLED is an element of enum PasswordResetStatus. Its value is "PWD_RESET_DISABLED".
+ */
+ public static final int PWD_RESET_DISABLED = 3;
+
+ /**
+ * Max value for enum PasswordResetStatus_MAX
+ */
+ public static final int PasswordResetStatus_MAX = 3;
+
+
+ /***************************************************************
+ * Enum values for PriorityType
+ **************************************************************/
+ /**
+ * PRIORITY_NORMAL is an element of enum PriorityType. Its value is "PRIORITY_NORMAL".
+ */
+ public static final int PRIORITY_NORMAL = 0;
+ /**
+ * PRIORITY_LOW is an element of enum PriorityType. Its value is "PRIORITY_LOW".
+ */
+ public static final int PRIORITY_LOW = 1;
+ /**
+ * PRIORITY_MEDIUM is an element of enum PriorityType. Its value is "PRIORITY_MEDIUM".
+ */
+ public static final int PRIORITY_MEDIUM = 2;
+ /**
+ * PRIORITY_HIGH is an element of enum PriorityType. Its value is "PRIORITY_HIGH".
+ */
+ public static final int PRIORITY_HIGH = 3;
+
+ /**
+ * Max value for enum PriorityType_MAX
+ */
+ public static final int PriorityType_MAX = 3;
+
+
+ /***************************************************************
+ * Enum values for ProgressStatus
+ **************************************************************/
+ /**
+ * PROGRESS_PENDING is an element of enum ProgressStatus. Its value is "PROGRESS_PENDING".
+ */
+ public static final int PROGRESS_PENDING = 0;
+ /**
+ * PROGRESS_IN_PROGRESS is an element of enum ProgressStatus. Its value is "PROGRESS_IN_PROGRESS".
+ */
+ public static final int PROGRESS_IN_PROGRESS = 1;
+ /**
+ * PROGRESS_COMPLETE is an element of enum ProgressStatus. Its value is "PROGRESS_COMPLETE".
+ */
+ public static final int PROGRESS_COMPLETE = 2;
+ /**
+ * PROGRESS_ABORTED is an element of enum ProgressStatus. Its value is "PROGRESS_ABORTED".
+ */
+ public static final int PROGRESS_ABORTED = 3;
+ /**
+ * PROGRESS_FAILED is an element of enum ProgressStatus. Its value is "PROGRESS_FAILED".
+ */
+ public static final int PROGRESS_FAILED = 4;
+
+ /**
+ * Max value for enum ProgressStatus_MAX
+ */
+ public static final int ProgressStatus_MAX = 4;
+
+
+ /***************************************************************
+ * Enum values for RelationType
+ **************************************************************/
+ /**
+ * REL_NONE is an element of enum RelationType. Its value is "REL_NONE".
+ */
+ public static final int REL_NONE = 0;
+ /**
+ * REL_SELF is an element of enum RelationType. Its value is "REL_SELF".
+ */
+ public static final int REL_SELF = 1;
+
+ /**
+ * Max value for enum RelationType_MAX
+ */
+ public static final int RelationType_MAX = 1;
+
+
+ /***************************************************************
+ * Enum values for UserSource
+ **************************************************************/
+ /**
+ * USER_APP is an element of enum UserSource. Its value is "USER_APP".
+ */
+ public static final int USER_APP = 0;
+ public static final int USER_EXTERNAL = 1;
+ public static final int USER_AD= 2;
+ public static final int USER_LDAP = 3;
+ public static final int USER_UNIX = 4;
+ public static final int USER_REPO = 5;
+
+ public static final int GROUP_INTERNAL = 0;
+ public static final int GROUP_EXTERNAL = 1;
+ public static final int GROUP_AD= 2;
+ public static final int GROUP_LDAP = 3;
+ public static final int GROUP_UNIX = 4;
+ public static final int GROUP_REPO = 5;
+ /**
+ * USER_GOOGLE is an element of enum UserSource. Its value is "USER_GOOGLE".
+ */
+ //public static final int USER_GOOGLE = 1;
+ /**
+ * USER_FB is an element of enum UserSource. Its value is "USER_FB".
+ */
+ //public static final int USER_FB = 2;
+
+ /**
+ * Max value for enum UserSource_MAX
+ */
+ public static final int UserSource_MAX = 5;
+
+
+ /***************************************************************
+ * Enum values for AssetType
+ **************************************************************/
+ /**
+ * ASSET_UNKNOWN is an element of enum AssetType. Its value is "ASSET_UNKNOWN".
+ */
+ public static final int ASSET_UNKNOWN = 0;
+ /**
+ * ASSET_HDFS is an element of enum AssetType. Its value is "ASSET_HDFS".
+ */
+ public static final int ASSET_HDFS = 1;
+ /**
+ * ASSET_HBASE is an element of enum AssetType. Its value is "ASSET_HBASE".
+ */
+ public static final int ASSET_HBASE = 2;
+ /**
+ * ASSET_HIVE is an element of enum AssetType. Its value is "ASSET_HIVE".
+ */
+ public static final int ASSET_HIVE = 3;
+ /**
+ * ASSET_HIVE is an element of enum AssetType. Its value is "ASSET_HIVE".
+ */
+ public static final int ASSET_AGENT = 4;
+ /**
+ * ASSET_HIVE is an element of enum AssetType. Its value is "ASSET_HIVE".
+ */
+ public static final int ASSET_KNOX = 5;
+ /**
+ * ASSET_HIVE is an element of enum AssetType. Its value is "ASSET_HIVE".
+ */
+ public static final int ASSET_STORM = 6;
+
+ /**
+ * Max value for enum AssetType_MAX
+ */
+ public static final int AssetType_MAX = 6;
+
+
+ /***************************************************************
+ * Enum values for AccessResult
+ **************************************************************/
+ /**
+ * ACCESS_RESULT_DENIED is an element of enum AccessResult. Its value is "ACCESS_RESULT_DENIED".
+ */
+ public static final int ACCESS_RESULT_DENIED = 0;
+ /**
+ * ACCESS_RESULT_ALLOWED is an element of enum AccessResult. Its value is "ACCESS_RESULT_ALLOWED".
+ */
+ public static final int ACCESS_RESULT_ALLOWED = 1;
+
+ /**
+ * Max value for enum AccessResult_MAX
+ */
+ public static final int AccessResult_MAX = 1;
+
+
+ /***************************************************************
+ * Enum values for PolicyType
+ **************************************************************/
+ /**
+ * POLICY_INCLUSION is an element of enum PolicyType. Its value is "POLICY_INCLUSION".
+ */
+ public static final int POLICY_INCLUSION = 0;
+ /**
+ * POLICY_EXCLUSION is an element of enum PolicyType. Its value is "POLICY_EXCLUSION".
+ */
+ public static final int POLICY_EXCLUSION = 1;
+
+ /**
+ * Max value for enum PolicyType_MAX
+ */
+ public static final int PolicyType_MAX = 1;
+
+
+ /***************************************************************
+ * Enum values for XAAuditType
+ **************************************************************/
+ /**
+ * XA_AUDIT_TYPE_UNKNOWN is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_UNKNOWN".
+ */
+ public static final int XA_AUDIT_TYPE_UNKNOWN = 0;
+ /**
+ * XA_AUDIT_TYPE_ALL is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_ALL".
+ */
+ public static final int XA_AUDIT_TYPE_ALL = 1;
+ /**
+ * XA_AUDIT_TYPE_READ is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_READ".
+ */
+ public static final int XA_AUDIT_TYPE_READ = 2;
+ /**
+ * XA_AUDIT_TYPE_WRITE is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_WRITE".
+ */
+ public static final int XA_AUDIT_TYPE_WRITE = 3;
+ /**
+ * XA_AUDIT_TYPE_CREATE is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_CREATE".
+ */
+ public static final int XA_AUDIT_TYPE_CREATE = 4;
+ /**
+ * XA_AUDIT_TYPE_DELETE is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_DELETE".
+ */
+ public static final int XA_AUDIT_TYPE_DELETE = 5;
+ /**
+ * XA_AUDIT_TYPE_LOGIN is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_LOGIN".
+ */
+ public static final int XA_AUDIT_TYPE_LOGIN = 6;
+
+ /**
+ * Max value for enum XAAuditType_MAX
+ */
+ public static final int XAAuditType_MAX = 6;
+
+
+ /***************************************************************
+ * Enum values for ResourceType
+ **************************************************************/
+ /**
+ * RESOURCE_UNKNOWN is an element of enum ResourceType. Its value is "RESOURCE_UNKNOWN".
+ */
+ public static final int RESOURCE_UNKNOWN = 0;
+ /**
+ * RESOURCE_PATH is an element of enum ResourceType. Its value is "RESOURCE_PATH".
+ */
+ public static final int RESOURCE_PATH = 1;
+ /**
+ * RESOURCE_DB is an element of enum ResourceType. Its value is "RESOURCE_DB".
+ */
+ public static final int RESOURCE_DB = 2;
+ /**
+ * RESOURCE_TABLE is an element of enum ResourceType. Its value is "RESOURCE_TABLE".
+ */
+ public static final int RESOURCE_TABLE = 3;
+ /**
+ * RESOURCE_COL_FAM is an element of enum ResourceType. Its value is "RESOURCE_COL_FAM".
+ */
+ public static final int RESOURCE_COL_FAM = 4;
+ /**
+ * RESOURCE_COLUMN is an element of enum ResourceType. Its value is "RESOURCE_COLUMN".
+ */
+ public static final int RESOURCE_COLUMN = 5;
+ /**
+ * RESOURCE_VIEW is an element of enum ResourceType. Its value is "RESOURCE_VIEW".
+ */
+ public static final int RESOURCE_VIEW = 6;
+ /**
+ * RESOURCE_UDF is an element of enum ResourceType. Its value is "RESOURCE_UDF".
+ */
+ public static final int RESOURCE_UDF = 7;
+ /**
+ * RESOURCE_VIEW_COL is an element of enum ResourceType. Its value is "RESOURCE_VIEW_COL".
+ */
+ public static final int RESOURCE_VIEW_COL = 8;
+
+ /**
+ * Max value for enum ResourceType_MAX
+ */
+ public static final int ResourceType_MAX = 8;
+
+
+ /***************************************************************
+ * Enum values for XAGroupType
+ **************************************************************/
+ /**
+ * XA_GROUP_UNKNOWN is an element of enum XAGroupType. Its value is "XA_GROUP_UNKNOWN".
+ */
+ public static final int XA_GROUP_UNKNOWN = 0;
+ /**
+ * XA_GROUP_USER is an element of enum XAGroupType. Its value is "XA_GROUP_USER".
+ */
+ public static final int XA_GROUP_USER = 1;
+ /**
+ * XA_GROUP_GROUP is an element of enum XAGroupType. Its value is "XA_GROUP_GROUP".
+ */
+ public static final int XA_GROUP_GROUP = 2;
+ /**
+ * XA_GROUP_ROLE is an element of enum XAGroupType. Its value is "XA_GROUP_ROLE".
+ */
+ public static final int XA_GROUP_ROLE = 3;
+
+ /**
+ * Max value for enum XAGroupType_MAX
+ */
+ public static final int XAGroupType_MAX = 3;
+
+
+ /***************************************************************
+ * Enum values for XAPermForType
+ **************************************************************/
+ /**
+ * XA_PERM_FOR_UNKNOWN is an element of enum XAPermForType. Its value is "XA_PERM_FOR_UNKNOWN".
+ */
+ public static final int XA_PERM_FOR_UNKNOWN = 0;
+ /**
+ * XA_PERM_FOR_USER is an element of enum XAPermForType. Its value is "XA_PERM_FOR_USER".
+ */
+ public static final int XA_PERM_FOR_USER = 1;
+ /**
+ * XA_PERM_FOR_GROUP is an element of enum XAPermForType. Its value is "XA_PERM_FOR_GROUP".
+ */
+ public static final int XA_PERM_FOR_GROUP = 2;
+
+ /**
+ * Max value for enum XAPermForType_MAX
+ */
+ public static final int XAPermForType_MAX = 2;
+
+
+ /***************************************************************
+ * Enum values for XAPermType
+ **************************************************************/
+ /**
+ * XA_PERM_TYPE_UNKNOWN is an element of enum XAPermType. Its value is "XA_PERM_TYPE_UNKNOWN".
+ */
+ public static final int XA_PERM_TYPE_UNKNOWN = 0;
+ /**
+ * XA_PERM_TYPE_RESET is an element of enum XAPermType. Its value is "XA_PERM_TYPE_RESET".
+ */
+ public static final int XA_PERM_TYPE_RESET = 1;
+ /**
+ * XA_PERM_TYPE_READ is an element of enum XAPermType. Its value is "XA_PERM_TYPE_READ".
+ */
+ public static final int XA_PERM_TYPE_READ = 2;
+ /**
+ * XA_PERM_TYPE_WRITE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_WRITE".
+ */
+ public static final int XA_PERM_TYPE_WRITE = 3;
+ /**
+ * XA_PERM_TYPE_CREATE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_CREATE".
+ */
+ public static final int XA_PERM_TYPE_CREATE = 4;
+ /**
+ * XA_PERM_TYPE_DELETE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_DELETE".
+ */
+ public static final int XA_PERM_TYPE_DELETE = 5;
+ /**
+ * XA_PERM_TYPE_ADMIN is an element of enum XAPermType. Its value is "XA_PERM_TYPE_ADMIN".
+ */
+ public static final int XA_PERM_TYPE_ADMIN = 6;
+ /**
+ * XA_PERM_TYPE_OBFUSCATE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_OBFUSCATE".
+ */
+ public static final int XA_PERM_TYPE_OBFUSCATE = 7;
+ /**
+ * XA_PERM_TYPE_MASK is an element of enum XAPermType. Its value is "XA_PERM_TYPE_MASK".
+ */
+ public static final int XA_PERM_TYPE_MASK = 8;
+ /**
+ * XA_PERM_TYPE_EXECUTE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_EXECUTE".
+ */
+ public static final int XA_PERM_TYPE_EXECUTE = 9;
+ /**
+ * XA_PERM_TYPE_SELECT is an element of enum XAPermType. Its value is "XA_PERM_TYPE_SELECT".
+ */
+ public static final int XA_PERM_TYPE_SELECT = 10;
+ /**
+ * XA_PERM_TYPE_UPDATE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_UPDATE".
+ */
+ public static final int XA_PERM_TYPE_UPDATE = 11;
+ /**
+ * XA_PERM_TYPE_DROP is an element of enum XAPermType. Its value is "XA_PERM_TYPE_DROP".
+ */
+ public static final int XA_PERM_TYPE_DROP = 12;
+ /**
+ * XA_PERM_TYPE_ALTER is an element of enum XAPermType. Its value is "XA_PERM_TYPE_ALTER".
+ */
+ public static final int XA_PERM_TYPE_ALTER = 13;
+ /**
+ * XA_PERM_TYPE_INDEX is an element of enum XAPermType. Its value is "XA_PERM_TYPE_INDEX".
+ */
+ public static final int XA_PERM_TYPE_INDEX = 14;
+ /**
+ * XA_PERM_TYPE_LOCK is an element of enum XAPermType. Its value is "XA_PERM_TYPE_LOCK".
+ */
+ public static final int XA_PERM_TYPE_LOCK = 15;
+ /**
+ * XA_PERM_TYPE_ALL is an element of enum XAPermType. Its value is "XA_PERM_TYPE_ALL".
+ */
+ public static final int XA_PERM_TYPE_ALL = 16;
+
+ /**
+ * XA_PERM_TYPE_ALL is an element of enum XAPermType. Its value is "XA_PERM_TYPE_ALLOW".
+ */
+ public static final int XA_PERM_TYPE_ALLOW = 17;
+
+ /**
+ * Max value for enum XAPermType_MAX
+ */
+ public static final int XAPermType_MAX = 17;
+
+
+ /***************************************************************
+ * Enum values for ClassTypes
+ **************************************************************/
+ /**
+ * CLASS_TYPE_NONE is an element of enum ClassTypes. Its value is "CLASS_TYPE_NONE".
+ */
+ public static final int CLASS_TYPE_NONE = 0;
+ /**
+ * CLASS_TYPE_MESSAGE is an element of enum ClassTypes. Its value is "CLASS_TYPE_MESSAGE".
+ */
+ public static final int CLASS_TYPE_MESSAGE = 1;
+ /**
+ * CLASS_TYPE_USER_PROFILE is an element of enum ClassTypes. Its value is "CLASS_TYPE_USER_PROFILE".
+ */
+ public static final int CLASS_TYPE_USER_PROFILE = 2;
+ /**
+ * CLASS_TYPE_AUTH_SESS is an element of enum ClassTypes. Its value is "CLASS_TYPE_AUTH_SESS".
+ */
+ public static final int CLASS_TYPE_AUTH_SESS = 3;
+ /**
+ * CLASS_TYPE_DATA_OBJECT is an element of enum ClassTypes. Its value is "CLASS_TYPE_DATA_OBJECT".
+ */
+ public static final int CLASS_TYPE_DATA_OBJECT = 4;
+ /**
+ * CLASS_TYPE_NAMEVALUE is an element of enum ClassTypes. Its value is "CLASS_TYPE_NAMEVALUE".
+ */
+ public static final int CLASS_TYPE_NAMEVALUE = 5;
+ /**
+ * CLASS_TYPE_LONG is an element of enum ClassTypes. Its value is "CLASS_TYPE_LONG".
+ */
+ public static final int CLASS_TYPE_LONG = 6;
+ /**
+ * CLASS_TYPE_PASSWORD_CHANGE is an element of enum ClassTypes. Its value is "CLASS_TYPE_PASSWORD_CHANGE".
+ */
+ public static final int CLASS_TYPE_PASSWORD_CHANGE = 7;
+ /**
+ * CLASS_TYPE_STRING is an element of enum ClassTypes. Its value is "CLASS_TYPE_STRING".
+ */
+ public static final int CLASS_TYPE_STRING = 8;
+ /**
+ * CLASS_TYPE_ENUM is an element of enum ClassTypes. Its value is "CLASS_TYPE_ENUM".
+ */
+ public static final int CLASS_TYPE_ENUM = 9;
+ /**
+ * CLASS_TYPE_ENUM_ELEMENT is an element of enum ClassTypes. Its value is "CLASS_TYPE_ENUM_ELEMENT".
+ */
+ public static final int CLASS_TYPE_ENUM_ELEMENT = 10;
+ /**
+ * CLASS_TYPE_RESPONSE is an element of enum ClassTypes. Its value is "CLASS_TYPE_RESPONSE".
+ */
+ public static final int CLASS_TYPE_RESPONSE = 11;
+ /**
+ * CLASS_TYPE_XA_ASSET is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_ASSET".
+ */
+ public static final int CLASS_TYPE_XA_ASSET = 1000;
+ /**
+ * CLASS_TYPE_XA_RESOURCE is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_RESOURCE".
+ */
+ public static final int CLASS_TYPE_XA_RESOURCE = 1001;
+ /**
+ * CLASS_TYPE_XA_GROUP is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_GROUP".
+ */
+ public static final int CLASS_TYPE_XA_GROUP = 1002;
+ /**
+ * CLASS_TYPE_XA_USER is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_USER".
+ */
+ public static final int CLASS_TYPE_XA_USER = 1003;
+ /**
+ * CLASS_TYPE_XA_GROUP_USER is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_GROUP_USER".
+ */
+ public static final int CLASS_TYPE_XA_GROUP_USER = 1004;
+ /**
+ * CLASS_TYPE_XA_GROUP_GROUP is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_GROUP_GROUP".
+ */
+ public static final int CLASS_TYPE_XA_GROUP_GROUP = 1005;
+ /**
+ * CLASS_TYPE_XA_PERM_MAP is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_PERM_MAP".
+ */
+ public static final int CLASS_TYPE_XA_PERM_MAP = 1006;
+ /**
+ * CLASS_TYPE_XA_AUDIT_MAP is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_AUDIT_MAP".
+ */
+ public static final int CLASS_TYPE_XA_AUDIT_MAP = 1007;
+ /**
+ * CLASS_TYPE_XA_CRED_STORE is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_CRED_STORE".
+ */
+ public static final int CLASS_TYPE_XA_CRED_STORE = 1008;
+ /**
+ * CLASS_TYPE_XA_POLICY_EXPORT_AUDIT is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_POLICY_EXPORT_AUDIT".
+ */
+ public static final int CLASS_TYPE_XA_POLICY_EXPORT_AUDIT = 1009;
+ /**
+ * CLASS_TYPE_TRX_LOG is an element of enum ClassTypes. Its value is "CLASS_TYPE_TRX_LOG".
+ */
+ public static final int CLASS_TYPE_TRX_LOG = 1010;
+ /**
+ * CLASS_TYPE_XA_ACCESS_AUDIT is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_ACCESS_AUDIT".
+ */
+ public static final int CLASS_TYPE_XA_ACCESS_AUDIT = 1011;
+ /**
+ * CLASS_TYPE_XA_TRANSACTION_LOG_ATTRIBUTE is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_TRANSACTION_LOG_ATTRIBUTE".
+ */
+ public static final int CLASS_TYPE_XA_TRANSACTION_LOG_ATTRIBUTE = 1012;
+
+ /**
+ * Max value for enum ClassTypes_MAX
+ */
+ public static final int ClassTypes_MAX = 1012;
+
+
+
+ static public String getLabelFor_ActiveStatus( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Disabled"; //STATUS_DISABLED
+ }
+ if( elementValue == 1 ) {
+ return "Enabled"; //STATUS_ENABLED
+ }
+ if( elementValue == 2 ) {
+ return "Deleted"; //STATUS_DELETED
+ }
+ return null;
+ }
+
+ static public String getLabelFor_ActivationStatus( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Disabled"; //ACT_STATUS_DISABLED
+ }
+ if( elementValue == 1 ) {
+ return "Active"; //ACT_STATUS_ACTIVE
+ }
+ if( elementValue == 2 ) {
+ return "Pending Approval"; //ACT_STATUS_PENDING_APPROVAL
+ }
+ if( elementValue == 3 ) {
+ return "Pending Activation"; //ACT_STATUS_PENDING_ACTIVATION
+ }
+ if( elementValue == 4 ) {
+ return "Rejected"; //ACT_STATUS_REJECTED
+ }
+ if( elementValue == 5 ) {
+ return "Deactivated"; //ACT_STATUS_DEACTIVATED
+ }
+ if( elementValue == 6 ) {
+ return "Registration Pending"; //ACT_STATUS_PRE_REGISTRATION
+ }
+ if( elementValue == 7 ) {
+ return "No login privilege"; //ACT_STATUS_NO_LOGIN
+ }
+ return null;
+ }
+
+ static public String getLabelFor_BooleanValue( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "None"; //BOOL_NONE
+ }
+ if( elementValue == 1 ) {
+ return "True"; //BOOL_TRUE
+ }
+ if( elementValue == 2 ) {
+ return "False"; //BOOL_FALSE
+ }
+ return null;
+ }
+
+ static public String getLabelFor_DataType( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Unknown"; //DATA_TYPE_UNKNOWN
+ }
+ if( elementValue == 1 ) {
+ return "Integer"; //DATA_TYPE_INTEGER
+ }
+ if( elementValue == 2 ) {
+ return "Double"; //DATA_TYPE_DOUBLE
+ }
+ if( elementValue == 3 ) {
+ return "String"; //DATA_TYPE_STRING
+ }
+ if( elementValue == 4 ) {
+ return "Boolean"; //DATA_TYPE_BOOLEAN
+ }
+ if( elementValue == 5 ) {
+ return "Date"; //DATA_TYPE_DATE
+ }
+ if( elementValue == 6 ) {
+ return "String enumeration"; //DATA_TYPE_STRING_ENUM
+ }
+ if( elementValue == 7 ) {
+ return "Long"; //DATA_TYPE_LONG
+ }
+ if( elementValue == 8 ) {
+ return "Integer enumeration"; //DATA_TYPE_INTEGER_ENUM
+ }
+ return null;
+ }
+
+ static public String getLabelFor_DeviceType( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Unknown"; //DEVICE_UNKNOWN
+ }
+ if( elementValue == 1 ) {
+ return "Browser"; //DEVICE_BROWSER
+ }
+ if( elementValue == 2 ) {
+ return "iPhone"; //DEVICE_IPHONE
+ }
+ if( elementValue == 3 ) {
+ return "iPad"; //DEVICE_IPAD
+ }
+ if( elementValue == 4 ) {
+ return "iPod"; //DEVICE_IPOD
+ }
+ if( elementValue == 5 ) {
+ return "Android"; //DEVICE_ANDROID
+ }
+ return null;
+ }
+
+ static public String getLabelFor_DiffLevel( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Unknown"; //DIFF_UNKNOWN
+ }
+ if( elementValue == 1 ) {
+ return "Low"; //DIFF_LOW
+ }
+ if( elementValue == 2 ) {
+ return "Medium"; //DIFF_MEDIUM
+ }
+ if( elementValue == 3 ) {
+ return "High"; //DIFF_HIGH
+ }
+ return null;
+ }
+
+ static public String getLabelFor_FileType( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "File"; //FILE_FILE
+ }
+ if( elementValue == 1 ) {
+ return "Directory"; //FILE_DIR
+ }
+ return null;
+ }
+
+ static public String getLabelFor_FreqType( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "None"; //FREQ_NONE
+ }
+ if( elementValue == 1 ) {
+ return "Manual"; //FREQ_MANUAL
+ }
+ if( elementValue == 2 ) {
+ return "Hourly"; //FREQ_HOURLY
+ }
+ if( elementValue == 3 ) {
+ return "Daily"; //FREQ_DAILY
+ }
+ if( elementValue == 4 ) {
+ return "Weekly"; //FREQ_WEEKLY
+ }
+ if( elementValue == 5 ) {
+ return "Bi Weekly"; //FREQ_BI_WEEKLY
+ }
+ if( elementValue == 6 ) {
+ return "Monthly"; //FREQ_MONTHLY
+ }
+ return null;
+ }
+
+ static public String getLabelFor_MimeType( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Unknown"; //MIME_UNKNOWN
+ }
+ if( elementValue == 1 ) {
+ return "Text"; //MIME_TEXT
+ }
+ if( elementValue == 2 ) {
+ return "Html"; //MIME_HTML
+ }
+ if( elementValue == 3 ) {
+ return "png"; //MIME_PNG
+ }
+ if( elementValue == 4 ) {
+ return "jpeg"; //MIME_JPEG
+ }
+ return null;
+ }
+
+ static public String getLabelFor_NumberFormat( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "None"; //NUM_FORMAT_NONE
+ }
+ if( elementValue == 1 ) {
+ return "Numeric"; //NUM_FORMAT_NUMERIC
+ }
+ if( elementValue == 2 ) {
+ return "Alphabhet"; //NUM_FORMAT_ALPHA
+ }
+ if( elementValue == 3 ) {
+ return "Roman"; //NUM_FORMAT_ROMAN
+ }
+ return null;
+ }
+
+ static public String getLabelFor_ObjectStatus( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Active"; //OBJ_STATUS_ACTIVE
+ }
+ if( elementValue == 1 ) {
+ return "Deleted"; //OBJ_STATUS_DELETED
+ }
+ if( elementValue == 2 ) {
+ return "Archived"; //OBJ_STATUS_ARCHIVED
+ }
+ return null;
+ }
+
+ static public String getLabelFor_PasswordResetStatus( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Active"; //PWD_RESET_ACTIVE
+ }
+ if( elementValue == 1 ) {
+ return "Used"; //PWD_RESET_USED
+ }
+ if( elementValue == 2 ) {
+ return "Expired"; //PWD_RESET_EXPIRED
+ }
+ if( elementValue == 3 ) {
+ return "Disabled"; //PWD_RESET_DISABLED
+ }
+ return null;
+ }
+
+ static public String getLabelFor_PriorityType( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Normal"; //PRIORITY_NORMAL
+ }
+ if( elementValue == 1 ) {
+ return "Low"; //PRIORITY_LOW
+ }
+ if( elementValue == 2 ) {
+ return "Medium"; //PRIORITY_MEDIUM
+ }
+ if( elementValue == 3 ) {
+ return "High"; //PRIORITY_HIGH
+ }
+ return null;
+ }
+
+ static public String getLabelFor_ProgressStatus( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Pending"; //PROGRESS_PENDING
+ }
+ if( elementValue == 1 ) {
+ return "In Progress"; //PROGRESS_IN_PROGRESS
+ }
+ if( elementValue == 2 ) {
+ return "Complete"; //PROGRESS_COMPLETE
+ }
+ if( elementValue == 3 ) {
+ return "Aborted"; //PROGRESS_ABORTED
+ }
+ if( elementValue == 4 ) {
+ return "Failed"; //PROGRESS_FAILED
+ }
+ return null;
+ }
+
+ static public String getLabelFor_RelationType( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "None"; //REL_NONE
+ }
+ if( elementValue == 1 ) {
+ return "Self"; //REL_SELF
+ }
+ return null;
+ }
+
+ static public String getLabelFor_UserSource( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Application"; //USER_APP
+ }
+ if( elementValue == 1 ) {
+ return "External"; //USER_EXTERNAL
+ }
+ /*if( elementValue == 1 ) {
+ return "Google"; //USER_GOOGLE
+ }
+ if( elementValue == 2 ) {
+ return "FaceBook"; //USER_FB
+ }*/
+ return null;
+ }
+
+ static public String getLabelFor_AssetType( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Unknown"; //ASSET_UNKNOWN
+ }
+ if( elementValue == 1 ) {
+ return "HDFS"; //ASSET_HDFS
+ }
+ if( elementValue == 2 ) {
+ return "HBase"; //ASSET_HBASE
+ }
+ if( elementValue == 3 ) {
+ return "Hive"; //ASSET_HIVE
+ }
+ if( elementValue == 4 ) {
+ return "Agent"; //ASSET_HIVE
+ }
+ if( elementValue == 5 ) {
+ return "Knox"; //ASSET_HIVE
+ }
+ if( elementValue == 6 ) {
+ return "Storm"; //ASSET_HIVE
+ }
+ return null;
+ }
+
+ static public String getLabelFor_AccessResult( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Denied"; //ACCESS_RESULT_DENIED
+ }
+ if( elementValue == 1 ) {
+ return "Allowed"; //ACCESS_RESULT_ALLOWED
+ }
+ return null;
+ }
+
+ static public String getLabelFor_PolicyType( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Inclusion"; //POLICY_INCLUSION
+ }
+ if( elementValue == 1 ) {
+ return "Exclusion"; //POLICY_EXCLUSION
+ }
+ return null;
+ }
+
+ static public String getLabelFor_XAAuditType( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Unknown"; //XA_AUDIT_TYPE_UNKNOWN
+ }
+ if( elementValue == 1 ) {
+ return "All"; //XA_AUDIT_TYPE_ALL
+ }
+ if( elementValue == 2 ) {
+ return "Read"; //XA_AUDIT_TYPE_READ
+ }
+ if( elementValue == 3 ) {
+ return "Write"; //XA_AUDIT_TYPE_WRITE
+ }
+ if( elementValue == 4 ) {
+ return "Create"; //XA_AUDIT_TYPE_CREATE
+ }
+ if( elementValue == 5 ) {
+ return "Delete"; //XA_AUDIT_TYPE_DELETE
+ }
+ if( elementValue == 6 ) {
+ return "Login"; //XA_AUDIT_TYPE_LOGIN
+ }
+ return null;
+ }
+
+ static public String getLabelFor_ResourceType( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Unknown"; //RESOURCE_UNKNOWN
+ }
+ if( elementValue == 1 ) {
+ return "Path"; //RESOURCE_PATH
+ }
+ if( elementValue == 2 ) {
+ return "Database"; //RESOURCE_DB
+ }
+ if( elementValue == 3 ) {
+ return "Table"; //RESOURCE_TABLE
+ }
+ if( elementValue == 4 ) {
+ return "Column Family"; //RESOURCE_COL_FAM
+ }
+ if( elementValue == 5 ) {
+ return "Column"; //RESOURCE_COLUMN
+ }
+ if( elementValue == 6 ) {
+ return "VIEW"; //RESOURCE_VIEW
+ }
+ if( elementValue == 7 ) {
+ return "UDF"; //RESOURCE_UDF
+ }
+ if( elementValue == 8 ) {
+ return "View Column"; //RESOURCE_VIEW_COL
+ }
+ return null;
+ }
+
+ static public String getLabelFor_XAGroupType( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Unknown"; //XA_GROUP_UNKNOWN
+ }
+ if( elementValue == 1 ) {
+ return "User"; //XA_GROUP_USER
+ }
+ if( elementValue == 2 ) {
+ return "Group"; //XA_GROUP_GROUP
+ }
+ if( elementValue == 3 ) {
+ return "Role"; //XA_GROUP_ROLE
+ }
+ return null;
+ }
+
+ static public String getLabelFor_XAPermForType( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Unknown"; //XA_PERM_FOR_UNKNOWN
+ }
+ if( elementValue == 1 ) {
+ return "Permission for Users"; //XA_PERM_FOR_USER
+ }
+ if( elementValue == 2 ) {
+ return "Permission for Groups"; //XA_PERM_FOR_GROUP
+ }
+ return null;
+ }
+
+ static public String getLabelFor_XAPermType( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "Unknown"; //XA_PERM_TYPE_UNKNOWN
+ }
+ if( elementValue == 1 ) {
+ return "Reset"; //XA_PERM_TYPE_RESET
+ }
+ if( elementValue == 2 ) {
+ return "Read"; //XA_PERM_TYPE_READ
+ }
+ if( elementValue == 3 ) {
+ return "Write"; //XA_PERM_TYPE_WRITE
+ }
+ if( elementValue == 4 ) {
+ return "Create"; //XA_PERM_TYPE_CREATE
+ }
+ if( elementValue == 5 ) {
+ return "Delete"; //XA_PERM_TYPE_DELETE
+ }
+ if( elementValue == 6 ) {
+ return "Admin"; //XA_PERM_TYPE_ADMIN
+ }
+ if( elementValue == 7 ) {
+ return "Obfuscate"; //XA_PERM_TYPE_OBFUSCATE
+ }
+ if( elementValue == 8 ) {
+ return "Mask"; //XA_PERM_TYPE_MASK
+ }
+ if( elementValue == 9 ) {
+ return "Execute"; //XA_PERM_TYPE_EXECUTE
+ }
+ if( elementValue == 10 ) {
+ return "Select"; //XA_PERM_TYPE_SELECT
+ }
+ if( elementValue == 11 ) {
+ return "Update"; //XA_PERM_TYPE_UPDATE
+ }
+ if( elementValue == 12 ) {
+ return "Drop"; //XA_PERM_TYPE_DROP
+ }
+ if( elementValue == 13 ) {
+ return "Alter"; //XA_PERM_TYPE_ALTER
+ }
+ if( elementValue == 14 ) {
+ return "Index"; //XA_PERM_TYPE_INDEX
+ }
+ if( elementValue == 15 ) {
+ return "Lock"; //XA_PERM_TYPE_LOCK
+ }
+ if( elementValue == 16 ) {
+ return "All"; //XA_PERM_TYPE_ALL
+ }
+ if( elementValue == 17 ) {
+ return "Allow"; //XA_PERM_TYPE_ALLOW
+ }
+ return null;
+ }
+
+ static public String getLabelFor_ClassTypes( int elementValue ) {
+ if( elementValue == 0 ) {
+ return "None"; //CLASS_TYPE_NONE
+ }
+ if( elementValue == 1 ) {
+ return "Message"; //CLASS_TYPE_MESSAGE
+ }
+ if( elementValue == 2 ) {
+ return "User Profile"; //CLASS_TYPE_USER_PROFILE
+ }
+ if( elementValue == 3 ) {
+ return "Authentication Session"; //CLASS_TYPE_AUTH_SESS
+ }
+ if( elementValue == 4 ) {
+ return null; //CLASS_TYPE_DATA_OBJECT
+ }
+ if( elementValue == 5 ) {
+ return null; //CLASS_TYPE_NAMEVALUE
+ }
+ if( elementValue == 6 ) {
+ return null; //CLASS_TYPE_LONG
+ }
+ if( elementValue == 7 ) {
+ return null; //CLASS_TYPE_PASSWORD_CHANGE
+ }
+ if( elementValue == 8 ) {
+ return null; //CLASS_TYPE_STRING
+ }
+ if( elementValue == 9 ) {
+ return null; //CLASS_TYPE_ENUM
+ }
+ if( elementValue == 10 ) {
+ return null; //CLASS_TYPE_ENUM_ELEMENT
+ }
+ if( elementValue == 11 ) {
+ return "Response"; //CLASS_TYPE_RESPONSE
+ }
+ if( elementValue == 1000 ) {
+ return "Asset"; //CLASS_TYPE_XA_ASSET
+ }
+ if( elementValue == 1001 ) {
+ return "Resource"; //CLASS_TYPE_XA_RESOURCE
+ }
+ if( elementValue == 1002 ) {
+ return "XA Group"; //CLASS_TYPE_XA_GROUP
+ }
+ if( elementValue == 1003 ) {
+ return "XA User"; //CLASS_TYPE_XA_USER
+ }
+ if( elementValue == 1004 ) {
+ return "XA Group of Users"; //CLASS_TYPE_XA_GROUP_USER
+ }
+ if( elementValue == 1005 ) {
+ return "XA Group of groups"; //CLASS_TYPE_XA_GROUP_GROUP
+ }
+ if( elementValue == 1006 ) {
+ return "XA permissions for resource"; //CLASS_TYPE_XA_PERM_MAP
+ }
+ if( elementValue == 1007 ) {
+ return "XA audits for resource"; //CLASS_TYPE_XA_AUDIT_MAP
+ }
+ if( elementValue == 1008 ) {
+ return "XA credential store"; //CLASS_TYPE_XA_CRED_STORE
+ }
+ if( elementValue == 1009 ) {
+ return "XA Policy Export Audit"; //CLASS_TYPE_XA_POLICY_EXPORT_AUDIT
+ }
+ if( elementValue == 1010 ) {
+ return "Transaction log"; //CLASS_TYPE_TRX_LOG
+ }
+ if( elementValue == 1011 ) {
+ return "Access Audit"; //CLASS_TYPE_XA_ACCESS_AUDIT
+ }
+ if( elementValue == 1012 ) {
+ return "Transaction log attribute"; //CLASS_TYPE_XA_TRANSACTION_LOG_ATTRIBUTE
+ }
+ return null;
+ }
+
+
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/XAConfigUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/XAConfigUtil.java b/security-admin/src/main/java/org/apache/ranger/common/XAConfigUtil.java
new file mode 100644
index 0000000..e50fb20
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/XAConfigUtil.java
@@ -0,0 +1,91 @@
+/*
+ * 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 org.apache.log4j.Logger;
+import org.apache.ranger.common.PropertiesUtil;
+import org.springframework.stereotype.Component;
+
+/**
+ *
+ *
+ */
+@Component
+public class XAConfigUtil {
+ static Logger logger = Logger.getLogger(XAConfigUtil.class);
+
+ String webappRootURL;
+ int defaultMaxRows = 250;
+ String[] roles;
+ boolean accessFilterEnabled = true;
+ boolean isModerationEnabled = false;
+ boolean isUserPrefEnabled = false;
+
+ public XAConfigUtil() {
+ webappRootURL = PropertiesUtil
+ .getProperty("xa.webapp.url.root");
+ if (webappRootURL == null || webappRootURL.trim().length() == 0) {
+ logger.error("webapp URL is not set. Please xa.webapp.url.root property");
+ }
+
+ defaultMaxRows = PropertiesUtil.getIntProperty(
+ "xa.db.maxrows.default", defaultMaxRows);
+
+ roles = PropertiesUtil
+ .getPropertyStringList("xa.users.roles.list");
+
+ accessFilterEnabled = PropertiesUtil.getBooleanProperty(
+ "xa.db.access.filter.enable", true);
+
+ isModerationEnabled = PropertiesUtil.getBooleanProperty(
+ "xa.moderation.enabled", isModerationEnabled);
+ isUserPrefEnabled = PropertiesUtil.getBooleanProperty(
+ "xa.userpref.enabled", isUserPrefEnabled);
+ }
+
+ /**
+ * @return the defaultMaxRows
+ */
+ public int getDefaultMaxRows() {
+ return defaultMaxRows;
+ }
+
+ /**
+ * @return the roles
+ */
+ public String[] getRoles() {
+ return roles;
+ }
+
+ /**
+ * @return the accessFilterEnabled
+ */
+ public boolean isAccessFilterEnabled() {
+ return accessFilterEnabled;
+ }
+
+ /**
+ * @return the webAppRootURL
+ */
+ public String getWebAppRootURL() {
+ return webappRootURL;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/XAConstants.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/XAConstants.java b/security-admin/src/main/java/org/apache/ranger/common/XAConstants.java
new file mode 100644
index 0000000..5dbebb8
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/XAConstants.java
@@ -0,0 +1,169 @@
+/*
+ * 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 XAConstants extends XACommonEnums {
+
+ // Default Roles
+ public final static String ROLE_SYS_ADMIN = "ROLE_SYS_ADMIN";
+ public final static String ROLE_ADMIN = "ROLE_ADMIN";
+ public final static String ROLE_INTEGRATOR = "ROLE_INTEGRATOR";
+ public final static String ROLE_DATA_ANALYST = "ROLE_DATA_ANALYST";
+ public final static String ROLE_BIZ_MGR = "ROLE_BIZ_MGR";
+
+ public final static String ROLE_USER = "ROLE_USER";
+ public final static String ROLE_ANON = "ROLE_ANON";
+ public final static String ROLE_OTHER = "ROLE_OTHER";
+ public final static String GROUP_PUBLIC = "public";
+ // Action constants
+ public final static String ACTION_EDIT = "edit";
+ public final static String ACTION_CHANGE = "change";
+ public final static String ACTION_DELETE = "delete";
+ public final static String ACTION_MARK_SPAM = "mark_spam";
+ public final static String ACTION_RATE = "rate";
+ public final static String ACTION_SELECT = "select";
+ public final static String ACTION_UNSELECT = "unselect";
+ public final static String ACTION_HIDE = "hide";
+ public final static String ACTION_UNHIDE = "unhide";
+ public final static String ACTION_SHARE = "share";
+ public final static String ACTION_UNSHARE = "unshare";
+ public final static String ACTION_BOOKMARK = "bookmark";
+ public final static String ACTION_UNBOOKMARK = "unbookmark";
+
+ // Sendgrid email API constants
+ public static final String SENDGRID_API_USER = "api_user";
+ public static final String SENDGRID_API_KEY = "api_key";
+ public static final String SENDGRID_TO = "to";
+ public static final String SENDGRID_TO_NAME = "toname";
+ public static final String SENDGRID_SUBJECT = "subject";
+ public static final String SENDGRID_TEXT = "text";
+ public static final String SENDGRID_HTML = "html";
+ public static final String SENDGRID_FROM_EMAIL = "from";
+ public static final String SENDGRID_FROM_NAME = "fromname";
+ public static final String SENDGRID_BCC = "bcc";
+ public static final String SENDGRID_CC = "cc";
+ public static final String SENDGRID_REPLY_TO = "replyto";
+
+ // User create validation errors
+ public enum ValidationUserProfile {
+
+ NO_EMAIL_ADDR("xa.validation.userprofile.no_email_addr",
+ "Email address not provided"), INVALID_EMAIL_ADDR(
+ "xa.validation.userprofile.userprofile.invalid_email_addr",
+ "Invalid email address"), NO_FIRST_NAME(
+ "xa.validation.userprofile.userprofile.no_first_name",
+ "First name not provided"), INVALID_FIRST_NAME(
+ "xa.validation.userprofile.invalid_first_name",
+ "Invalid first name"), NO_LAST_NAME(
+ "xa.validation.userprofile.noemailaddr",
+ "Email address not provided"), INVALID_LAST_NAME(
+ "xa.validation.userprofile.noemailaddr",
+ "Email address not provided"), NO_PUBLIC_SCREEN_NAME(
+ "xa.validation.userprofile.noemailaddr",
+ "Email address not provided"), INVALID_PUBLIC_SCREEN_NAME(
+ "xa.validation.userprofile.noemailaddr",
+ "Email address not provided");
+
+ String rbKey;
+ String message;
+
+ ValidationUserProfile(String rbKey, String message) {
+ this.rbKey = rbKey;
+ this.message = message;
+ }
+ };
+
+ // these constants will be used in setting GjResponse object.
+
+ public final static String USER_PENDING_APPROVAL_MSG = "User is yet not reviewed by Administrator. Please contact at <number>.";
+ public final static int USER_PENDING_APPROVAL_STATUS_CODE = 0;
+
+ public final static String USER_APPROVAL_MSG = "User is approved";
+ public final static int USER_APPROVAL_STATUS_CODE = 1;
+
+ public final static String USER_REJECTION_MSG = "User is rejected";
+ public final static int USER_REJECTION_STATUS_CODE = 1;
+
+ public final static String USER_STATUS_ALREADY_CHANGED_MSG = "Can not change user status. it is either already activated/approved/rejected";
+ public final static int USER_STATUS_ALREADY_CHANGED_STATUS_CODE = 0;
+
+ public final static String USER_ALREADY_ACTIVATED_MSG = "Your account is already activated. If you have forgotten your password, then from the login page, select 'Forgot Password'";
+ public final static int USER_ALREADY_ACTIVATED_STATUS_CODE = 0;
+
+ public final static String USER_STATUS_NOT_ACTIVE_MSG = "User is not in active status. Please activate your account first.";
+ public final static int USER_STATUS_NOT_ACTIVE_STATUS_CODE = 0;
+
+ public final static String INVALID_EMAIL_ADDRESS_MSG = "Invalid email address";
+ public final static int INVALID_EMAIL_ADDRESS_STATUS_CODE = 0;
+
+ public final static String WRONG_ACTIVATION_CODE_MSG = "Wrong activation code";
+ public final static int WRONG_ACTIVATION_CODE_STATUS_CODE = 0;
+
+ public final static String VALID_EMAIL_ADDRESS_MSG = "Valid email address";
+ public final static int VALID_EMAIL_ADDRESS_STATUS_CODE = 1;
+
+ public final static String NO_ACTIVATION_RECORD_FOR_USER_ERR_MSG = "No activation record found for user:";
+ public final static String NO_ACTIVATION_ENTRY = "activation entry not found";
+
+ public final static String VALIDATION_INVALID_DATA_DESC = "Invalid value for";
+ public final static int VALIDATION_INVALID_DATA_CODE = 0;
+ public static final String GROUP_MODERATORS = "GROUP_MODERATORS";
+
+ // public final static String EMAIL_WELCOME_MSG =
+ // "Welcome to iSchoolCircle";
+ // public final static String EMAIL_LINK_WELCOME_MSG =
+ // "Welcome to iSchoolCircle ! Please verify your account by clicking on the link below: ";
+ // public static final String EMAIL_EDIT_REJECTED_MSG =
+ // "Your changes not approved for public sharing.";
+ // public static final String EMAIL_APPROVAL_NEEDED_MSG =
+ // "New objects pending approval";
+ // public static final String EMAIL_PWD_RESET_CODE_MSG =
+ // "iSchoolCircle - Password Reset";
+
+ public final static String PWD_RESET_FAILED_MSG = "Invalid password reset request";
+
+ public final static String INVALID_NEW_PASSWORD_MSG = "Invalid new password";
+ public static final String EMAIL_NEW_FEEDBACK_RECEIVED = "New feedback from";
+ public static final int INITIAL_DOCUMENT_VERSION = 1;
+
+ public static final int EMAIL_TYPE_ACCOUNT_CREATE = 0;
+ public static final int EMAIL_TYPE_USER_CREATE = 1;
+ public static final int EMAIL_TYPE_USER_ACCT_ADD = 2;
+ public static final int EMAIL_TYPE_DOCUMENT_CREATE = 3;
+ public static final int EMAIL_TYPE_DISCUSSION_CREATE = 4;
+ public static final int EMAIL_TYPE_NOTE_CREATE = 5;
+ public static final int EMAIL_TYPE_TASK_CREATE = 6;
+ public static final int EMAIL_TYPE_USER_PASSWORD = 7;
+ public static final int EMAIL_TYPE_USER_ACTIVATION = 8;
+ public static final int EMAIL_TYPE_USER_ROLE_UPDATED = 9;
+ public static final int EMAIL_TYPE_USER_GRP_ADD = 10;
+
+ public static enum RBAC_PERM {
+ ALLOW_NONE,
+ ALLOW_READ,
+ ALLOW_WRITE,
+ ALLOW_DELETE
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/XAJAXBContextResolver.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/XAJAXBContextResolver.java b/security-admin/src/main/java/org/apache/ranger/common/XAJAXBContextResolver.java
new file mode 100644
index 0000000..87a7924
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/XAJAXBContextResolver.java
@@ -0,0 +1,73 @@
+/*
+ * 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 javax.ws.rs.ext.ContextResolver;
+import javax.ws.rs.ext.Provider;
+import javax.xml.bind.JAXBContext;
+
+import org.apache.ranger.common.*;
+
+import com.sun.jersey.api.json.JSONConfiguration;
+import com.sun.jersey.api.json.JSONJAXBContext;
+
+/**
+ *
+ *
+ */
+@Provider
+public class XAJAXBContextResolver implements ContextResolver<JAXBContext> {
+
+ private JAXBContext context;
+ private Class<?>[] types = {
+ org.apache.ranger.view.VXAuthSessionList.class,
+ org.apache.ranger.view.VXResponse.class,
+ org.apache.ranger.view.VXStringList.class,
+ org.apache.ranger.view.VXPortalUserList.class,
+ org.apache.ranger.view.VXAssetList.class,
+ org.apache.ranger.view.VXResourceList.class,
+ org.apache.ranger.view.VXCredentialStoreList.class,
+ org.apache.ranger.view.VXGroupList.class,
+ org.apache.ranger.view.VXUserList.class,
+ org.apache.ranger.view.VXGroupUserList.class,
+ org.apache.ranger.view.VXGroupGroupList.class,
+ org.apache.ranger.view.VXPermMapList.class,
+ org.apache.ranger.view.VXAuditMapList.class,
+ org.apache.ranger.view.VXPolicyExportAuditList.class,
+ org.apache.ranger.view.VXAccessAuditList.class
+ };
+
+ public XAJAXBContextResolver() throws Exception {
+ JSONConfiguration config = JSONConfiguration.natural().build();
+ context = new JSONJAXBContext(config, types);
+ }
+
+ @Override
+ public JAXBContext getContext(Class<?> objectType) {
+ // return context;
+ for (Class<?> type : types) {
+ if (type.getName().equals(objectType.getName())) {
+ return context;
+ }
+ }
+ return null;
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/XASearchUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/XASearchUtil.java b/security-admin/src/main/java/org/apache/ranger/common/XASearchUtil.java
new file mode 100644
index 0000000..ff1f1a4
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/XASearchUtil.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 javax.persistence.EntityManager;
+import javax.persistence.Query;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.common.SearchCriteria;
+import org.apache.ranger.common.SearchField;
+import org.apache.ranger.common.SearchUtil;
+import org.apache.ranger.db.XADaoManager;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+@Component
+public class XASearchUtil extends SearchUtil {
+ final static Logger logger = Logger.getLogger(XASearchUtil.class);
+ /*
+ @Override
+ 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;
+ }
+ */
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/annotation/XAAnnotationClassName.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/annotation/XAAnnotationClassName.java b/security-admin/src/main/java/org/apache/ranger/common/annotation/XAAnnotationClassName.java
new file mode 100644
index 0000000..dcc357d
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/annotation/XAAnnotationClassName.java
@@ -0,0 +1,32 @@
+/*
+ * 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.annotation;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+
+@Retention(RetentionPolicy.RUNTIME)
+public @interface XAAnnotationClassName {
+ public Class class_name();
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/annotation/XAAnnotationJSMgrName.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/annotation/XAAnnotationJSMgrName.java b/security-admin/src/main/java/org/apache/ranger/common/annotation/XAAnnotationJSMgrName.java
new file mode 100644
index 0000000..cf21848
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/annotation/XAAnnotationJSMgrName.java
@@ -0,0 +1,35 @@
+/*
+ * 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.annotation;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ *
+ *
+ */
+@Retention(RetentionPolicy.RUNTIME)
+public @interface XAAnnotationJSMgrName {
+ public String value();
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/annotation/XAAnnotationRestAPI.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/annotation/XAAnnotationRestAPI.java b/security-admin/src/main/java/org/apache/ranger/common/annotation/XAAnnotationRestAPI.java
new file mode 100644
index 0000000..3dc62bb
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/annotation/XAAnnotationRestAPI.java
@@ -0,0 +1,36 @@
+/*
+ * 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.annotation;
+
+import java.lang.annotation.*;
+
+/**
+ * Annotating the REST APIs
+ *
+ */
+@Retention(RetentionPolicy.RUNTIME)
+public @interface XAAnnotationRestAPI {
+ public String api_name() default "";
+ public boolean updates_generic_objects() default false;
+ public String updates_classes() default "";
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/db/BaseDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/db/BaseDao.java b/security-admin/src/main/java/org/apache/ranger/common/db/BaseDao.java
new file mode 100644
index 0000000..bebe956
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/db/BaseDao.java
@@ -0,0 +1,215 @@
+/*
+ * 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.db;
+
+
+
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.persistence.EntityManager;
+import javax.persistence.NoResultException;
+import javax.persistence.Query;
+import javax.persistence.TypedQuery;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.common.ContextUtil;
+import org.apache.ranger.db.XADaoManager;
+import org.apache.ranger.db.XADaoManagerBase;
+import org.apache.ranger.entity.XXDBBase;
+
+public abstract class BaseDao<T> {
+ static final Logger logger = Logger.getLogger(BaseDao.class);
+
+ protected XADaoManager daoManager;
+
+ EntityManager em;
+
+ protected Class<T> tClass;
+
+ public BaseDao(XADaoManagerBase daoManager) {
+ this.daoManager = (XADaoManager) daoManager;
+ this.init(daoManager.getEntityManager());
+ }
+
+ public BaseDao(XADaoManagerBase daoManager, String persistenceContextUnit) {
+ this.daoManager = (XADaoManager) daoManager;
+
+ EntityManager em = this.daoManager.getEntityManager(persistenceContextUnit);
+
+ this.init(em);
+ }
+
+ @SuppressWarnings("unchecked")
+ private void init(EntityManager em) {
+ this.em = em;
+
+ ParameterizedType genericSuperclass = (ParameterizedType) getClass()
+ .getGenericSuperclass();
+
+ Type type = genericSuperclass.getActualTypeArguments()[0];
+
+ if (type instanceof ParameterizedType) {
+ this.tClass = (Class<T>) ((ParameterizedType) type).getRawType();
+ } else {
+ this.tClass = (Class<T>) type;
+ }
+ }
+
+ public EntityManager getEntityManager() {
+ return this.em;
+ }
+
+ public T create(T obj) {
+ T ret = null;
+
+ em.persist(obj);
+ em.flush();
+
+ ret = obj;
+ return ret;
+ }
+
+ public T update(T obj) {
+ em.merge(obj);
+ em.flush();
+ return obj;
+ }
+
+ public boolean remove(Long id) {
+ return remove(getById(id));
+ }
+
+ public boolean remove(T obj) {
+ if (obj == null) {
+ return true;
+ }
+
+ em.remove(obj);
+ em.flush();
+
+ return true;
+ }
+
+ public T getById(Long id) {
+ if (id == null) {
+ return null;
+ }
+ T ret = null;
+ try {
+ ret = em.find(tClass, id);
+ } catch (NoResultException e) {
+ return null;
+ }
+ return ret;
+ }
+
+ public List<T> findByNamedQuery(String namedQuery, String paramName,
+ Object refId) {
+ List<T> ret = new ArrayList<T>();
+
+ if (namedQuery == null) {
+ return ret;
+ }
+ try {
+ TypedQuery<T> qry = em.createNamedQuery(namedQuery, tClass);
+ qry.setParameter(paramName, refId);
+ ret = qry.getResultList();
+ } catch (NoResultException e) {
+ // ignore
+ }
+ return ret;
+ }
+
+ public List<T> findByParentId(Long parentId) {
+ String namedQuery = tClass.getSimpleName() + ".findByParentId";
+ return findByNamedQuery(namedQuery, "parentId", parentId);
+ }
+
+
+ public List<T> executeQueryInSecurityContext(Class<T> clazz, Query query) {
+ return executeQueryInSecurityContext(clazz, query, true);
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<T> executeQueryInSecurityContext(Class<T> clazz, Query query,
+ boolean userPrefFilter) {
+ // boolean filterEnabled = false;
+ List<T> rtrnList = null;
+ try {
+ // filterEnabled = enableVisiblityFilters(clazz, userPrefFilter);
+
+ rtrnList = query.getResultList();
+ } finally {
+ // if (filterEnabled) {
+ // disableVisiblityFilters(clazz);
+ // }
+
+ }
+
+ return rtrnList;
+ }
+
+ /**
+ * @param clazz
+ * @param query
+ * @param b
+ * @return
+ */
+ private Long executeCountQueryInSecurityContext(Class<T> clazz,
+ Query query, boolean userPrefFilter) {
+ // boolean filterEnabled = false;
+ Long rtrnObj = null;
+ try {
+ // filterEnabled = enableVisiblityFilters(clazz, userPrefFilter);
+ rtrnObj = (Long) query.getSingleResult();
+ } finally {
+ // if (filterEnabled) {
+ // disableVisiblityFilters(clazz);
+ // }
+ }
+
+ return rtrnObj;
+ }
+
+ public Long executeCountQueryInSecurityContext(Class<T> clazz, Query query) {
+ return executeCountQueryInSecurityContext(clazz, query, true);
+ }
+
+ public List<T> getAll() {
+ List<T> ret = null;
+ TypedQuery<T> qry = em.createQuery(
+ "SELECT t FROM " + tClass.getSimpleName() + " t", tClass);
+ ret = qry.getResultList();
+ return ret;
+ }
+
+ public Long getAllCount() {
+ Long ret = null;
+ TypedQuery<Long> qry = em.createQuery(
+ "SELECT count(t) FROM " + tClass.getSimpleName() + " t",
+ Long.class);
+ ret = qry.getSingleResult();
+ return ret;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/db/JPABeanCallbacks.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/db/JPABeanCallbacks.java b/security-admin/src/main/java/org/apache/ranger/common/db/JPABeanCallbacks.java
new file mode 100644
index 0000000..c5176ba
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/db/JPABeanCallbacks.java
@@ -0,0 +1,103 @@
+/*
+ * 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.db;
+
+import javax.persistence.PrePersist;
+import javax.persistence.PreUpdate;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.common.DateUtil;
+import org.apache.ranger.common.UserSessionBase;
+import org.apache.ranger.entity.XXDBBase;
+import org.apache.ranger.security.context.XAContextHolder;
+import org.apache.ranger.security.context.XASecurityContext;
+
+public class JPABeanCallbacks {
+ static final Logger logger = Logger.getLogger(JPABeanCallbacks.class);
+
+ @PrePersist
+ void onPrePersist(Object o) {
+ try {
+ if (o != null && o instanceof XXDBBase) {
+ XXDBBase entity = (XXDBBase) o;
+
+ entity.setUpdateTime(DateUtil.getUTCDate());
+
+ XASecurityContext context = XAContextHolder
+ .getSecurityContext();
+ if (context != null) {
+ UserSessionBase userSession = context.getUserSession();
+ if (userSession != null) {
+ entity.setAddedByUserId(userSession.getUserId());
+ entity.setUpdatedByUserId(userSession
+ .getUserId());
+ }
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug(
+ "Security context not found for this request. obj="
+ + o, new Throwable());
+ }
+ }
+ }
+ } catch (Throwable t) {
+ logger.error(t);
+ }
+
+ }
+
+ // @PostPersist
+ // void onPostPersist(Object o) {
+ // if (o != null && o instanceof MBase) {
+ // MBase entity = (MBase) o;
+ // if (logger.isDebugEnabled()) {
+ // logger.debug("DBChange.create:class=" + o.getClass().getName()
+ // + entity.getId());
+ // }
+ //
+ // }
+ // }
+
+ // @PostLoad void onPostLoad(Object o) {}
+
+ @PreUpdate
+ void onPreUpdate(Object o) {
+ try {
+ if (o != null && o instanceof XXDBBase) {
+ XXDBBase entity = (XXDBBase) o;
+ entity.setUpdateTime(DateUtil.getUTCDate());
+ }
+ } catch (Throwable t) {
+ logger.error(t);
+ }
+
+ }
+
+ // @PostUpdate
+ // void onPostUpdate(Object o) {
+ // }
+
+ // @PreRemove void onPreRemove(Object o) {}
+
+ // @PostRemove
+ // void onPostRemove(Object o) {
+ // }
+
+}
\ 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/view/VEnum.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/view/VEnum.java b/security-admin/src/main/java/org/apache/ranger/common/view/VEnum.java
new file mode 100644
index 0000000..9f31390
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/view/VEnum.java
@@ -0,0 +1,107 @@
+/*
+ * 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.view;
+
+import java.util.List;
+
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.apache.ranger.common.XACommonEnums;
+
+
+@XmlRootElement
+public class VEnum extends ViewBaseBean implements java.io.Serializable {
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * Name of the enum
+ */
+ protected String enumName;
+ /**
+ * List of elements for this enum
+ */
+ protected List<VEnumElement> elementList;
+
+ /**
+ * Default constructor. This will set all the attributes to default value.
+ */
+ public VEnum() {
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>enumName</b>. You
+ * cannot set null to the attribute.
+ *
+ * @param enumName
+ * Value to set member attribute <b>enumName</b>
+ */
+ public void setEnumName(String enumName) {
+ this.enumName = enumName;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>enumName</b>
+ *
+ * @return String - value of member attribute <b>enumName</b>.
+ */
+ public String getEnumName() {
+ return this.enumName;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>elementList</b>.
+ * You cannot set null to the attribute.
+ *
+ * @param elementList
+ * Value to set member attribute <b>elementList</b>
+ */
+ public void setElementList(List<VEnumElement> elementList) {
+ this.elementList = elementList;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>elementList</b>
+ *
+ * @return List<VEnumElement> - value of member attribute
+ * <b>elementList</b>.
+ */
+ public List<VEnumElement> getElementList() {
+ return this.elementList;
+ }
+
+ @Override
+ public int getMyClassType() {
+ return XACommonEnums.CLASS_TYPE_ENUM;
+ }
+
+ /**
+ * This return the bean content in string format
+ *
+ * @return formatedStr
+ */
+ public String toString() {
+ String str = "VEnum={";
+ str += super.toString();
+ str += "enumName={" + enumName + "} ";
+ str += "elementList={" + elementList + "} ";
+ str += "}";
+ return str;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/view/VEnumElement.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/view/VEnumElement.java b/security-admin/src/main/java/org/apache/ranger/common/view/VEnumElement.java
new file mode 100644
index 0000000..15f890d
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/view/VEnumElement.java
@@ -0,0 +1,166 @@
+/*
+ * 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.view;
+
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.apache.ranger.common.XACommonEnums;
+
+@XmlRootElement
+public class VEnumElement extends ViewBaseBean implements java.io.Serializable {
+ private static final long serialVersionUID = 1L;
+
+
+ /**
+ * Name of the element
+ */
+ protected String elementName;
+ /**
+ * Name of the enum
+ */
+ protected String enumName;
+ /**
+ * Value of the element
+ */
+ protected int elementValue;
+ /**
+ * Label for the element
+ */
+ protected String elementLabel;
+ /**
+ * Resource bundle key
+ */
+ protected String rbKey;
+
+ /**
+ * Default constructor. This will set all the attributes to default value.
+ */
+ public VEnumElement ( ) {
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>elementName</b>.
+ * You cannot set null to the attribute.
+ * @param elementName Value to set member attribute <b>elementName</b>
+ */
+ public void setElementName( String elementName ) {
+ this.elementName = elementName;
+ }
+
+
+
+ /**
+ * @return the elementName
+ */
+ public String getElementName() {
+ return elementName;
+ }
+
+ /**
+ * @return the enumName
+ */
+ public String getEnumName() {
+ return enumName;
+ }
+
+ /**
+ * @return the rbKey
+ */
+ public String getRbKey() {
+ return rbKey;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>enumName</b>.
+ * You cannot set null to the attribute.
+ * @param enumName Value to set member attribute <b>enumName</b>
+ */
+ public void setEnumName( String enumName ) {
+ this.enumName = enumName;
+ }
+
+
+
+ /**
+ * This method sets the value to the member attribute <b>elementValue</b>.
+ * You cannot set null to the attribute.
+ * @param elementValue Value to set member attribute <b>elementValue</b>
+ */
+ public void setElementValue( int elementValue ) {
+ this.elementValue = elementValue;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>elementValue</b>
+ * @return int - value of member attribute <b>elementValue</b>.
+ */
+ public int getElementValue( ) {
+ return this.elementValue;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>elementLabel</b>.
+ * You cannot set null to the attribute.
+ * @param elementLabel Value to set member attribute <b>elementLabel</b>
+ */
+ public void setElementLabel( String elementLabel ) {
+ this.elementLabel = elementLabel;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>elementLabel</b>
+ * @return String - value of member attribute <b>elementLabel</b>.
+ */
+ public String getElementLabel( ) {
+ return this.elementLabel;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>rbKey</b>.
+ * You cannot set null to the attribute.
+ * @param rbKey Value to set member attribute <b>rbKey</b>
+ */
+ public void setRbKey( String rbKey ) {
+ this.rbKey = rbKey;
+ }
+
+
+
+ @Override
+ public int getMyClassType( ) {
+ return XACommonEnums.CLASS_TYPE_ENUM_ELEMENT;
+ }
+
+ /**
+ * This return the bean content in string format
+ * @return formatedStr
+ */
+ public String toString( ) {
+ String str = "VEnumElement={";
+ str += super.toString();
+ str += "elementName={" + elementName + "} ";
+ str += "enumName={" + enumName + "} ";
+ str += "elementValue={" + elementValue + "} ";
+ str += "elementLabel={" + elementLabel + "} ";
+ str += "rbKey={" + rbKey + "} ";
+ str += "}";
+ return str;
+ }
+}
[24/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/AppConstants.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/AppConstants.java b/security-admin/src/main/java/com/xasecure/common/AppConstants.java
deleted file mode 100644
index c4e5991..0000000
--- a/security-admin/src/main/java/com/xasecure/common/AppConstants.java
+++ /dev/null
@@ -1,954 +0,0 @@
-/*
- * 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 com.xasecure.common;
-
-import java.util.*;
-import com.xasecure.common.*;
-
-public class AppConstants extends XACommonEnums {
-
- /***************************************************************
- * Enum values for AssetType
- **************************************************************/
- /**
- * ASSET_UNKNOWN is an element of enum AssetType. Its value is "ASSET_UNKNOWN".
- */
- public static final int ASSET_UNKNOWN = 0;
- /**
- * ASSET_HDFS is an element of enum AssetType. Its value is "ASSET_HDFS".
- */
- public static final int ASSET_HDFS = 1;
- /**
- * ASSET_HBASE is an element of enum AssetType. Its value is "ASSET_HBASE".
- */
- public static final int ASSET_HBASE = 2;
- /**
- * ASSET_HIVE is an element of enum AssetType. Its value is "ASSET_HIVE".
- */
- public static final int ASSET_HIVE = 3;
-
- /**
- * enum XAAGENT is reserved for internal use
- */
- public static final int XAAGENT = 4 ;
- /**
- * ASSET_KNOX is an element of enum AssetType. Its value is "ASSET_KNOX".
- */
- public static final int ASSET_KNOX = 5;
- /**
- * ASSET_STORM is an element of enum AssetType. Its value is "ASSET_STORM".
- */
- public static final int ASSET_STORM = 6;
-
- /**
- * Max value for enum AssetType_MAX
- */
- public static final int AssetType_MAX = 6;
-
- /***************************************************************
- * Enum values for PolicyType
- **************************************************************/
- /**
- * POLICY_INCLUSION is an element of enum PolicyType. Its value is "POLICY_INCLUSION".
- */
- public static final int POLICY_INCLUSION = 0;
- /**
- * POLICY_EXCLUSION is an element of enum PolicyType. Its value is "POLICY_EXCLUSION".
- */
- public static final int POLICY_EXCLUSION = 1;
-
- /***************************************************************
- * Enum values for XAAuditType
- **************************************************************/
- /**
- * XA_AUDIT_TYPE_UNKNOWN is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_UNKNOWN".
- */
- public static final int XA_AUDIT_TYPE_UNKNOWN = 0;
- /**
- * XA_AUDIT_TYPE_ALL is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_ALL".
- */
- public static final int XA_AUDIT_TYPE_ALL = 1;
- /**
- * XA_AUDIT_TYPE_READ is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_READ".
- */
- public static final int XA_AUDIT_TYPE_READ = 2;
- /**
- * XA_AUDIT_TYPE_WRITE is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_WRITE".
- */
- public static final int XA_AUDIT_TYPE_WRITE = 3;
- /**
- * XA_AUDIT_TYPE_CREATE is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_CREATE".
- */
- public static final int XA_AUDIT_TYPE_CREATE = 4;
- /**
- * XA_AUDIT_TYPE_DELETE is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_DELETE".
- */
- public static final int XA_AUDIT_TYPE_DELETE = 5;
- /**
- * XA_AUDIT_TYPE_LOGIN is an element of enum XAAuditType. Its value is "XA_AUDIT_TYPE_LOGIN".
- */
- public static final int XA_AUDIT_TYPE_LOGIN = 6;
-
- /**
- * Max value for enum XAAuditType_MAX
- */
- public static final int XAAuditType_MAX = 6;
-
-
- /***************************************************************
- * Enum values for ResourceType
- **************************************************************/
- /**
- * RESOURCE_UNKNOWN is an element of enum ResourceType. Its value is "RESOURCE_UNKNOWN".
- */
- public static final int RESOURCE_UNKNOWN = 0;
- /**
- * RESOURCE_PATH is an element of enum ResourceType. Its value is "RESOURCE_PATH".
- */
- public static final int RESOURCE_PATH = 1;
- /**
- * RESOURCE_DB is an element of enum ResourceType. Its value is "RESOURCE_DB".
- */
- public static final int RESOURCE_DB = 2;
- /**
- * RESOURCE_TABLE is an element of enum ResourceType. Its value is "RESOURCE_TABLE".
- */
- public static final int RESOURCE_TABLE = 3;
- /**
- * RESOURCE_COL_FAM is an element of enum ResourceType. Its value is "RESOURCE_COL_FAM".
- */
- public static final int RESOURCE_COL_FAM = 4;
- /**
- * RESOURCE_COLUMN is an element of enum ResourceType. Its value is "RESOURCE_COLUMN".
- */
- public static final int RESOURCE_COLUMN = 5;
- /**
- * RESOURCE_VIEW is an element of enum ResourceType. Its value is "RESOURCE_VIEW".
- */
- public static final int RESOURCE_VIEW = 6;
- /**
- * RESOURCE_UDF is an element of enum ResourceType. Its value is "RESOURCE_UDF".
- */
- public static final int RESOURCE_UDF = 7;
- /**
- * RESOURCE_VIEW_COL is an element of enum ResourceType. Its value is "RESOURCE_VIEW_COL".
- */
- public static final int RESOURCE_VIEW_COL = 8;
- /**
- * RESOURCE_TOPOLOGY is an element of enum ResourceType. Its value is "RESOURCE_TOPOLOGY".
- */
- public static final int RESOURCE_TOPOLOGY = 9;
- /**
- * RESOURCE_SERVICE_NAME is an element of enum ResourceType. Its value is "RESOURCE_SERVICE_NAME".
- */
- public static final int RESOURCE_SERVICE_NAME = 10;
-
- /**
- * Max value for enum ResourceType_MAX
- */
- public static final int ResourceType_MAX = 10;
-
-
- /***************************************************************
- * Enum values for XAGroupType
- **************************************************************/
- /**
- * XA_GROUP_UNKNOWN is an element of enum XAGroupType. Its value is "XA_GROUP_UNKNOWN".
- */
- public static final int XA_GROUP_UNKNOWN = 0;
- /**
- * XA_GROUP_USER is an element of enum XAGroupType. Its value is "XA_GROUP_USER".
- */
- public static final int XA_GROUP_USER = 1;
- /**
- * XA_GROUP_GROUP is an element of enum XAGroupType. Its value is "XA_GROUP_GROUP".
- */
- public static final int XA_GROUP_GROUP = 2;
- /**
- * XA_GROUP_ROLE is an element of enum XAGroupType. Its value is "XA_GROUP_ROLE".
- */
- public static final int XA_GROUP_ROLE = 3;
-
- /**
- * Max value for enum XAGroupType_MAX
- */
- public static final int XAGroupType_MAX = 3;
-
-
- /***************************************************************
- * Enum values for XAPermForType
- **************************************************************/
- /**
- * XA_PERM_FOR_UNKNOWN is an element of enum XAPermForType. Its value is "XA_PERM_FOR_UNKNOWN".
- */
- public static final int XA_PERM_FOR_UNKNOWN = 0;
- /**
- * XA_PERM_FOR_USER is an element of enum XAPermForType. Its value is "XA_PERM_FOR_USER".
- */
- public static final int XA_PERM_FOR_USER = 1;
- /**
- * XA_PERM_FOR_GROUP is an element of enum XAPermForType. Its value is "XA_PERM_FOR_GROUP".
- */
- public static final int XA_PERM_FOR_GROUP = 2;
-
- /**
- * Max value for enum XAPermForType_MAX
- */
- public static final int XAPermForType_MAX = 2;
-
-
- /***************************************************************
- * Enum values for XAPermType
- **************************************************************/
- /**
- * XA_PERM_TYPE_UNKNOWN is an element of enum XAPermType. Its value is "XA_PERM_TYPE_UNKNOWN".
- */
- public static final int XA_PERM_TYPE_UNKNOWN = 0;
- /**
- * XA_PERM_TYPE_RESET is an element of enum XAPermType. Its value is "XA_PERM_TYPE_RESET".
- */
- public static final int XA_PERM_TYPE_RESET = 1;
- /**
- * XA_PERM_TYPE_READ is an element of enum XAPermType. Its value is "XA_PERM_TYPE_READ".
- */
- public static final int XA_PERM_TYPE_READ = 2;
- /**
- * XA_PERM_TYPE_WRITE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_WRITE".
- */
- public static final int XA_PERM_TYPE_WRITE = 3;
- /**
- * XA_PERM_TYPE_CREATE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_CREATE".
- */
- public static final int XA_PERM_TYPE_CREATE = 4;
- /**
- * XA_PERM_TYPE_DELETE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_DELETE".
- */
- public static final int XA_PERM_TYPE_DELETE = 5;
- /**
- * XA_PERM_TYPE_ADMIN is an element of enum XAPermType. Its value is "XA_PERM_TYPE_ADMIN".
- */
- public static final int XA_PERM_TYPE_ADMIN = 6;
- /**
- * XA_PERM_TYPE_OBFUSCATE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_OBFUSCATE".
- */
- public static final int XA_PERM_TYPE_OBFUSCATE = 7;
- /**
- * XA_PERM_TYPE_MASK is an element of enum XAPermType. Its value is "XA_PERM_TYPE_MASK".
- */
- public static final int XA_PERM_TYPE_MASK = 8;
- /**
- * XA_PERM_TYPE_EXECUTE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_EXECUTE".
- */
- public static final int XA_PERM_TYPE_EXECUTE = 9;
- /**
- * XA_PERM_TYPE_SELECT is an element of enum XAPermType. Its value is "XA_PERM_TYPE_SELECT".
- */
- public static final int XA_PERM_TYPE_SELECT = 10;
- /**
- * XA_PERM_TYPE_UPDATE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_UPDATE".
- */
- public static final int XA_PERM_TYPE_UPDATE = 11;
- /**
- * XA_PERM_TYPE_DROP is an element of enum XAPermType. Its value is "XA_PERM_TYPE_DROP".
- */
- public static final int XA_PERM_TYPE_DROP = 12;
- /**
- * XA_PERM_TYPE_ALTER is an element of enum XAPermType. Its value is "XA_PERM_TYPE_ALTER".
- */
- public static final int XA_PERM_TYPE_ALTER = 13;
- /**
- * XA_PERM_TYPE_INDEX is an element of enum XAPermType. Its value is "XA_PERM_TYPE_INDEX".
- */
- public static final int XA_PERM_TYPE_INDEX = 14;
- /**
- * XA_PERM_TYPE_LOCK is an element of enum XAPermType. Its value is "XA_PERM_TYPE_LOCK".
- */
- public static final int XA_PERM_TYPE_LOCK = 15;
- /**
- * XA_PERM_TYPE_ALL is an element of enum XAPermType. Its value is "XA_PERM_TYPE_ALL".
- */
- public static final int XA_PERM_TYPE_ALL = 16;
- /**
- * XA_PERM_TYPE_ALLOW is an element of enum XAPermType. Its value is "XA_PERM_TYPE_ALLOW".
- */
- public static final int XA_PERM_TYPE_ALLOW = 17;
- /**
- * XA_PERM_TYPE_SUBMIT_TOPOLOGY is an element of enum XAPermType. Its value is "XA_PERM_TYPE_SUBMIT_TOPOLOGY".
- */
- public static final int XA_PERM_TYPE_SUBMIT_TOPOLOGY = 18;
- /**
- * XA_PERM_TYPE_FILE_UPLOAD is an element of enum XAPermType. Its value is "XA_PERM_TYPE_FILE_UPLOAD".
- */
- public static final int XA_PERM_TYPE_FILE_UPLOAD = 19;
- /**
- * XA_PERM_TYPE_GET_NIMBUS is an element of enum XAPermType. Its value is "XA_PERM_TYPE_GET_NIMBUS".
- */
- public static final int XA_PERM_TYPE_GET_NIMBUS = 20;
- /**
- * XA_PERM_TYPE_GET_CLUSTER_INFO is an element of enum XAPermType. Its value is "XA_PERM_TYPE_GET_CLUSTER_INFO".
- */
- public static final int XA_PERM_TYPE_GET_CLUSTER_INFO = 21;
- /**
- * XA_PERM_TYPE_FILE_DOWNLOAD is an element of enum XAPermType. Its value is "XA_PERM_TYPE_FILE_DOWNLOAD".
- */
- public static final int XA_PERM_TYPE_FILE_DOWNLOAD = 22;
- /**
- * XA_PERM_TYPE_KILL_TOPOLOGY is an element of enum XAPermType. Its value is "XA_PERM_TYPE_KILL_TOPOLOGY".
- */
- public static final int XA_PERM_TYPE_KILL_TOPOLOGY = 23;
- /**
- * XA_PERM_TYPE_REBALANCE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_REBALANCE".
- */
- public static final int XA_PERM_TYPE_REBALANCE = 24;
- /**
- * XA_PERM_TYPE_ACTIVATE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_ACTIVATE".
- */
- public static final int XA_PERM_TYPE_ACTIVATE = 25;
- /**
- * XA_PERM_TYPE_DEACTIVATE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_DEACTIVATE".
- */
- public static final int XA_PERM_TYPE_DEACTIVATE = 26;
- /**
- * XA_PERM_TYPE_GET_TOPOLOGY_CONF is an element of enum XAPermType. Its value is "XA_PERM_TYPE_GET_TOPOLOGY_CONF".
- */
- public static final int XA_PERM_TYPE_GET_TOPOLOGY_CONF = 27;
- /**
- * XA_PERM_TYPE_GET_TOPOLOGY is an element of enum XAPermType. Its value is "XA_PERM_TYPE_GET_TOPOLOGY".
- */
- public static final int XA_PERM_TYPE_GET_TOPOLOGY = 28;
- /**
- * XA_PERM_TYPE_GET_USER_TOPOLOGY is an element of enum XAPermType. Its value is "XA_PERM_TYPE_GET_USER_TOPOLOGY".
- */
- public static final int XA_PERM_TYPE_GET_USER_TOPOLOGY = 29;
- /**
- * XA_PERM_TYPE_GET_TOPOLOGY_INFO is an element of enum XAPermType. Its value is "XA_PERM_TYPE_GET_TOPOLOGY_INFO".
- */
- public static final int XA_PERM_TYPE_GET_TOPOLOGY_INFO = 30;
- /**
- * XA_PERM_TYPE_UPLOAD_NEW_CREDENTIAL is an element of enum XAPermType. Its value is "XA_PERM_TYPE_UPLOAD_NEW_CREDENTIAL".
- */
- public static final int XA_PERM_TYPE_UPLOAD_NEW_CREDENTIAL = 31;
-
- /**
- * Max value for enum XAPermType_MAX
- */
- public static final int XAPermType_MAX = 31;
-
- /***************************************************************
- * Enum values for DatabaseFavor
- **************************************************************/
- /**
- * DB Favor Unknown
- */
- public static final int DB_FLAVOR_UNKNOWN = 0;
- /**
- * DB Favor MySql
- */
- public static final int DB_FLAVOR_MYSQL = 1;
- /**
- * DB Favor Oracle
- */
- public static final int DB_FLAVOR_ORACLE = 2;
-
-
- /***************************************************************
- * Enum values for ClassTypes
- **************************************************************/
- /**
- * CLASS_TYPE_XA_ASSET is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_ASSET".
- */
- public static final int CLASS_TYPE_XA_ASSET = 1000;
- /**
- * CLASS_TYPE_XA_RESOURCE is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_RESOURCE".
- */
- public static final int CLASS_TYPE_XA_RESOURCE = 1001;
- /**
- * CLASS_TYPE_XA_GROUP is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_GROUP".
- */
- public static final int CLASS_TYPE_XA_GROUP = 1002;
- /**
- * CLASS_TYPE_XA_USER is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_USER".
- */
- public static final int CLASS_TYPE_XA_USER = 1003;
- /**
- * CLASS_TYPE_XA_GROUP_USER is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_GROUP_USER".
- */
- public static final int CLASS_TYPE_XA_GROUP_USER = 1004;
- /**
- * CLASS_TYPE_XA_GROUP_GROUP is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_GROUP_GROUP".
- */
- public static final int CLASS_TYPE_XA_GROUP_GROUP = 1005;
- /**
- * CLASS_TYPE_XA_PERM_MAP is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_PERM_MAP".
- */
- public static final int CLASS_TYPE_XA_PERM_MAP = 1006;
- /**
- * CLASS_TYPE_XA_AUDIT_MAP is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_AUDIT_MAP".
- */
- public static final int CLASS_TYPE_XA_AUDIT_MAP = 1007;
- /**
- * CLASS_TYPE_XA_CRED_STORE is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_CRED_STORE".
- */
- public static final int CLASS_TYPE_XA_CRED_STORE = 1008;
- /**
- * CLASS_TYPE_XA_COMN_REF is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_COMN_REF".
- */
- public static final int CLASS_TYPE_XA_COMN_REF = 1009;
- /**
- * CLASS_TYPE_XA_LICENSE is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_LICENSE".
- */
- public static final int CLASS_TYPE_XA_LICENSE = 1010;
- /**
- * CLASS_TYPE_XA_POLICY_EXPORT_AUDIT is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_POLICY_EXPORT_AUDIT".
- */
- public static final int CLASS_TYPE_XA_POLICY_EXPORT_AUDIT = 1011;
- /**
- * CLASS_TYPE_TRX_LOG is an element of enum ClassTypes. Its value is "CLASS_TYPE_TRX_LOG".
- */
- public static final int CLASS_TYPE_TRX_LOG = 1012;
- /**
- * CLASS_TYPE_XA_ACCESS_AUDIT is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_ACCESS_AUDIT".
- */
- public static final int CLASS_TYPE_XA_ACCESS_AUDIT = 1013;
- /**
- * CLASS_TYPE_XA_TRANSACTION_LOG_ATTRIBUTE is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_TRANSACTION_LOG_ATTRIBUTE".
- */
- public static final int CLASS_TYPE_XA_TRANSACTION_LOG_ATTRIBUTE = 1014;
-
- /**
- * Max value for enum ClassTypes_MAX
- */
- public static final int ClassTypes_MAX = 1014;
-
-
-
- static public String getLabelFor_AssetType( int elementValue ) {
- if( elementValue == 0 ) {
- return "Unknown"; //ASSET_UNKNOWN
- }
- if( elementValue == 1 ) {
- return "HDFS"; //ASSET_HDFS
- }
- if( elementValue == 2 ) {
- return "HBase"; //ASSET_HBASE
- }
- if( elementValue == 3 ) {
- return "Hive"; //ASSET_HIVE
- }
- if( elementValue == 4 ) {
- return "XAAGENT"; // XAAGENT
- }
- if( elementValue == 5 ) {
- return "Knox"; //ASSET_KNOX
- }
- if( elementValue == 6 ) {
- return "Storm"; //ASSET_STORM
- }
- return null;
- }
-
- static public String getLabelFor_PolicyType( int elementValue ) {
- if( elementValue == 0 ) {
- return "Inclusion"; //POLICY_INCLUSION
- }
- if( elementValue == 1 ) {
- return "Exclusion"; //POLICY_EXCLUSION
- }
- return null;
- }
-
- static public String getLabelFor_XAAuditType( int elementValue ) {
- if( elementValue == 0 ) {
- return "Unknown"; //XA_AUDIT_TYPE_UNKNOWN
- }
- if( elementValue == 1 ) {
- return "All"; //XA_AUDIT_TYPE_ALL
- }
- if( elementValue == 2 ) {
- return "Read"; //XA_AUDIT_TYPE_READ
- }
- if( elementValue == 3 ) {
- return "Write"; //XA_AUDIT_TYPE_WRITE
- }
- if( elementValue == 4 ) {
- return "Create"; //XA_AUDIT_TYPE_CREATE
- }
- if( elementValue == 5 ) {
- return "Delete"; //XA_AUDIT_TYPE_DELETE
- }
- if( elementValue == 6 ) {
- return "Login"; //XA_AUDIT_TYPE_LOGIN
- }
- return null;
- }
-
- static public String getLabelFor_ResourceType( int elementValue ) {
- if( elementValue == 0 ) {
- return "Unknown"; //RESOURCE_UNKNOWN
- }
- if( elementValue == 1 ) {
- return "Path"; //RESOURCE_PATH
- }
- if( elementValue == 2 ) {
- return "Database"; //RESOURCE_DB
- }
- if( elementValue == 3 ) {
- return "Table"; //RESOURCE_TABLE
- }
- if( elementValue == 4 ) {
- return "Column Family"; //RESOURCE_COL_FAM
- }
- if( elementValue == 5 ) {
- return "Column"; //RESOURCE_COLUMN
- }
- if( elementValue == 6 ) {
- return "VIEW"; //RESOURCE_VIEW
- }
- if( elementValue == 7 ) {
- return "UDF"; //RESOURCE_UDF
- }
- if( elementValue == 8 ) {
- return "View Column"; //RESOURCE_VIEW_COL
- }
- if( elementValue == 9 ) {
- return "Topology"; //RESOURCE_TOPOLOGY
- }
- if( elementValue == 10 ) {
- return "Service"; //RESOURCE_SERVICE
- }
- return null;
- }
-
- static public String getLabelFor_XAGroupType( int elementValue ) {
- if( elementValue == 0 ) {
- return "Unknown"; //XA_GROUP_UNKNOWN
- }
- if( elementValue == 1 ) {
- return "User"; //XA_GROUP_USER
- }
- if( elementValue == 2 ) {
- return "Group"; //XA_GROUP_GROUP
- }
- if( elementValue == 3 ) {
- return "Role"; //XA_GROUP_ROLE
- }
- return null;
- }
-
- static public String getLabelFor_XAPermForType( int elementValue ) {
- if( elementValue == 0 ) {
- return "Unknown"; //XA_PERM_FOR_UNKNOWN
- }
- if( elementValue == 1 ) {
- return "Permission for Users"; //XA_PERM_FOR_USER
- }
- if( elementValue == 2 ) {
- return "Permission for Groups"; //XA_PERM_FOR_GROUP
- }
- return null;
- }
-
- static public String getLabelFor_XAPermType( int elementValue ) {
- if( elementValue == 0 ) {
- return "Unknown"; //XA_PERM_TYPE_UNKNOWN
- }
- if( elementValue == 1 ) {
- return "Reset"; //XA_PERM_TYPE_RESET
- }
- if( elementValue == 2 ) {
- return "Read"; //XA_PERM_TYPE_READ
- }
- if( elementValue == 3 ) {
- return "Write"; //XA_PERM_TYPE_WRITE
- }
- if( elementValue == 4 ) {
- return "Create"; //XA_PERM_TYPE_CREATE
- }
- if( elementValue == 5 ) {
- return "Delete"; //XA_PERM_TYPE_DELETE
- }
- if( elementValue == 6 ) {
- return "Admin"; //XA_PERM_TYPE_ADMIN
- }
- if( elementValue == 7 ) {
- return "Obfuscate"; //XA_PERM_TYPE_OBFUSCATE
- }
- if( elementValue == 8 ) {
- return "Mask"; //XA_PERM_TYPE_MASK
- }
- if( elementValue == 9 ) {
- return "Execute"; //XA_PERM_TYPE_EXECUTE
- }
- if( elementValue == 10 ) {
- return "Select"; //XA_PERM_TYPE_SELECT
- }
- if( elementValue == 11 ) {
- return "Update"; //XA_PERM_TYPE_UPDATE
- }
- if( elementValue == 12 ) {
- return "Drop"; //XA_PERM_TYPE_DROP
- }
- if( elementValue == 13 ) {
- return "Alter"; //XA_PERM_TYPE_ALTER
- }
- if( elementValue == 14 ) {
- return "Index"; //XA_PERM_TYPE_INDEX
- }
- if( elementValue == 15 ) {
- return "Lock"; //XA_PERM_TYPE_LOCK
- }
- if( elementValue == 16 ) {
- return "All"; //XA_PERM_TYPE_ALL
- }
- if( elementValue == 17 ) {
- return "Allow"; //XA_PERM_TYPE_ALLOW
- }
- if( elementValue == 18 ) {
- // return "Submit Topology"; //XA_PERM_TYPE_SUBMIT_TOPOLOGY
- return "submitTopology" ;
- }
- if( elementValue == 19 ) {
- // return "File Upload"; //XA_PERM_TYPE_FILE_UPLOAD
- return "fileUpload" ;
- }
- if( elementValue == 20 ) {
- // return "Get Nimbus Conf"; //XA_PERM_TYPE_GET_NIMBUS
- return "getNimbusConf" ;
- }
- if( elementValue == 21 ) {
- // return "Get Cluster Info"; //XA_PERM_TYPE_GET_CLUSTER_INFO
- return "getClusterInfo" ;
- }
- if( elementValue == 22 ) {
- // return "File Download"; //XA_PERM_TYPE_FILE_DOWNLOAD
- return "fileDownload" ;
- }
- if( elementValue == 23 ) {
- // return "Kill Topology"; //XA_PERM_TYPE_KILL_TOPOLOGY
- return "killTopology" ;
- }
- if( elementValue == 24 ) {
- // return "Rebalance"; //XA_PERM_TYPE_REBALANCE
- return "rebalance" ;
- }
- if( elementValue == 25 ) {
- // return "Activate"; //XA_PERM_TYPE_ACTIVATE
- return "activate" ;
- }
- if( elementValue == 26 ) {
- // return "Deactivate"; //XA_PERM_TYPE_DEACTIVATE
- return "deactivate" ;
- }
- if( elementValue == 27 ) {
- // return "Get Topology Conf"; //XA_PERM_TYPE_GET_TOPOLOGY_CONF
- return "getTopologyConf" ;
- }
- if( elementValue == 28 ) {
- // return "Get Topology"; //XA_PERM_TYPE_GET_TOPOLOGY
- return "getTopology" ;
- }
- if( elementValue == 29 ) {
- // return "Get User Topology"; //XA_PERM_TYPE_GET_USER_TOPOLOGY
- return "getUserTopology" ;
- }
- if( elementValue == 30 ) {
- // return "Get Topology Info"; //XA_PERM_TYPE_GET_TOPOLOGY_INFO
- return "getTopologyInfo" ;
- }
- if( elementValue == 31 ) {
- // return "Upload New Credential"; //XA_PERM_TYPE_UPLOAD_NEW_CREDENTIAL
- return "uploadNewCredentials" ;
- }
- return null;
- }
-
- static public String getLabelFor_ClassTypes( int elementValue ) {
- if( elementValue == 1000 ) {
- return "Asset"; //CLASS_TYPE_XA_ASSET
- }
- if( elementValue == 1001 ) {
- return "Resource"; //CLASS_TYPE_XA_RESOURCE
- }
- if( elementValue == 1002 ) {
- return "XA Group"; //CLASS_TYPE_XA_GROUP
- }
- if( elementValue == 1003 ) {
- return "XA User"; //CLASS_TYPE_XA_USER
- }
- if( elementValue == 1004 ) {
- return "XA Group of Users"; //CLASS_TYPE_XA_GROUP_USER
- }
- if( elementValue == 1005 ) {
- return "XA Group of groups"; //CLASS_TYPE_XA_GROUP_GROUP
- }
- if( elementValue == 1006 ) {
- return "XA permissions for resource"; //CLASS_TYPE_XA_PERM_MAP
- }
- if( elementValue == 1007 ) {
- return "XA audits for resource"; //CLASS_TYPE_XA_AUDIT_MAP
- }
- if( elementValue == 1008 ) {
- return "XA credential store"; //CLASS_TYPE_XA_CRED_STORE
- }
- if( elementValue == 1009 ) {
- return "XA Common Reference"; //CLASS_TYPE_XA_COMN_REF
- }
- if( elementValue == 1010 ) {
- return "XA License"; //CLASS_TYPE_XA_LICENSE
- }
- if( elementValue == 1011 ) {
- return "XA Policy Export Audit"; //CLASS_TYPE_XA_POLICY_EXPORT_AUDIT
- }
- if( elementValue == 1012 ) {
- return "Transaction log"; //CLASS_TYPE_TRX_LOG
- }
- if( elementValue == 1013 ) {
- return "Access Audit"; //CLASS_TYPE_XA_ACCESS_AUDIT
- }
- return null;
- }
-
- static public int getEnumFor_AssetType(String label) {
- if (label == null) {
- return 0;
- }
- if (label.equalsIgnoreCase("Unknown")) {
- return AppConstants.ASSET_UNKNOWN; // ASSET_UNKNOWN
- }
- if (label.equalsIgnoreCase("HDFS")) {
- return AppConstants.ASSET_HDFS; // ASSET_HDFS
- }
- if (label.equalsIgnoreCase("HBase")) {
- return AppConstants.ASSET_HBASE; // ASSET_HBASE
- }
- if (label.equalsIgnoreCase("Hive")) {
- return AppConstants.ASSET_HIVE; // ASSET_HIVE
- }
- if (label.equalsIgnoreCase("Knox")) {
- return AppConstants.ASSET_KNOX; // ASSET_KNOX
- }
- if (label.equalsIgnoreCase("Storm")) {
- return AppConstants.ASSET_STORM; // ASSET_STORM
- }
- return 0;
- }
-
- static public int getEnumFor_BooleanValue(boolean label) {
- if (label) {
- return AppConstants.BOOL_TRUE;
- } else {
- return AppConstants.BOOL_FALSE;
- }
- }
-
- static public boolean getBooleanFor_BooleanValue(int elementValue) {
- if (elementValue == 1) {
- return true;
- }
- if (elementValue == 2) {
- return false;
- }
- return false;
- }
-
- static public int getEnumFor_ResourceType(String label) {
- if (label == null) {
- return 0;
- }
- if (label.equalsIgnoreCase("Unknown")) {
- return AppConstants.RESOURCE_UNKNOWN; // RESOURCE_UNKNOWN
- }
- if (label.equalsIgnoreCase("Path")) {
- return AppConstants.RESOURCE_PATH; // RESOURCE_PATH
- }
- if (label.equalsIgnoreCase("Database")) {
- return AppConstants.RESOURCE_DB; // RESOURCE_DB
- }
- if (label.equalsIgnoreCase("Table")) {
- return AppConstants.RESOURCE_TABLE; // RESOURCE_TABLE
- }
- if (label.equalsIgnoreCase("Column Family")) {
- return AppConstants.RESOURCE_COL_FAM; // RESOURCE_COL_FAM
- }
- if (label.equalsIgnoreCase("Column")) {
- return AppConstants.RESOURCE_COLUMN; // RESOURCE_COLUMN
- }
- if (label.equalsIgnoreCase("VIEW")) {
- return AppConstants.RESOURCE_VIEW; // RESOURCE_VIEW
- }
- if (label.equalsIgnoreCase("UDF")) {
- return AppConstants.RESOURCE_UDF; // RESOURCE_UDF
- }
- if (label.equalsIgnoreCase("View Column")) {
- return AppConstants.RESOURCE_VIEW_COL; // RESOURCE_VIEW_COL
- }
- if (label.equalsIgnoreCase("Topology")) {
- return AppConstants.RESOURCE_TOPOLOGY; // RESOURCE_TOPOLOGY
- }
- if (label.equalsIgnoreCase("Service")) {
- return AppConstants.RESOURCE_SERVICE_NAME; // RESOURCE_SERVICE_NAME
- }
- return 0;
- }
-
- static public int getEnumFor_XAPermType(String label) {
- if (label == null) {
- return 0;
- }
- if (label.equalsIgnoreCase("Unknown")) {
- return AppConstants.XA_PERM_TYPE_UNKNOWN; // XA_PERM_TYPE_UNKNOWN
- }
- if (label.equalsIgnoreCase("Reset")) {
- return AppConstants.XA_PERM_TYPE_RESET; // XA_PERM_TYPE_RESET
- }
- if (label.equalsIgnoreCase("Read")) {
- return AppConstants.XA_PERM_TYPE_READ; // XA_PERM_TYPE_READ
- }
- if (label.equalsIgnoreCase("Write")) {
- return AppConstants.XA_PERM_TYPE_WRITE; // XA_PERM_TYPE_WRITE
- }
- if (label.equalsIgnoreCase("Create")) {
- return AppConstants.XA_PERM_TYPE_CREATE; // XA_PERM_TYPE_CREATE
- }
- if (label.equalsIgnoreCase("Delete")) {
- return AppConstants.XA_PERM_TYPE_DELETE; // XA_PERM_TYPE_DELETE
- }
- if (label.equalsIgnoreCase("Admin")) {
- return AppConstants.XA_PERM_TYPE_ADMIN; // XA_PERM_TYPE_ADMIN
- }
- if (label.equalsIgnoreCase("Obfuscate")) {
- return AppConstants.XA_PERM_TYPE_OBFUSCATE; // XA_PERM_TYPE_OBFUSCATE
- }
- if (label.equalsIgnoreCase("Mask")) {
- return AppConstants.XA_PERM_TYPE_MASK; // XA_PERM_TYPE_MASK
- }
- if (label.equalsIgnoreCase("Execute")) {
- return AppConstants.XA_PERM_TYPE_EXECUTE; // XA_PERM_TYPE_EXECUTE
- }
- if (label.equalsIgnoreCase("Select")) {
- return AppConstants.XA_PERM_TYPE_SELECT; // XA_PERM_TYPE_SELECT
- }
- if (label.equalsIgnoreCase("Update")) {
- return AppConstants.XA_PERM_TYPE_UPDATE; // XA_PERM_TYPE_UPDATE
- }
- if (label.equalsIgnoreCase("Drop")) {
- return AppConstants.XA_PERM_TYPE_DROP; // XA_PERM_TYPE_DROP
- }
- if (label.equalsIgnoreCase("Alter")) {
- return AppConstants.XA_PERM_TYPE_ALTER; // XA_PERM_TYPE_ALTER
- }
- if (label.equalsIgnoreCase("Index")) {
- return AppConstants.XA_PERM_TYPE_INDEX; // XA_PERM_TYPE_INDEX
- }
- if (label.equalsIgnoreCase("Lock")) {
- return AppConstants.XA_PERM_TYPE_LOCK; // XA_PERM_TYPE_LOCK
- }
- if (label.equalsIgnoreCase("All")) {
- return AppConstants.XA_PERM_TYPE_ALL; // XA_PERM_TYPE_ALL
- }
- if(label.equalsIgnoreCase("Allow")) {
- return AppConstants.XA_PERM_TYPE_ALLOW; //XA_PERM_TYPE_ALLOW
- }
- if(label.equalsIgnoreCase("submitTopology")) {
- return AppConstants.XA_PERM_TYPE_SUBMIT_TOPOLOGY; //XA_PERM_TYPE_SUBMIT_TOPOLOGY
- }
- if(label.equalsIgnoreCase("fileUpload")) {
- return AppConstants.XA_PERM_TYPE_FILE_UPLOAD; //XA_PERM_TYPE_FILE_UPLOAD
- }
- if(label.equalsIgnoreCase("getNimbusConf")) {
- return AppConstants.XA_PERM_TYPE_GET_NIMBUS; //XA_PERM_TYPE_GET_NIMBUS
- }
- if(label.equalsIgnoreCase("getClusterInfo")) {
- return AppConstants.XA_PERM_TYPE_GET_CLUSTER_INFO; //XA_PERM_TYPE_GET_CLUSTER_INFO
- }
- if(label.equalsIgnoreCase("fileDownload")) {
- return AppConstants.XA_PERM_TYPE_FILE_DOWNLOAD; //XA_PERM_TYPE_FILE_DOWNLOAD
- }
- if(label.equalsIgnoreCase("killTopology")) {
- return AppConstants.XA_PERM_TYPE_KILL_TOPOLOGY; //XA_PERM_TYPE_KILL_TOPOLOGY
- }
- if(label.equalsIgnoreCase("rebalance")) {
- return AppConstants.XA_PERM_TYPE_REBALANCE; //XA_PERM_TYPE_REBALANCE
- }
- if(label.equalsIgnoreCase("activate")) {
- return AppConstants.XA_PERM_TYPE_ACTIVATE; //XA_PERM_TYPE_ACTIVATE
- }
- if(label.equalsIgnoreCase("deactivate")) {
- return AppConstants.XA_PERM_TYPE_DEACTIVATE; //XA_PERM_TYPE_DEACTIVATE
- }
- if(label.equalsIgnoreCase("getTopologyConf")) {
- return AppConstants.XA_PERM_TYPE_GET_TOPOLOGY_CONF; //XA_PERM_TYPE_GET_TOPOLOGY_CONF
- }
- if(label.equalsIgnoreCase("getTopology")) {
- return AppConstants.XA_PERM_TYPE_GET_TOPOLOGY; //XA_PERM_TYPE_GET_TOPOLOGY
- }
- if(label.equalsIgnoreCase("getUserTopology")) {
- return AppConstants.XA_PERM_TYPE_GET_USER_TOPOLOGY; //XA_PERM_TYPE_GET_USER_TOPOLOGY
- }
- if(label.equalsIgnoreCase("getTopologyInfo")) {
- return AppConstants.XA_PERM_TYPE_GET_TOPOLOGY_INFO; //XA_PERM_TYPE_GET_TOPOLOGY_INFO
- }
- if(label.equalsIgnoreCase("uploadNewCredentials")) {
- return AppConstants.XA_PERM_TYPE_UPLOAD_NEW_CREDENTIAL; //XA_PERM_TYPE_UPLOAD_NEW_CREDENTIAL
- }
- return 0;
- }
-
- static public int getEnumFor_PolicyType(String label) {
- if (label == null) {
- return 0;
- }
- if (label.equalsIgnoreCase("Inclusion")) {
- return AppConstants.POLICY_INCLUSION; // POLICY_INCLUSION
- }
- if (label.equalsIgnoreCase("Exclusion")) {
- return AppConstants.POLICY_EXCLUSION; // POLICY_EXCLUSION
- }
- return 0;
- }
-
- static public int getEnumFor_DatabaseFlavor(String label) {
- if (label == null) {
- return DB_FLAVOR_UNKNOWN; // DB_FLAVOR_UNKNOWN
- }
- if ("MYSQL".equalsIgnoreCase(label)) {
- return DB_FLAVOR_MYSQL; // DB_FLAVOR_MYSQL
- }
- if ("ORACLE".equalsIgnoreCase(label)) {
- return DB_FLAVOR_ORACLE; // DB_FLAVOR_ORACLE
- }
- return DB_FLAVOR_UNKNOWN;
- }
-
- static public String getLabelFor_DatabaseFlavor(int elementValue) {
- if (elementValue == DB_FLAVOR_UNKNOWN) {
- return "UNKNOWN"; // Unknown
- }
- if (elementValue == DB_FLAVOR_MYSQL) {
- return "MYSQL"; // MYSQL
- }
- if (elementValue == DB_FLAVOR_ORACLE) {
- return "ORACLE"; // ORACLE
- }
- return null;
- }
-
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/ContextUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/ContextUtil.java b/security-admin/src/main/java/com/xasecure/common/ContextUtil.java
deleted file mode 100644
index 610b86b..0000000
--- a/security-admin/src/main/java/com/xasecure/common/ContextUtil.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * 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 com.xasecure.common;
-
-import com.xasecure.security.context.XAContextHolder;
-import com.xasecure.security.context.XASecurityContext;
-
-public class ContextUtil {
-
- /**
- * Singleton class
- */
- private ContextUtil() {
- }
-
- public static Long getCurrentUserId() {
- XASecurityContext context = XAContextHolder.getSecurityContext();
- if (context != null) {
- UserSessionBase userSession = context.getUserSession();
- if (userSession != null) {
- return userSession.getUserId();
- }
- }
- return null;
- }
-
- public static String getCurrentUserPublicName() {
- XASecurityContext context = XAContextHolder.getSecurityContext();
- if (context != null) {
- UserSessionBase userSession = context.getUserSession();
- if (userSession != null) {
- return userSession.getXXPortalUser().getPublicScreenName();
- // return userSession.getGjUser().getPublicScreenName();
- }
- }
- return null;
- }
-
- public static UserSessionBase getCurrentUserSession() {
- UserSessionBase userSession = null;
- XASecurityContext context = XAContextHolder.getSecurityContext();
- if (context != null) {
- userSession = context.getUserSession();
- }
- return userSession;
- }
-
- public static RequestContext getCurrentRequestContext() {
- XASecurityContext context = XAContextHolder.getSecurityContext();
- if (context != null) {
- return context.getRequestContext();
- }
- return null;
- }
-
- public static String getCurrentUserLoginId() {
- XASecurityContext context = XAContextHolder.getSecurityContext();
- if (context != null) {
- UserSessionBase userSession = context.getUserSession();
- if (userSession != null) {
- return userSession.getLoginId();
- }
- }
- return null;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/DateUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/DateUtil.java b/security-admin/src/main/java/com/xasecure/common/DateUtil.java
deleted file mode 100644
index a5ebcaa..0000000
--- a/security-admin/src/main/java/com/xasecure/common/DateUtil.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * 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 com.xasecure.common;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.TimeZone;
-import org.springframework.stereotype.Component;
-
-
-@Component
-public class DateUtil {
-
- private static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT+0");
-
- public Date getDateFromNow(int days) {
- return getDateFromNow(days, 0, 0);
- }
-
- public Date getDateFromNow(int days, int hours, int minutes) {
- Calendar cal = Calendar.getInstance();
- cal.add(Calendar.DATE, days);
- cal.add(Calendar.HOUR, hours);
- cal.add(Calendar.MINUTE, minutes);
- return cal.getTime();
- }
-
- public static String dateToString(Date date, String dateFromat) {
- SimpleDateFormat formatter = new SimpleDateFormat(dateFromat);
- return formatter.format(date).toString();
- }
-
- public Date getDateFromGivenDate(Date date, int days, int hours,int minutes, int second) {
- Calendar cal = Calendar.getInstance();
- cal.setTime(date);
- cal.add(Calendar.DATE, days);
- cal.add(Calendar.HOUR, hours);
- cal.add(Calendar.MINUTE, minutes);
- cal.add(Calendar.SECOND, second);
- return cal.getTime();
- }
- /**
- * useful for converting client time zone Date to UTC Date
- * @param date
- * @param mins
- * @return
- */
- public Date addTimeOffset(Date date, int mins) {
- if (date == null) {
- return date;
- }
- long t = date.getTime();
- Date newDate = new Date(t + (mins * 60000));
- return newDate;
- }
-
-
- public static Date getUTCDate(){
- try{
- Calendar local=Calendar.getInstance();
- int offset = local.getTimeZone().getOffset(local.getTimeInMillis());
- GregorianCalendar utc = new GregorianCalendar(gmtTimeZone);
- utc.setTimeInMillis(local.getTimeInMillis());
- utc.add(Calendar.MILLISECOND, -offset);
- return utc.getTime();
- }catch(Exception ex){
- return null;
- }
- }
-
- public static Date getUTCDate(long epoh) {
- if(epoh==0){
- return null;
- }
- try{
- Calendar local=Calendar.getInstance();
- int offset = local.getTimeZone().getOffset(epoh);
- GregorianCalendar utc = new GregorianCalendar(gmtTimeZone);
- utc.setTimeInMillis(epoh);
- utc.add(Calendar.MILLISECOND, -offset);
- return utc.getTime();
- }catch(Exception ex){
- return null;
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/ErrorMessageUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/ErrorMessageUtil.java b/security-admin/src/main/java/com/xasecure/common/ErrorMessageUtil.java
deleted file mode 100644
index 44d3875..0000000
--- a/security-admin/src/main/java/com/xasecure/common/ErrorMessageUtil.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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 com.xasecure.common;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-
-import org.springframework.beans.BeansException;
-import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
-import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
-
-public class ErrorMessageUtil extends PropertyPlaceholderConfigurer {
- private static Map<String, String> messageMap;
-
- private ErrorMessageUtil() {
-
- }
-
- @Override
- protected void processProperties(
- ConfigurableListableBeanFactory beanFactory, Properties props)
- throws BeansException {
- super.processProperties(beanFactory, props);
-
- messageMap = new HashMap<String, String>();
- Set<Object> keySet = props.keySet();
-
- for (Object key : keySet) {
- String keyStr = key.toString();
- messageMap.put(keyStr, props.getProperty(keyStr));
- }
- }
-
-
- public static String getMessage(String key) {
- return messageMap.get(key);
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/GUIDUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/GUIDUtil.java b/security-admin/src/main/java/com/xasecure/common/GUIDUtil.java
deleted file mode 100644
index 6321c5c..0000000
--- a/security-admin/src/main/java/com/xasecure/common/GUIDUtil.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * 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 com.xasecure.common;
-
-import java.io.Serializable;
-import java.security.SecureRandom;
-
-public class GUIDUtil implements Serializable {
-
- private static final long serialVersionUID = -7284237762948427019L;
-
- static SecureRandom secureRandom = new SecureRandom();
- static int counter = 0;
-
- static public String genGUI() {
- return System.currentTimeMillis() + "_" + secureRandom.nextInt(1000)
- + "_" + counter++;
- }
-
- public static long genLong() {
- return secureRandom.nextLong();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/HTTPUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/HTTPUtil.java b/security-admin/src/main/java/com/xasecure/common/HTTPUtil.java
deleted file mode 100644
index 60bba8f..0000000
--- a/security-admin/src/main/java/com/xasecure/common/HTTPUtil.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * 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 com.xasecure.common;
-
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.springframework.stereotype.Component;
-
-@Component
-public class HTTPUtil {
-
- public static final String USER_AGENT = "User-Agent";
-
- public static final String IPHONE = "iPhone";
- public static final String IPAD = "iPad";
- public static final String IPOD = "iPod";
- public static final String ANDROID = "Android";
-
- public int getDeviceType(HttpServletRequest httpRequest) {
- return getDeviceType(httpRequest.getHeader(USER_AGENT));
-
- }
-
- public int getDeviceType(String userAgent) {
- if (userAgent == null) {
- return XACommonEnums.DEVICE_UNKNOWN;
- }
-
- if (userAgent.contains(IPHONE)) {
- return XACommonEnums.DEVICE_IPHONE;
- } else if (userAgent.contains(IPAD)) {
- return XACommonEnums.DEVICE_IPAD;
- } else if (userAgent.contains(IPOD)) {
- return XACommonEnums.DEVICE_IPOD;
- } else if (userAgent.contains(ANDROID)) {
- return XACommonEnums.DEVICE_ANDROID;
- } else {
- return XACommonEnums.DEVICE_BROWSER;
- }
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/JSONUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/JSONUtil.java b/security-admin/src/main/java/com/xasecure/common/JSONUtil.java
deleted file mode 100644
index bd7803f..0000000
--- a/security-admin/src/main/java/com/xasecure/common/JSONUtil.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * 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 com.xasecure.common;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-
-import com.xasecure.common.view.ViewBaseBean;
-
-import org.apache.log4j.Logger;
-import org.codehaus.jackson.JsonGenerationException;
-import org.codehaus.jackson.JsonParseException;
-import org.codehaus.jackson.map.JsonMappingException;
-import org.codehaus.jackson.map.ObjectMapper;
-import org.codehaus.jackson.type.TypeReference;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-@Component
-public class JSONUtil {
-
- @Autowired
- RESTErrorUtil restErrorUtil;
-
- static final Logger logger = Logger.getLogger(JSONUtil.class);
-
- public File writeJsonToFile(ViewBaseBean viewBean, String fileName)
- throws JsonGenerationException, JsonMappingException, IOException {
- ObjectMapper objectMapper = new ObjectMapper();
-
- if (fileName.length() < 3) {
- fileName = "file_" + fileName;
- }
-
- File file = File.createTempFile(fileName, ".json");
- objectMapper.defaultPrettyPrintingWriter().writeValue(file, viewBean);
-
- return file;
- }
-
- public Map<String, String> jsonToMap(String jsonStr) {
- if (jsonStr == null || jsonStr.isEmpty()) {
- return new HashMap<String, String>();
- }
-
- ObjectMapper mapper = new ObjectMapper();
- try {
- Map<String, String> tempObject = mapper.readValue(jsonStr,
- new TypeReference<Map<String, String>>() {
- });
- return tempObject;
-
- } catch (JsonParseException e) {
- throw restErrorUtil.createRESTException(
- "Invalid input data: " + e.getMessage(),
- MessageEnums.INVALID_INPUT_DATA);
- } catch (JsonMappingException e) {
- throw restErrorUtil.createRESTException(
- "Invalid input data: " + e.getMessage(),
- MessageEnums.INVALID_INPUT_DATA);
- } catch (IOException e) {
- throw restErrorUtil.createRESTException(
- "Invalid input data: " + e.getMessage(),
- MessageEnums.INVALID_INPUT_DATA);
- }
-
- }
-
- public String readMapToString(Map<?, ?> map) {
- ObjectMapper mapper = new ObjectMapper();
- String jsonString = null;
- try {
- jsonString = mapper.writeValueAsString(map);
- } catch (JsonParseException e) {
- throw restErrorUtil.createRESTException(
- "Invalid input data: " + e.getMessage(),
- MessageEnums.INVALID_INPUT_DATA);
- } catch (JsonMappingException e) {
- throw restErrorUtil.createRESTException(
- "Invalid input data: " + e.getMessage(),
- MessageEnums.INVALID_INPUT_DATA);
- } catch (IOException e) {
- throw restErrorUtil.createRESTException(
- "Invalid input data: " + e.getMessage(),
- MessageEnums.INVALID_INPUT_DATA);
- }
- return jsonString;
- }
-
- public String writeObjectAsString(ViewBaseBean vObj) {
- ObjectMapper mapper = new ObjectMapper();
-
- String jsonStr;
- try {
- jsonStr = mapper.writeValueAsString(vObj);
- return jsonStr;
- } catch (JsonParseException e) {
- throw restErrorUtil.createRESTException(
- "Invalid input data: " + e.getMessage(),
- MessageEnums.INVALID_INPUT_DATA);
- } catch (JsonMappingException e) {
- throw restErrorUtil.createRESTException(
- "Invalid input data: " + e.getMessage(),
- MessageEnums.INVALID_INPUT_DATA);
- } catch (IOException e) {
- throw restErrorUtil.createRESTException(
- "Invalid input data: " + e.getMessage(),
- MessageEnums.INVALID_INPUT_DATA);
- }
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/MessageEnums.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/MessageEnums.java b/security-admin/src/main/java/com/xasecure/common/MessageEnums.java
deleted file mode 100644
index 9799158..0000000
--- a/security-admin/src/main/java/com/xasecure/common/MessageEnums.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * 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 com.xasecure.common;
-
-import com.xasecure.view.VXMessage;
-
-
-public enum MessageEnums {
-
- // Note: Please do not format this file. It messes up the indentations
-
- // Common Errors
- DATA_NOT_FOUND("xa.error.data_not_found", "Data not found"),
- OPER_NOT_ALLOWED_FOR_STATE( "xa.error.oper_not_allowed_for_state", "Operation not allowed in current state"),
- OPER_NOT_ALLOWED_FOR_ENTITY( "xa.error.oper_not_allowed_for_state", "Operation not allowed for entity"),
- OPER_NO_PERMISSION("xa.error.oper_no_permission", "User doesn't have permission to perform this operation"),
- DATA_NOT_UPDATABLE( "xa.error.data_not_updatable", "Data not updatable"),
- ERROR_CREATING_OBJECT("xa.error.create_object", "Error creating object"),
- ERROR_DUPLICATE_OBJECT("xa.error.duplicate_object", "Error creating duplicate object"),
- ERROR_SYSTEM("xa.error.system", "System Error. Please try later."),
- OPER_NO_EXPORT("xa.error.oper_no_export", "repository is disabled"),
-
- // Common Validations
- INVALID_PASSWORD( "xa.validation.invalid_password", "Invalid password"),
- INVALID_INPUT_DATA("xa.validation.invalid_input_data", "Invalid input data"),
- NO_INPUT_DATA("xa.validation.no_input_data", "Input data is not provided"),
- INPUT_DATA_OUT_OF_BOUND("xa.validation.data_out_of_bound", "Input data if out of bound");
-
- String rbKey;
- String messageDesc;
-
- MessageEnums(String rbKey, String messageDesc) {
- this.rbKey = rbKey;
- this.messageDesc = messageDesc;
- }
-
- public VXMessage getMessage() {
- VXMessage msg = new VXMessage();
- msg.setName(this.toString());
- msg.setRbKey(rbKey);
- msg.setMessage(messageDesc);
- return msg;
- }
-
- public VXMessage getMessage(Long objectId, String fieldName) {
- VXMessage msg = new VXMessage();
- msg.setName(this.toString());
- msg.setRbKey(rbKey);
- msg.setMessage(messageDesc);
- msg.setObjectId(objectId);
- msg.setFieldName(fieldName);
- return msg;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/MyCallBack.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/MyCallBack.java b/security-admin/src/main/java/com/xasecure/common/MyCallBack.java
deleted file mode 100644
index c44e131..0000000
--- a/security-admin/src/main/java/com/xasecure/common/MyCallBack.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * 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 com.xasecure.common;
-
-
-public interface MyCallBack {
- /**
- * Make sure to add @Transactional annotation to the implementation method.
- *
- * @Override
- * @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
- */
- public Object process(Object data);
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/PasswordUtils.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/PasswordUtils.java b/security-admin/src/main/java/com/xasecure/common/PasswordUtils.java
deleted file mode 100644
index b20a3dd..0000000
--- a/security-admin/src/main/java/com/xasecure/common/PasswordUtils.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * 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 com.xasecure.common;
-import java.io.IOException;
-import java.util.Map;
-
-import javax.crypto.Cipher;
-import javax.crypto.SecretKey;
-import javax.crypto.SecretKeyFactory;
-import javax.crypto.spec.PBEKeySpec;
-import javax.crypto.spec.PBEParameterSpec;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.sun.jersey.core.util.Base64;
-public class PasswordUtils {
-
- private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class) ;
-
- private static final char[] ENCRYPT_KEY = "tzL1AKl5uc4NKYaoQ4P3WLGIBFPXWPWdu1fRm9004jtQiV".toCharArray() ;
-
- private static final byte[] SALT = "f77aLYLo".getBytes() ;
-
- private static final int ITERATION_COUNT = 17 ;
-
- private static final String CRYPT_ALGO = "PBEWithMD5AndDES" ;
-
- private static final String PBE_KEY_ALGO = "PBEWithMD5AndDES" ;
-
- private static final String LEN_SEPARATOR_STR = ":" ;
-
- public static String encryptPassword(String aPassword) throws IOException {
- Map<String, String> env = System.getenv();
- String encryptKeyStr = env.get("ENCRYPT_KEY") ;
- char[] encryptKey;
- if (encryptKeyStr == null) {
- encryptKey=ENCRYPT_KEY;
- }else{
- encryptKey=encryptKeyStr.toCharArray();
- }
- String saltStr = env.get("ENCRYPT_SALT") ;
- byte[] salt;
- if (saltStr == null) {
- salt = SALT ;
- }else{
- salt=saltStr.getBytes();
- }
- String ret = null ;
- String strToEncrypt = null ;
- if (aPassword == null) {
- strToEncrypt = "" ;
- }
- else {
- strToEncrypt = aPassword.length() + LEN_SEPARATOR_STR + aPassword ;
- }
- try {
- Cipher engine = Cipher.getInstance(CRYPT_ALGO) ;
- PBEKeySpec keySpec = new PBEKeySpec(encryptKey) ;
- SecretKeyFactory skf = SecretKeyFactory.getInstance(PBE_KEY_ALGO) ;
- SecretKey key = skf.generateSecret(keySpec) ;
- engine.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(salt, ITERATION_COUNT));
- byte[] encryptedStr = engine.doFinal(strToEncrypt.getBytes()) ;
- ret = new String(Base64.encode(encryptedStr)) ;
- }
- catch(Throwable t) {
- LOG.error("Unable to encrypt password due to error", t);
- throw new IOException("Unable to encrypt password due to error", t) ;
- }
- return ret ;
- }
-
- public static String decryptPassword(String aPassword) throws IOException {
- String ret = null ;
- Map<String, String> env = System.getenv();
- String encryptKeyStr = env.get("ENCRYPT_KEY") ;
- char[] encryptKey;
- if (encryptKeyStr == null) {
- encryptKey=ENCRYPT_KEY;
- }else{
- encryptKey=encryptKeyStr.toCharArray();
- }
- String saltStr = env.get("ENCRYPT_SALT") ;
- byte[] salt;
- if (saltStr == null) {
- salt = SALT ;
- }else{
- salt=saltStr.getBytes();
- }
- try {
- byte[] decodedPassword = Base64.decode(aPassword) ;
- Cipher engine = Cipher.getInstance(CRYPT_ALGO) ;
- PBEKeySpec keySpec = new PBEKeySpec(encryptKey) ;
- SecretKeyFactory skf = SecretKeyFactory.getInstance(PBE_KEY_ALGO) ;
- SecretKey key = skf.generateSecret(keySpec) ;
- engine.init(Cipher.DECRYPT_MODE, key,new PBEParameterSpec(salt, ITERATION_COUNT));
- String decrypted = new String(engine.doFinal(decodedPassword)) ;
- int foundAt = decrypted.indexOf(LEN_SEPARATOR_STR) ;
- if (foundAt > -1) {
- if (decrypted.length() > foundAt) {
- ret = decrypted.substring(foundAt+1) ;
- }
- else {
- ret = "" ;
- }
- }
- else {
- ret = null;
- }
- }
- catch(Throwable t) {
- LOG.error("Unable to decrypt password due to error", t);
- throw new IOException("Unable to decrypt password due to error", t) ;
- }
- return ret ;
- }
-
- public static void main(String[] args) {
- String[] testPasswords = { "a", "a123", "dsfdsgdg", "*7263^5#", "", null } ;
- for(String password : testPasswords) {
- try {
- String ePassword = PasswordUtils.encryptPassword(password) ;
- String dPassword = PasswordUtils.decryptPassword(ePassword) ;
- if (password == null ) {
- if (dPassword != null) {
- throw new RuntimeException("The password expected [" + password + "]. Found [" + dPassword + "]") ;
- }
- else {
- System.out.println("Password: [" + password + "] matched after decrypt. Encrypted: [" + ePassword + "]") ;
- }
- }
- else if (! password.equals(dPassword)) {
- throw new RuntimeException("The password expected [" + password + "]. Found [" + dPassword + "]") ;
- }
- else {
- System.out.println("Password: [" + password + "] matched after decrypt. Encrypted: [" + ePassword + "]") ;
- }
- }
- catch(IOException ioe) {
- ioe.printStackTrace();
- System.out.println("Password verification failed for password [" + password + "]:" + ioe) ;
- }
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/PropertiesUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/PropertiesUtil.java b/security-admin/src/main/java/com/xasecure/common/PropertiesUtil.java
deleted file mode 100644
index 5e2503d..0000000
--- a/security-admin/src/main/java/com/xasecure/common/PropertiesUtil.java
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * 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 com.xasecure.common;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.BeansException;
-import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
-import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
-
-
-import com.xasecure.credentialapi.CredentialReader;
-
-public class PropertiesUtil extends PropertyPlaceholderConfigurer {
- private static Map<String, String> propertiesMap = new HashMap<String, String>();
- private static Logger logger = Logger.getLogger(PropertiesUtil.class);
- private PropertiesUtil() {
-
- }
-
- @Override
- protected void processProperties(
- ConfigurableListableBeanFactory beanFactory, Properties props)
- throws BeansException {
-
- // First let's add the system properties
- Set<Object> keySet = System.getProperties().keySet();
- for (Object key : keySet) {
- String keyStr = key.toString();
- propertiesMap.put(keyStr, System.getProperties()
- .getProperty(keyStr).trim());
- }
-
- // Let's add our properties now
- keySet = props.keySet();
- for (Object key : keySet) {
- String keyStr = key.toString();
- propertiesMap.put(keyStr, props.getProperty(keyStr).trim());
- }
-
- //update credential from keystore
- if(propertiesMap!=null && propertiesMap.containsKey("xaDB.jdbc.credential.provider.path") && propertiesMap.containsKey("xaDB.jdbc.credential.alias")){
- String path=propertiesMap.get("xaDB.jdbc.credential.provider.path");
- String alias=propertiesMap.get("xaDB.jdbc.credential.alias");
- if(path!=null && alias!=null){
- String xaDBPassword=CredentialReader.getDecryptedString(path.trim(),alias.trim());
- if(xaDBPassword!=null&& !xaDBPassword.trim().isEmpty() &&
- !xaDBPassword.trim().equalsIgnoreCase("none")){
- propertiesMap.put("jdbc.password", xaDBPassword);
- props.put("jdbc.password", xaDBPassword);
- }else{
- logger.info("Credential keystore password not applied for XA DB; clear text password shall be applicable");
- }
- }
- }
- if(propertiesMap!=null && propertiesMap.containsKey("auditDB.jdbc.credential.provider.path") && propertiesMap.containsKey("auditDB.jdbc.credential.alias")){
- String path=propertiesMap.get("auditDB.jdbc.credential.provider.path");
- String alias=propertiesMap.get("auditDB.jdbc.credential.alias");
- if(path!=null && alias!=null){
- String auditDBPassword=CredentialReader.getDecryptedString(path.trim(), alias.trim());
- if(auditDBPassword!=null&& !auditDBPassword.trim().isEmpty() &&
- !auditDBPassword.trim().equalsIgnoreCase("none")){
- propertiesMap.put("auditDB.jdbc.password", auditDBPassword);
- props.put("auditDB.jdbc.password", auditDBPassword);
- }else{
- logger.info("Credential keystore password not applied for Audit DB; clear text password shall be applicable");
- }
- }
- }
- super.processProperties(beanFactory, props);
- }
-
- public static String getProperty(String key, String defaultValue) {
- if (key == null) {
- return null;
- }
- String rtrnVal = propertiesMap.get(key);
- if (rtrnVal == null) {
- rtrnVal = defaultValue;
- }
- return rtrnVal;
- }
-
- public static String getProperty(String key) {
- if (key == null) {
- return null;
- }
- return propertiesMap.get(key);
- }
-
- public static String[] getPropertyStringList(String key) {
- if (key == null) {
- return null;
- }
- String value = propertiesMap.get(key);
- if (value != null) {
- String[] splitValues = value.split(",");
- String[] returnValues = new String[splitValues.length];
- for (int i = 0; i < splitValues.length; i++) {
- returnValues[i] = splitValues[i].trim();
- }
- return returnValues;
- } else {
- return new String[0];
- }
- }
-
- public static Integer getIntProperty(String key, int defaultValue) {
- if (key == null) {
- return null;
- }
- String rtrnVal = propertiesMap.get(key);
- if (rtrnVal == null) {
- return defaultValue;
- }
- return Integer.valueOf(rtrnVal);
- }
-
- public static Integer getIntProperty(String key) {
- if (key == null) {
- return null;
- }
- String rtrnVal = propertiesMap.get(key);
- if (rtrnVal == null) {
- return null;
- }
- return Integer.valueOf(rtrnVal);
- }
-
- public static boolean getBooleanProperty(String key, boolean defaultValue) {
- if (key == null) {
- return defaultValue;
- }
- String value = getProperty(key);
- if (value == null) {
- return defaultValue;
- }
- return Boolean.parseBoolean(value);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/RESTErrorUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/RESTErrorUtil.java b/security-admin/src/main/java/com/xasecure/common/RESTErrorUtil.java
deleted file mode 100644
index bfcb241..0000000
--- a/security-admin/src/main/java/com/xasecure/common/RESTErrorUtil.java
+++ /dev/null
@@ -1,349 +0,0 @@
-/*
- * 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 com.xasecure.common;
-
-import java.text.DateFormat;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.Response;
-
-import com.xasecure.view.VXMessage;
-import com.xasecure.view.VXResponse;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-
-@Component
-public class RESTErrorUtil {
-
- static final Logger logger = Logger.getLogger(RESTErrorUtil.class);
-
- @Autowired
- StringUtil stringUtil;
-
- public static final String TRUE = "true";
-
- public WebApplicationException createRESTException(VXResponse gjResponse) {
- Response errorResponse = Response
- .status(javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST)
- .entity(gjResponse).build();
-
- WebApplicationException restException = new WebApplicationException(
- errorResponse);
- restException.fillInStackTrace();
- UserSessionBase userSession = ContextUtil.getCurrentUserSession();
- Long sessionId = null;
- String loginId = null;
- if (userSession != null) {
- loginId = userSession.getLoginId();
- sessionId = userSession.getSessionId();
- }
-
- logger.info("Request failed. SessionId=" + sessionId + ", loginId="
- + loginId + ", logMessage=" + gjResponse.getMsgDesc(),
- restException);
-
- return restException;
- }
-
- /**
- *
- * @param logMessage
- * This is optional
- * @return
- */
- public WebApplicationException create403RESTException(String logMessage) {
- Response errorResponse = Response.status(
- javax.servlet.http.HttpServletResponse.SC_FORBIDDEN).build();
-
- WebApplicationException restException = new WebApplicationException(
- errorResponse);
- restException.fillInStackTrace();
- // TODO:Future:Open: Need to log all these and add user to
- // block list if this is deliberate
- // Get user information
- UserSessionBase userSession = ContextUtil.getCurrentUserSession();
- Long sessionId = null;
- String loginId = null;
- String sessionInfo = "";
- if (userSession != null) {
- loginId = userSession.getLoginId();
- sessionInfo = userSession.toString();
- sessionId = userSession.getSessionId();
- }
-
- String requestInfo = "";
- try {
- RequestContext reqContext = ContextUtil.getCurrentRequestContext();
- if (reqContext != null) {
- requestInfo = reqContext.toString();
- requestInfo += ", timeTaken="
- + (System.currentTimeMillis() - reqContext
- .getStartTime());
- }
- } catch (Throwable contextEx) {
- logger.error("Error getting request info", contextEx);
- }
-
- logger.error("Access restricted. SessionId=" + sessionId + ", loginId="
- + loginId + ", logMessage=" + logMessage + ", requestInfo="
- + requestInfo + ", sessionInfo=" + sessionInfo, restException);
-
- return restException;
- }
-
-
-
-
- public Integer parseInt(String value, String errorMessage,
- MessageEnums messageEnum, Long objectId, String fieldName) {
- try {
- if (stringUtil.isEmpty(value)) {
- return null;
- } else {
- return new Integer(value.trim());
- }
- } catch (Throwable t) {
- throw createRESTException(errorMessage, messageEnum, objectId,
- fieldName, value);
- }
- }
-
- public Integer parseInt(String value, int defaultValue,
- String errorMessage, MessageEnums messageEnum, Long objectId,
- String fieldName) {
- try {
- if (stringUtil.isEmpty(value)) {
- return new Integer(defaultValue);
- } else {
- return new Integer(value.trim());
- }
- } catch (Throwable t) {
- throw createRESTException(errorMessage, messageEnum, objectId,
- fieldName, value);
- }
- }
-
- public Long parseLong(String value, Long defaultValue) {
- if (stringUtil.isEmpty(value)) {
- return defaultValue;
- }
- return new Long(value.trim());
- }
-
- public Long parseLong(String value, String errorMessage,
- MessageEnums messageEnum, Long objectId, String fieldName) {
- try {
- if (stringUtil.isEmpty(value)) {
- return null;
- } else {
- return new Long(value.trim());
- }
- } catch (Throwable t) {
- throw createRESTException(errorMessage, messageEnum, objectId,
- fieldName, value);
- }
- }
-
-
-
- public String validateString(String value, String regExStr,
- String errorMessage, MessageEnums messageEnum, Long objectId,
- String fieldName) {
- return validateString(value, regExStr, errorMessage, messageEnum,
- objectId, fieldName, false);
-
- }
-
- public String validateString(String value, String regExStr,
- String errorMessage, MessageEnums messageEnum, Long objectId,
- String fieldName, boolean isMandatory) {
- if (stringUtil.isEmpty(value)) {
- if (isMandatory) {
- throw createRESTException(errorMessage,
- MessageEnums.NO_INPUT_DATA, objectId, fieldName, null);
- }
- return null;
- }
- value = value.trim();
- if (value.length() != 0) {
- if (!stringUtil.validateString(regExStr, value)) {
- throw createRESTException(errorMessage, messageEnum, objectId,
- fieldName, value);
- }
- return value;
- } else {
- return null;
- }
-
- }
-
- public String validateStringForUpdate(String value, String originalValue,
- String regExStr, String errorMessage, MessageEnums messageEnum,
- Long objectId, String fieldName) {
- return validateStringForUpdate(value, originalValue, regExStr,
- errorMessage, messageEnum, objectId, fieldName, false);
- }
-
- public String validateStringForUpdate(String value, String originalValue,
- String regExStr, String errorMessage, MessageEnums messageEnum,
- Long objectId, String fieldName, boolean isMandatory) {
- if (stringUtil.isEmpty(value)) {
- if (isMandatory) {
- throw createRESTException(errorMessage,
- MessageEnums.NO_INPUT_DATA, objectId, fieldName, null);
- }
- return null;
- }
-
- if (!value.equalsIgnoreCase(originalValue)) {
- return validateString(value, StringUtil.VALIDATION_NAME,
- errorMessage, messageEnum, objectId, fieldName);
- } else {
- return value;
- }
- }
-
- public void validateStringList(String value, String[] validValues,
- String errorMessage, Long objectId, String fieldName) {
- for (int i = 0; i < validValues.length; i++) {
- if (validValues[i].equals(value)) {
- return;
- }
- }
- throw createRESTException(errorMessage,
- MessageEnums.INVALID_INPUT_DATA, objectId, fieldName, value);
- }
-
-
-
-
-
- public void validateMinMax(int value, int minValue, int maxValue,
- String errorMessage, Long objectId, String fieldName) {
- if (value < minValue || value > maxValue) {
- throw createRESTException(errorMessage,
- MessageEnums.INPUT_DATA_OUT_OF_BOUND, objectId, fieldName,
- "" + value);
- }
- }
-
-
- public WebApplicationException createRESTException(String errorMessage,
- MessageEnums messageEnum, Long objectId, String fieldName,
- String logMessage) {
- List<VXMessage> messageList = new ArrayList<VXMessage>();
- messageList.add(messageEnum.getMessage(objectId, fieldName));
-
- VXResponse gjResponse = new VXResponse();
- gjResponse.setStatusCode(VXResponse.STATUS_ERROR);
- gjResponse.setMsgDesc(errorMessage);
- gjResponse.setMessageList(messageList);
- WebApplicationException webAppEx = createRESTException(gjResponse);
- logger.info("Validation error:logMessage=" + logMessage + ", response="
- + gjResponse, webAppEx);
- return webAppEx;
- }
-
- public WebApplicationException createRESTException(String errorMessage,
- MessageEnums messageEnum) {
- List<VXMessage> messageList = new ArrayList<VXMessage>();
- messageList.add(messageEnum.getMessage());
-
- VXResponse gjResponse = new VXResponse();
- gjResponse.setStatusCode(VXResponse.STATUS_ERROR);
- gjResponse.setMsgDesc(errorMessage);
- gjResponse.setMessageList(messageList);
- WebApplicationException webAppEx = createRESTException(gjResponse);
- logger.info("Operation error. response=" + gjResponse, webAppEx);
- return webAppEx;
- }
-
- public WebApplicationException createRESTException(int responseCode,
- String logMessage, boolean logError) {
- Response errorResponse = Response
- .status(responseCode).build();
-
- WebApplicationException restException = new WebApplicationException(
- errorResponse);
- restException.fillInStackTrace();
- UserSessionBase userSession = ContextUtil.getCurrentUserSession();
- Long sessionId = null;
- String loginId = null;
- if (userSession != null) {
- loginId = userSession.getLoginId();
- sessionId = userSession.getSessionId();
- }
-
- if (logError) {
- logger.info("Request failed. SessionId=" + sessionId + ", loginId="
- + loginId + ", logMessage=" + logMessage,
- restException);
- }
-
- return restException;
- }
-
-
- public Date parseDate(String value, String errorMessage,
- MessageEnums messageEnum, Long objectId, String fieldName,
- String dateFormat) {
- try {
- if (stringUtil.isEmpty(value)) {
- return null;
- } else {
- DateFormat formatter = new SimpleDateFormat(dateFormat);
- return formatter.parse(value);
-
- }
- } catch (Throwable t) {
- throw createRESTException(errorMessage, messageEnum, objectId,
- fieldName, value);
- }
- }
-
- public boolean parseBoolean(String value, boolean defaultValue) {
- if (stringUtil.isEmpty(value)) {
- return defaultValue;
- }
- return TRUE.equalsIgnoreCase(value.trim());
- }
-
- public Boolean parseBoolean(String value, String errorMessage,
- MessageEnums messageEnum, Long objectId, String fieldName) {
- try {
- if (stringUtil.isEmpty(value)) {
- return null;
- } else {
- return new Boolean(value.trim());
- }
- } catch (Throwable t) {
- throw createRESTException(errorMessage, messageEnum, objectId,
- fieldName, value);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/RequestContext.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/RequestContext.java b/security-admin/src/main/java/com/xasecure/common/RequestContext.java
deleted file mode 100644
index 5ad3b03..0000000
--- a/security-admin/src/main/java/com/xasecure/common/RequestContext.java
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * 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 com.xasecure.common;
-
-import java.io.Serializable;
-
-public class RequestContext implements Serializable {
- private static final long serialVersionUID = -7083383106845193385L;
- private String ipAddress = null;
- private String userAgent = null;
- private String requestURL = null;
- private int deviceType = XACommonEnums.DEVICE_UNKNOWN;
- private String serverRequestId = null;
- private boolean isSync = true;
- private long startTime = System.currentTimeMillis();
- private int clientTimeOffsetInMinute = 0;
-
- /**
- * @return the ipAddress
- */
- public String getIpAddress() {
- return ipAddress;
- }
-
- /**
- * @param ipAddress
- * the ipAddress to set
- */
- public void setIpAddress(String ipAddress) {
- this.ipAddress = ipAddress;
- }
-
- /**
- * @return the userAgent
- */
- public String getUserAgent() {
- return userAgent;
- }
-
- /**
- * @param userAgent
- * the userAgent to set
- */
- public void setUserAgent(String userAgent) {
- this.userAgent = userAgent;
- }
-
- /**
- * @return the deviceType
- */
- public int getDeviceType() {
- return deviceType;
- }
-
- /**
- * @param deviceType
- * the deviceType to set
- */
- public void setDeviceType(int deviceType) {
- this.deviceType = deviceType;
- }
-
- /**
- * @return the serverRequestId
- */
- public String getServerRequestId() {
- return serverRequestId;
- }
-
- /**
- * @param serverRequestId
- * the serverRequestId to set
- */
- public void setServerRequestId(String serverRequestId) {
- this.serverRequestId = serverRequestId;
- }
-
- /**
- * @return the isSync
- */
- public boolean isSync() {
- return isSync;
- }
-
- /**
- * @param isSync
- * the isSync to set
- */
- public void setSync(boolean isSync) {
- this.isSync = isSync;
- }
-
- /**
- * @return the requestURL
- */
- public String getRequestURL() {
- return requestURL;
- }
-
- /**
- * @param requestURL
- * the requestURL to set
- */
- public void setRequestURL(String requestURL) {
- this.requestURL = requestURL;
- }
-
- /**
- * @return the startTime
- */
- public long getStartTime() {
- return startTime;
- }
-
- /**
- * @param startTime
- * the startTime to set
- */
- public void setStartTime(long startTime) {
- this.startTime = startTime;
- }
-
- public int getClientTimeOffsetInMinute() {
- return clientTimeOffsetInMinute;
- }
-
- public void setClientTimeOffsetInMinute(int clientTimeOffset) {
- this.clientTimeOffsetInMinute = clientTimeOffset;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.lang.Object#toString()
- */
- @Override
- public String toString() {
- return "RequestContext [ipAddress=" + ipAddress + ", userAgent="
- + userAgent + ", requestURL=" + requestURL + ", deviceType="
- + deviceType + ", serverRequestId=" + serverRequestId
- + ", isSync=" + isSync + ", startTime=" + startTime + "]";
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/SearchCriteria.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/SearchCriteria.java b/security-admin/src/main/java/com/xasecure/common/SearchCriteria.java
deleted file mode 100644
index c1df00f..0000000
--- a/security-admin/src/main/java/com/xasecure/common/SearchCriteria.java
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * 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 com.xasecure.common;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.apache.log4j.Logger;
-
-import com.xasecure.biz.XABizUtil;
-
-
-public class SearchCriteria {
- Logger logger = Logger.getLogger(SearchCriteria.class);
-
- int startIndex = 0;
- int maxRows = Integer.MAX_VALUE;
- String sortBy = null;
- String sortType = null;
- boolean getCount = true;
- Number ownerId = null;
- boolean familyOnly = false;
- boolean getChildren = false;
- boolean isDistinct = false;
- HashMap<String, Object> paramList = new HashMap<String, Object>();
- Set<String> nullParamList = new HashSet<String>();
- Set<String> notNullParamList = new HashSet<String>();
-
- List<SearchGroup> searchGroups = new ArrayList<SearchGroup>();
-
- /**
- * @return the startIndex
- */
- public int getStartIndex() {
- return startIndex;
- }
-
- /**
- * @param startIndex
- * the startIndex to set
- */
- public void setStartIndex(int startIndex) {
- this.startIndex = startIndex;
- }
-
- /**
- * @return the maxRows
- */
- public int getMaxRows() {
- return maxRows;
- }
-
- /**
- * @param maxRows
- * the maxRows to set
- */
- public void setMaxRows(int maxRows) {
- this.maxRows = maxRows;
- }
-
- /**
- * @return the sortBy
- */
- public String getSortBy() {
- return sortBy;
- }
-
- /**
- * @param sortBy
- * the sortBy to set
- */
- public void setSortBy(String sortBy) {
- this.sortBy = sortBy;
- }
-
- /**
- * @return the sortType
- */
- public String getSortType() {
- return sortType;
- }
-
- /**
- * @param sortType
- * the sortType to set
- */
- public void setSortType(String sortType) {
- this.sortType = sortType;
- }
-
- public boolean isGetCount() {
- return getCount;
- }
-
- public void setGetCount(boolean getCount) {
- this.getCount = getCount;
- }
-
- public Number getOwnerId() {
- return ownerId;
- }
-
- public void setOwnerId(Number ownerId) {
- this.ownerId = ownerId;
- }
-
- public boolean isGetChildren() {
- return getChildren;
- }
-
- public void setGetChildren(boolean getChildren) {
- this.getChildren = getChildren;
- }
-
- /**
- * @return the paramList
- */
- public HashMap<String, Object> getParamList() {
- return paramList;
- }
-
- /**
- * @param string
- * @param caId
- */
- public void addParam(String name, Object value) {
- paramList.put(name, value);
- }
-
- public Object getParamValue(String name) {
- return paramList.get(name);
- }
-
- /**
- * @return the nullParamList
- */
- public Set<String> getNullParamList() {
- return nullParamList;
- }
-
- /**
- * @return the notNullParamList
- */
- public Set<String> getNotNullParamList() {
- return notNullParamList;
- }
-
- /**
- * @return the searchGroups
- */
- public List<SearchGroup> getSearchGroups() {
- return searchGroups;
- }
-
- /**
- * @return the isDistinct
- */
- public boolean isDistinct() {
- return isDistinct;
- }
-
- /**
- * @param isDistinct
- * the isDistinct to set
- */
- public void setDistinct(boolean isDistinct) {
-
- int dbFlavor = XABizUtil.getDBFlavor();
- if (isDistinct && dbFlavor == AppConstants.DB_FLAVOR_ORACLE) {
- isDistinct = false;
- logger.debug("Database flavor is `ORACLE` so ignoring DISTINCT "
- + "clause from select statement.");
- }
- this.isDistinct = isDistinct;
- }
-
-}
[14/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XResourceService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XResourceService.java b/security-admin/src/main/java/com/xasecure/service/XResourceService.java
deleted file mode 100644
index bbbf458..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XResourceService.java
+++ /dev/null
@@ -1,1115 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-import java.io.File;
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map.Entry;
-
-import com.xasecure.common.ContextUtil;
-import com.xasecure.common.MessageEnums;
-import com.xasecure.common.PropertiesUtil;
-import com.xasecure.common.SearchCriteria;
-import com.xasecure.common.SearchField;
-import com.xasecure.common.SearchField.DATA_TYPE;
-import com.xasecure.common.SearchField.SEARCH_TYPE;
-import com.xasecure.common.SortField;
-import com.xasecure.common.StringUtil;
-import com.xasecure.common.UserSessionBase;
-import com.xasecure.common.XAConstants;
-import com.xasecure.view.VXResponse;
-
-import org.apache.commons.lang.ArrayUtils;
-import org.apache.commons.lang.StringUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Service;
-
-import com.xasecure.biz.XABizUtil;
-import com.xasecure.common.AppConstants;
-import com.xasecure.common.view.VTrxLogAttr;
-import com.xasecure.db.XADaoManager;
-import com.xasecure.entity.*;
-import com.xasecure.util.XAEnumUtil;
-import com.xasecure.view.*;
-@Service
-@Scope("singleton")
-public class XResourceService extends
- XResourceServiceBase<XXResource, VXResource> {
-
- @Autowired
- XPermMapService xPermMapService;
-
- @Autowired
- XAuditMapService xAuditMapService;
-
- @Autowired
- XUserService xUserService;
-
- @Autowired
- StringUtil stringUtil;
-
- @Autowired
- XADaoManager xADaoManager;
- @Autowired
- XABizUtil xaBizUtil;
-
- @Autowired
- XAEnumUtil xaEnumUtil;
-
- @Autowired
- XPolicyService xPolicyService;
-
- static HashMap<String, VTrxLogAttr> trxLogAttrs = new HashMap<String, VTrxLogAttr>();
-
- static String fileSeparator = PropertiesUtil.getProperty(
- "xa.file.separator", "/");
-
- static {
- trxLogAttrs.put("name", new VTrxLogAttr("name", "Resource Path", false));
- trxLogAttrs.put("description", new VTrxLogAttr("description", "Policy Description", false));
- trxLogAttrs.put("resourceType", new VTrxLogAttr("resourceType", "Policy Type", true));
- trxLogAttrs.put("isEncrypt", new VTrxLogAttr("isEncrypt", "Policy Encryption", true));
- trxLogAttrs.put("isRecursive", new VTrxLogAttr("isRecursive", "Is Policy Recursive", true));
- trxLogAttrs.put("databases", new VTrxLogAttr("databases", "Databases", false));
- trxLogAttrs.put("tables", new VTrxLogAttr("tables", "Tables", false));
- trxLogAttrs.put("columnFamilies", new VTrxLogAttr("columnFamilies", "Column Families", false));
- trxLogAttrs.put("columns", new VTrxLogAttr("columns", "Columns", false));
- trxLogAttrs.put("udfs", new VTrxLogAttr("udfs", "UDF", false));
- trxLogAttrs.put("resourceStatus", new VTrxLogAttr("resourceStatus", "Policy Status", true));
- trxLogAttrs.put("tableType", new VTrxLogAttr("tableType", "Table Type", true));
- trxLogAttrs.put("columnType", new VTrxLogAttr("columnType", "Column Type", true));
- trxLogAttrs.put("policyName", new VTrxLogAttr("policyName", "Policy Name", false));
- trxLogAttrs.put("topologies", new VTrxLogAttr("topologies", "Topologies", false));
- trxLogAttrs.put("services", new VTrxLogAttr("services", "Services", false));
- trxLogAttrs.put("assetType", new VTrxLogAttr("assetType", "Repository Type", true));
- }
-
- public XResourceService() {
- searchFields.add(new SearchField("name", "obj.name",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
- searchFields.add(new SearchField("fullname", "obj.name",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL));
- searchFields.add(new SearchField("policyName", "obj.policyName",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
- searchFields.add(new SearchField("fullPolicyName", "obj.policyName",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL));
- searchFields.add(new SearchField("columns", "obj.columns",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
- searchFields.add(new SearchField("columnFamilies",
- "obj.columnFamilies", SearchField.DATA_TYPE.STRING,
- SearchField.SEARCH_TYPE.PARTIAL));
- searchFields.add(new SearchField("tables", "obj.tables",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
- searchFields.add(new SearchField("udfs", "obj.udfs",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
- searchFields.add(new SearchField("databases", "obj.databases",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
- searchFields.add(new SearchField("assetId", "obj.assetId",
- SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
- searchFields.add(new SearchField("resourceType", "obj.resourceType",
- SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
- searchFields.add(new SearchField("isEncrypt", "obj.isEncrypt",
- SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
- searchFields.add(new SearchField("isRecursive", "obj.isRecursive",
- SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
-
- searchFields.add(new SearchField("groupName", "xxGroup.name",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL,
- "XXPermMap xxPermMap, XXGroup xxGroup", "xxPermMap.resourceId "
- + "= obj.id and xxPermMap.groupId = xxGroup.id"));
-
- searchFields.add(new SearchField("userName", "xUser.name",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL,
- "XXPermMap xxPermMap, XXUser xUser", "xxPermMap.resourceId "
- + "= obj.id and xxPermMap.userId = xUser.id"));
-
- searchFields.add(new SearchField("userId", "xxPermMap.userId",
- SearchField.DATA_TYPE.INT_LIST, SearchField.SEARCH_TYPE.FULL,
- "XXPermMap xxPermMap", "xxPermMap.resourceId = obj.id "));
-
- searchFields.add(new SearchField("groupId", "xxPermMap.groupId",
- SearchField.DATA_TYPE.INT_LIST, SearchField.SEARCH_TYPE.FULL,
- "XXPermMap xxPermMap", "xxPermMap.resourceId = obj.id"));
-
- searchFields.add(new SearchField("assetType", "xxAsset.assetType",
- SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL,
- "XXAsset xxAsset", "xxAsset.id = obj.assetId "));
-
- searchFields.add(new SearchField("id", "obj.id",
- SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
- searchFields.add(new SearchField("topologies", "obj.topologies",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
- searchFields.add(new SearchField("services", "obj.services",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
- searchFields.add(new SearchField("tableType", "obj.tableType",
- DATA_TYPE.INTEGER, SEARCH_TYPE.FULL));
- searchFields.add(new SearchField("columnType", "obj.columnType",
- DATA_TYPE.INTEGER, SEARCH_TYPE.FULL));
- searchFields.add(new SearchField("repositoryName", "xxAsset.name",
- DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL, "XXAsset xxAsset",
- "xxAsset.id = obj.assetId"));
- searchFields.add(new SearchField("resourceStatus",
- "obj.resourceStatus", DATA_TYPE.INT_LIST, SEARCH_TYPE.FULL));
-
- sortFields.add(new SortField("name", "obj.name"));
- sortFields.add(new SortField("isRecursive", "obj.isRecursive"));
- sortFields.add(new SortField("isEncrypt", "obj.isEncrypt"));
-
- }
-
- @Override
- protected void validateForCreate(VXResource vObj) {
- if(vObj == null){
- throw restErrorUtil.createRESTException("Policy not provided.",
- MessageEnums.DATA_NOT_FOUND);
- }
- Long assetId = vObj.getAssetId();
- int assetType;
- if(assetId != null){
- XXAsset xAsset = xADaoManager.getXXAsset().getById(assetId);
- if(xAsset != null){
- assetType = xAsset.getAssetType();
- } else {
- throw restErrorUtil.createRESTException("The repository for which "
- + "the policy is created, doesn't exist in the system.",
- MessageEnums.OPER_NOT_ALLOWED_FOR_STATE);
- }
- } else {
- logger.debug("Asset id not provided.");
- throw restErrorUtil.createRESTException("Please provide repository"
- + " id for policy.", MessageEnums.OPER_NOT_ALLOWED_FOR_STATE);
- }
-
- String resourceName = vObj.getName();
-// Long resourceId = vObj.getId();
-// int isRecursive = vObj.getIsRecursive();
- if(stringUtil.isEmpty(resourceName)){
- logger.error("Resource name not found for : " + vObj.toString());
- throw restErrorUtil.createRESTException("Please provide valid resources.",
- MessageEnums.INVALID_INPUT_DATA);
- }
-
-// String[] resourceNameList = stringUtil.split(resourceName, ",");
-// for(String resName : resourceNameList){
-// List<XXResource> xXResourceList = null;
-// if (assetType == AppConstants.ASSET_HDFS) {
-// xXResourceList = appDaoManager.getXXResource()
-// .findByResourceNameAndAssetIdAndRecursiveFlag(resName, assetId, isRecursive);
-// } else {
-// xXResourceList = appDaoManager.getXXResource()
-// .findByResourceNameAndAssetIdAndResourceType(vObj.getName(),
-// vObj.getAssetId(), vObj.getResourceType());
-// }
-//
-// if (xXResourceList != null) {
-// boolean similarPolicyFound = false;
-// for(XXResource xxResource : xXResourceList){
-// String dbResourceName = xxResource.getName();
-// // Not checking dbResourceName to be null or empty
-// // as this should never be the case
-// String[] resources = stringUtil.split(dbResourceName, ",");
-// for(String dbResource: resources){
-// if(dbResource.equalsIgnoreCase(resName)){
-// if(resourceId!=null){
-// Long dbResourceId = xxResource.getId();
-// if(!resourceId.equals(dbResourceId)){
-// similarPolicyFound = true;
-// break;
-// }
-// } else {
-// similarPolicyFound = true;
-// break;
-// }
-// }
-// }
-// if(similarPolicyFound){
-// break;
-// }
-// }
-// if(similarPolicyFound){
-// throw restErrorUtil.createRESTException(
-// "Similar policy already exists for the resource : " + resName,
-// MessageEnums.ERROR_DUPLICATE_OBJECT);
-// }
-// }
-// }
-
-// if(vObj.getAssetType())
-
- }
-
- @Override
- protected void validateForUpdate(VXResource vObj, XXResource mObj) {
- if (vObj != null && vObj.getAssetType() == AppConstants.ASSET_HDFS) {
- if (!(vObj.getName() != null) || vObj.getName().isEmpty()) {
- throw restErrorUtil.createRESTException("Please provide the "
- + "resource path.", MessageEnums.INVALID_INPUT_DATA);
- }
- }
- if (!vObj.getName().equalsIgnoreCase(mObj.getName()) ||
- vObj.getIsRecursive()!=mObj.getIsRecursive() ||
- vObj.getResourceType() != mObj.getResourceType()) {
- validateForCreate(vObj);
- }
-
- }
-
- @Override
- public VXResource createResource(VXResource vXResource) {
-
- VXResource resource = super.createResource(vXResource);
-
- List<VXAuditMap> newAuditMapList = new ArrayList<VXAuditMap>();
- List<VXAuditMap> vxAuditMapList = vXResource.getAuditList();
- if (vxAuditMapList != null) {
- for (VXAuditMap vxAuditMap : vxAuditMapList) {
- vxAuditMap.setResourceId(resource.getId());
- vxAuditMap = xAuditMapService.createResource(vxAuditMap);
- newAuditMapList.add(vxAuditMap);
- }
- }
-
- List<VXPermMap> newPermMapList = new ArrayList<VXPermMap>();
- List<VXPermMap> vxPermMapList = vXResource.getPermMapList();
- if (vxPermMapList != null) {
- for (VXPermMap permMap : vxPermMapList) {
- if (permMap.getUserId() == null && permMap.getGroupId() == null
- && vxAuditMapList == null){
- if(vxAuditMapList == null){
- throw restErrorUtil.createRESTException("Please provide"
- + " valid group/user permissions for policy.",
- MessageEnums.INVALID_INPUT_DATA);
- }
- } else {
- permMap.setResourceId(resource.getId());
- permMap = xPermMapService.createResource(permMap);
- newPermMapList.add(permMap);
- }
- }
- }
-
-
- resource.setPermMapList(newPermMapList);
- resource.setAuditList(newAuditMapList);
- return resource;
- }
- @Override
- public boolean deleteResource(Long id) {
- return super.deleteResource(id);
- }
-
- @Override
- public VXResource populateViewBean(XXResource xXResource) {
- VXResource vXResource = super.populateViewBean(xXResource);
- populateAssetProperties(vXResource);
- populatePermList(vXResource);
- return vXResource;
- }
-
- private void populateAssetProperties(VXResource vXResource) {
- XXAsset xxAsset = xADaoManager.getXXAsset().getById(
- vXResource.getAssetId());
- if (xxAsset != null) {
- vXResource.setAssetName(xxAsset.getName());
- }
- vXResource.setAssetType(xxAsset.getAssetType());
- }
-
- private void populateAuditList(VXResource vXResource) {
- SearchCriteria searchCriteria = new SearchCriteria();
- searchCriteria.addParam("resourceId", vXResource.getId());
- VXAuditMapList vXAuditMapList = xAuditMapService
- .searchXAuditMaps(searchCriteria);
- if (vXAuditMapList != null && vXAuditMapList.getResultSize() != 0) {
- List<VXAuditMap> auditMapList = vXAuditMapList.getList();
- vXResource.setAuditList(auditMapList);
- }
- }
-
- private void populatePermList(VXResource vXResource) {
- SearchCriteria searchCriteria = new SearchCriteria();
- searchCriteria.addParam("resourceId", vXResource.getId());
- VXPermMapList vXPermMapList = xPermMapService
- .searchXPermMaps(searchCriteria);
- if (vXPermMapList != null && vXPermMapList.getResultSize() != 0) {
- List<VXPermMap> permMapList = vXPermMapList.getList();
- vXResource.setPermMapList(permMapList);
- }
- }
-
- @Override
- public VXResourceList searchXResources(SearchCriteria searchCriteria) {
-
- VXResourceList returnList;
- UserSessionBase currentUserSession = ContextUtil
- .getCurrentUserSession();
- // If user is system admin
- if (currentUserSession.isUserAdmin()) {
- returnList = super.searchXResources(searchCriteria);
-
- } else {// need to be optimize
- returnList = new VXResourceList();
- int startIndex = searchCriteria.getStartIndex();
- int pageSize = searchCriteria.getMaxRows();
- searchCriteria.setStartIndex(0);
- searchCriteria.setMaxRows(Integer.MAX_VALUE);
- List<XXResource> resultList = (List<XXResource>) searchResources(
- searchCriteria, searchFields, sortFields, returnList);
- List<XXResource> adminPermResourceList = new ArrayList<XXResource>();
- for (XXResource xXResource : resultList) {
- VXResponse vXResponse = xaBizUtil.hasPermission(populateViewBean(xXResource),
- AppConstants.XA_PERM_TYPE_ADMIN);
- if(vXResponse.getStatusCode() == VXResponse.STATUS_SUCCESS){
- adminPermResourceList.add(xXResource);
- }
- }
-
- if (adminPermResourceList.size() > 0) {
- populatePageList(adminPermResourceList, startIndex, pageSize,
- returnList);
- }
- }
- if(returnList!=null && returnList.getResultSize()>0){
- for (VXResource vXResource : returnList.getVXResources()) {
- populateAuditList(vXResource);
- }
- }
- return returnList;
- }
-
- private void populatePageList(List<XXResource> resourceList,
- int startIndex, int pageSize, VXResourceList vxResourceList) {
- List<VXResource> onePageList = new ArrayList<VXResource>();
- for (int i = startIndex; i < pageSize + startIndex
- && i < resourceList.size(); i++) {
- VXResource vXResource = populateViewBean(resourceList.get(i));
- onePageList.add(vXResource);
- }
- vxResourceList.setVXResources(onePageList);
- vxResourceList.setStartIndex(startIndex);
- vxResourceList.setPageSize(pageSize);
- vxResourceList.setResultSize(onePageList.size());
- vxResourceList.setTotalCount(resourceList.size());
-
- }
-
- @Override
- protected XXResource mapViewToEntityBean(VXResource vObj, XXResource mObj, int OPERATION_CONTEXT) {
- super.mapViewToEntityBean(vObj, mObj, OPERATION_CONTEXT);
- mObj.setUdfs(vObj.getUdfs());
- if(vObj!=null && mObj!=null){
- XXPortalUser xXPortalUser= null;
- if(mObj.getAddedByUserId()==null || mObj.getAddedByUserId()==0){
- if(!stringUtil.isEmpty(vObj.getOwner())){
- xXPortalUser=xADaoManager.getXXPortalUser().findByLoginId(vObj.getOwner());
- if(xXPortalUser!=null){
- mObj.setAddedByUserId(xXPortalUser.getId());
- }
- }
- }
- if(mObj.getUpdatedByUserId()==null || mObj.getUpdatedByUserId()==0){
- if(!stringUtil.isEmpty(vObj.getUpdatedBy())){
- xXPortalUser= xADaoManager.getXXPortalUser().findByLoginId(vObj.getUpdatedBy());
- if(xXPortalUser!=null){
- mObj.setUpdatedByUserId(xXPortalUser.getId());
- }
- }
- }
-
- }
- return mObj;
- }
-
- @Override
- protected VXResource mapEntityToViewBean(VXResource vObj, XXResource mObj) {
- super.mapEntityToViewBean(vObj, mObj);
- vObj.setUdfs(mObj.getUdfs());
- populateAssetProperties(vObj);
- if(mObj!=null && vObj!=null){
- XXPortalUser xXPortalUser= null;
- if(stringUtil.isEmpty(vObj.getOwner())){
- xXPortalUser=xADaoManager.getXXPortalUser().getById(mObj.getAddedByUserId());
- if(xXPortalUser!=null){
- vObj.setOwner(xXPortalUser.getLoginId());
- }
- }
- if(stringUtil.isEmpty(vObj.getUpdatedBy())){
- xXPortalUser= xADaoManager.getXXPortalUser().getById(mObj.getUpdatedByUserId());
- if(xXPortalUser!=null){
- vObj.setUpdatedBy(xXPortalUser.getLoginId());
- }
- }
- }
- return vObj;
- }
-
- /**
- * check resource parent path permission for user and group
- * @param vXResource
- */
- public void checkAccess(VXResource vXResource) {
-
- XXAsset xxAsset = xADaoManager.getXXAsset().getById(
- vXResource.getAssetId());
- if (xxAsset == null) {
- throw restErrorUtil
- .createRESTException("Asset not found",
- MessageEnums.DATA_NOT_FOUND, vXResource.getId(),
- null, null);
- }
- int assetType = xxAsset.getAssetType();
-
- if(assetType==AppConstants.ASSET_HDFS){
-
-// int resourceType = vXResource.getResourceType();
- int resourceType = xPolicyService.getResourceType(vXResource);
- List<Integer> resourceTypeList = xaBizUtil
- .getResorceTypeParentHirearchy(resourceType, assetType);
-
- List<String> pathList = new ArrayList<String>();
- String resourceNames = vXResource.getName();
- String[] resourceList = stringUtil.split(resourceNames, ",");
- List<String> resourceArrayList=new ArrayList<String>();
- if(resourceList!=null && resourceList.length>0)
- {
- Collections.addAll(resourceArrayList, resourceList);
- }
-
- for (String resourceName : resourceList) {
- String policyPath = resourceName;
- String[] policyPathParts = policyPath.split(fileSeparator);
-
- if(policyPathParts.length>1){
- pathList.add(fileSeparator);
- }
-
- StringBuffer path = new StringBuffer();
- for (int i = 1; i < policyPathParts.length - 1; i++) {
- path.append(fileSeparator + policyPathParts[i]);
- pathList.add(path.toString());
- }
- if(path!=null){
- if(resourceArrayList.contains(path.toString())){
- continue;
- }
- if(resourceArrayList.contains(path.toString()+"/")){
- continue;
- }
- }
-
- if (pathList != null && pathList.size() != 0) {
- List<VXPermMap> vxPermMaps = vXResource.getPermMapList();
- //update perm list and read and execute
- vxPermMaps=updatePermMaps(vxPermMaps);
- for (VXPermMap vxPermMap : vxPermMaps) {
- //check only read and execution permission
- if (vxPermMap.getPermFor() == AppConstants.XA_PERM_FOR_USER
- &&(vxPermMap.getPermType()==AppConstants.XA_PERM_TYPE_READ ||
- vxPermMap.getPermType()==AppConstants.XA_PERM_TYPE_EXECUTE)) {
- boolean access = checkUserAccess(vxPermMap, pathList,
- vXResource.getAssetId(),
- vXResource.getIsRecursive(), assetType,
- resourceTypeList);
-
- if (!access) {
- XXUser xxUser = xADaoManager.getXXUser().getById(
- vxPermMap.getUserId());
- throw restErrorUtil.createRESTException(
- xxUser.getName() + " may not have "
- + AppConstants.getLabelFor_XAPermType(
- vxPermMap.getPermType()).toLowerCase()
- + " permission on parent folder. Do you want to save this policy?"
- ,
- MessageEnums.OPER_NO_PERMISSION,
- null, "parentPermission", null);
-
- }
- }
- //check only read and execution permission
- if (vxPermMap.getPermFor() == AppConstants.XA_PERM_FOR_GROUP
- &&(vxPermMap.getPermType()==AppConstants.XA_PERM_TYPE_READ ||
- vxPermMap.getPermType()==AppConstants.XA_PERM_TYPE_EXECUTE)) {
- boolean access = checkGroupAccess(vxPermMap, pathList,
- vXResource.getAssetId(),
- vXResource.getIsRecursive(), assetType,
- resourceTypeList);
- if (!access) {
- XXGroup xxGroup = xADaoManager.getXXGroup()
- .getById(vxPermMap.getGroupId());
- throw restErrorUtil.createRESTException(xxGroup
- .getName() + " may not have " + AppConstants
- .getLabelFor_XAPermType(vxPermMap.getPermType()).toLowerCase()
- + " permission on parent folder. Do you want to save this policy?"
- ,
- MessageEnums.OPER_NO_PERMISSION, null,
- "parentPermission", null);
- }
- }
- }
- }
- }
- }
- }
-
- /**
- * check user permission
- *
- * @param vxPermMap
- * @param pathList
- * @return
- */
- public boolean checkUserAccess(VXPermMap vxPermMap, List<String> pathList,
- Long assetId, int isRecursive, int assetType,
- List<Integer> resourceTypeList) {
- boolean isAccess = false;
- boolean isRecursivlyAllowed;
- // all possible path and check access on all path
- for (int i = 0; i < pathList.size(); i++) {
- isAccess = false;
- isRecursivlyAllowed = false;
- HashMap<String, Object> accessMap = fetchUserAccessMap(
- vxPermMap.getUserId(), vxPermMap.getPermType(),
- pathList.get(i), assetType, assetId, isRecursive,
- resourceTypeList);
- //isAccess = Boolean.getBoolean(""+accessMap.get("isAccess"));
- //isRecursivlyAllowed = Boolean.getBoolean(""+accessMap.get("isRecursive"));
- isAccess=(Boolean)accessMap.get("isAccess");
- isRecursivlyAllowed=(Boolean)accessMap.get("isRecursive");
- // if user have recursively access then return true
- if (isAccess && isRecursivlyAllowed) {
- return true;
- }
- // access fail for root folder return false
- if (!isAccess) {
- break;
- }
-
- }
- return isAccess;
- }
-
- /**
- * check group permission on path
- *
- * @param vxPermMap
- * @param pathList
- * @return
- */
- public boolean checkGroupAccess(VXPermMap vxPermMap, List<String> pathList,
- Long assetId, int isRecursive, int assetType,
- List<Integer> resourceTypeList) {
- boolean isAccess = false;
- boolean isRecursivlyAllowed;
- for (int i = 0; i < pathList.size(); i++) {
- isAccess = false;
- isRecursivlyAllowed = false;
- HashMap<String, Object> accessMap = fetchGroupAccessMap(
- vxPermMap.getGroupId(), vxPermMap.getPermType(),
- pathList.get(i), assetType, assetId, isRecursive,
- resourceTypeList);
- isAccess = Boolean.getBoolean(""+accessMap.get("isAccess"));
- isRecursivlyAllowed = Boolean.getBoolean(""+accessMap.get("isRecursive"));
- if (isAccess && isRecursivlyAllowed) {
- return true;
- }
- if (!isAccess) {
- break;
- }
-
- }
- return isAccess;
- }
-
- public HashMap<String, Object> fetchUserAccessMap(Long userId,
- int permType, String path, int assetType, Long assetId,
- int isRecursive, List<Integer> resourceTypeList) {
- HashMap<String, Object> accessMap = new HashMap<String, Object>();
- boolean isAccess = false;
- List<XXGroup> xGroupList = xADaoManager.getXXGroup().findByUserId(
- userId);
- boolean isRecursivlyAllowed = false;
- List<XXResource> xXResourceList = null;
- if (assetType == AppConstants.ASSET_HDFS) {
- xXResourceList = xADaoManager.getXXResource().findByAssetId(
- assetId);
- //this code block is to add record of 'public' group in group_user mapping list.
- XXGroup xXGroupPublic = xADaoManager.getXXGroup().
- findByGroupName(XAConstants.GROUP_PUBLIC);
- if (xXGroupPublic != null
- && xXGroupPublic.getName().trim()
- .equalsIgnoreCase(XAConstants.GROUP_PUBLIC)) {
- if(xGroupList!=null){
- xGroupList.add(xXGroupPublic);
- }else{
- xGroupList=new ArrayList<XXGroup>();
- xGroupList.add(xXGroupPublic);
- }
- }
- } else {
- xXResourceList = xADaoManager.getXXResource()
- .findByAssetIdAndResourceTypes(assetId, resourceTypeList);
- }
- String expandedName = xaBizUtil.replaceMetaChars(path);
- if (xXResourceList != null) {
- // If resource name is comma separated, then we need to check each
- // of the resources
- for (XXResource xResource : xXResourceList) {
- String resource = xResource.getName();
-
- if (resource == null || resource.isEmpty()) {
- logger.debug("Resource name not found for resourceId : "
- + xResource.getId());
- throw restErrorUtil.createRESTException(
- "Resource name not found.",
- MessageEnums.DATA_NOT_FOUND);
- }
-
- String[] dbResourceNameList = resource.split(",");
- boolean matchFound = false;
- for (String dbResourceName : dbResourceNameList) {
- String[] requestResNameList = expandedName.split(",");
- for (String resourceName : requestResNameList) {
- if (xaBizUtil.comparePathsForExactMatch(resourceName,
- dbResourceName)) {
- matchFound = true;
- } else {
- // resource name has a file extension then don't
- // append "/*"
- // "/*" is required for directory matching
- if (xResource.getIsRecursive() == AppConstants.BOOL_TRUE) {
- matchFound = xaBizUtil
- .isRecursiveWildCardMatch(resourceName,
- dbResourceName);
- } else {
- matchFound = xaBizUtil
- .nonRecursiveWildCardMatch(
- resourceName, dbResourceName);
- }
- }
- if (matchFound) {
- break;
- }
- }
- if (matchFound) {
- break;
- }
- }
- if (matchFound) {
- // get the perms for this resource
- List<XXPermMap> permMapList = xADaoManager.getXXPermMap()
- .findByResourceId(xResource.getId());
- for (XXPermMap permMap : permMapList) {
- if (permMap.getPermType() == permType) {
- if (permMap.getPermFor() == AppConstants.XA_PERM_FOR_GROUP
- && xaBizUtil.isGroupInList(
- permMap.getGroupId(), xGroupList)) {
- isAccess = true;
- isRecursivlyAllowed = xResource.getIsRecursive() == AppConstants.BOOL_TRUE ? true
- : false;
- } else if (permMap.getPermFor() == AppConstants.XA_PERM_FOR_USER
- && permMap.getUserId().equals(userId)) {
- isAccess = true;
- isRecursivlyAllowed = xResource.getIsRecursive() == AppConstants.BOOL_TRUE ? true
- : false;
- }
- }
- }
- }
- }
- }
- accessMap.put("isAccess", isAccess);
- accessMap.put("isRecursive", isRecursivlyAllowed);
- return accessMap;
- }
-
- public HashMap<String, Object> fetchGroupAccessMap(Long groupId,
- int permType, String path, int assetType, Long assetId,
- int isRecursive, List<Integer> resourceTypeList) {
-
- boolean isAccess = false;
- boolean isRecursivlyAllowed = false;
- HashMap<String, Object> accessMap = new HashMap<String, Object>();
- List<XXResource> xXResourceList = new ArrayList<XXResource>();
-
- if (assetType == AppConstants.ASSET_HDFS) {
- xXResourceList = xADaoManager.getXXResource().findByAssetId(
- assetId);
- } else {
- xXResourceList = xADaoManager.getXXResource()
- .findByAssetIdAndResourceTypes(assetId, resourceTypeList);
- }
-
- String expandedName = xaBizUtil.replaceMetaChars(path);
-
- for (XXResource xResource : xXResourceList) {
- String resource = xResource.getName();
-
- if (resource == null || resource.isEmpty()) {
- logger.debug("Resource name not found for resourceId : "
- + xResource.getId());
- throw restErrorUtil.createRESTException(
- "Resource name not found.",
- MessageEnums.DATA_NOT_FOUND);
- }
-
- String[] dbResourceNameList = resource.split(",");
- boolean matchFound = false;
-
- for (String dbResourceName : dbResourceNameList) {
-
- String[] requestResNameList = expandedName.split(",");
- for (String resourceName : requestResNameList) {
- if (xaBizUtil.comparePathsForExactMatch(resourceName,
- dbResourceName)) {
- matchFound = true;
- } else {
- // resource name has a file extension then don't
- // append "/*"
- // "/*" is required for directory matching
- if (xResource.getIsRecursive() == AppConstants.BOOL_TRUE) {
- matchFound = xaBizUtil
- .isRecursiveWildCardMatch(resourceName,
- dbResourceName);
- } else {
- matchFound = xaBizUtil
- .nonRecursiveWildCardMatch(
- resourceName, dbResourceName);
- }
- }
- if (matchFound) {
- break;
- }
- }
- if (matchFound) {
- break;
- }
- }
- if (matchFound) {
- // get the perms for this resource
- List<XXPermMap> permMapList = xADaoManager.getXXPermMap()
- .findByResourceId(xResource.getId());
- for (XXPermMap permMap : permMapList) {
- if (permMap.getPermType() == permType) {
- if (permMap.getPermFor() == AppConstants.XA_PERM_FOR_GROUP
- && permMap.getGroupId().doubleValue() == groupId.doubleValue()) {
- isAccess = true;
- isRecursivlyAllowed = (xResource.getIsRecursive() == AppConstants.BOOL_TRUE);
- }
- }
- }
- }
- }
-
- accessMap.put("isAccess", isAccess);
- accessMap.put("isRecursive", isRecursivlyAllowed);
- return accessMap;
- }
-
- public List<VXPermMap> updatePermMaps(List<VXPermMap> vxPermMaps) {
- List<VXPermMap> updatedPermList = new ArrayList<VXPermMap>();
-
- List<Long> listOfUser = new ArrayList<Long>();
- List<Long> listOfGroup = new ArrayList<Long>();
-
- //[1] : Populate perm maps for user and groups
- for (VXPermMap vxPermMap : vxPermMaps) {
- if (vxPermMap.getPermFor() == AppConstants.XA_PERM_FOR_USER) {
- if (!listOfUser.contains(vxPermMap.getUserId())) {
- listOfUser.add(vxPermMap.getUserId());
- }
- } else if (vxPermMap.getPermFor() == AppConstants.XA_PERM_FOR_GROUP) {
- if (!listOfGroup.contains(vxPermMap.getGroupId())) {
- listOfGroup.add(vxPermMap.getGroupId());
- }
- }
- }
-
- HashMap<Long, HashMap<Integer, VXPermMap>> userPermMap =
- new HashMap<Long, HashMap<Integer, VXPermMap>>();
-
- for (Long userId : listOfUser) {
- HashMap<Integer, VXPermMap> userPerm = new HashMap<Integer, VXPermMap>();
- for (VXPermMap vxPermMap : vxPermMaps) {
- if (vxPermMap.getPermFor() == AppConstants.XA_PERM_FOR_USER
- && vxPermMap.getUserId() == userId) {
- userPerm.put(vxPermMap.getPermType(), vxPermMap);
- }
- }
- userPermMap.put(userId, userPerm);
- }
-
- //[2] :
- HashMap<Long, HashMap<Integer, VXPermMap>> groupPermMap =
- new HashMap<Long, HashMap<Integer, VXPermMap>>();
-
- for (Long groupId : listOfGroup) {
- HashMap<Integer, VXPermMap> groupPerm = new HashMap<Integer, VXPermMap>();
- for (VXPermMap vxPermMap : vxPermMaps) {
- Long permGroupId = vxPermMap.getGroupId();
- int permFor = vxPermMap.getPermFor();
- if (permFor == AppConstants.XA_PERM_FOR_GROUP
- && permGroupId.equals(groupId)) {
- groupPerm.put(vxPermMap.getPermType(), vxPermMap);
- }
- }
- groupPermMap.put(groupId, groupPerm);
- }
-
- for (Long userId : listOfUser) {
- HashMap<Integer, VXPermMap> map = userPermMap.get(userId);
- VXPermMap vxPermMap = null;
-
- for (Entry<Integer, VXPermMap> perm : map.entrySet()) {
- vxPermMap = perm.getValue();
- break;
- }
-
- if (map.size() > 0 && map.get(AppConstants.XA_PERM_TYPE_READ) == null) {
- vxPermMap.setPermType(AppConstants.XA_PERM_TYPE_READ);
- map.put(AppConstants.XA_PERM_TYPE_READ, vxPermMap);
- }
-
- if (map.size() > 1 && map.get(AppConstants.XA_PERM_TYPE_EXECUTE) == null) {
- vxPermMap.setPermType(AppConstants.XA_PERM_TYPE_EXECUTE);
- map.put(AppConstants.XA_PERM_TYPE_EXECUTE, vxPermMap);
- }
- userPermMap.put(userId, map);
- }
-
- for (Long groupId : listOfGroup) {
- HashMap<Integer, VXPermMap> map = groupPermMap.get(groupId);
- VXPermMap vxPermMap = null;
-
- for (Entry<Integer, VXPermMap> perm : map.entrySet()) {
- vxPermMap = perm.getValue();
- break;
- }
-
- if (map.size() > 0 && map.get(AppConstants.XA_PERM_TYPE_READ) == null) {
- vxPermMap.setPermType(AppConstants.XA_PERM_TYPE_READ);
- map.put(AppConstants.XA_PERM_TYPE_READ, vxPermMap);
- }
-
- if (map.size() > 1 && map.get(AppConstants.XA_PERM_TYPE_EXECUTE) == null) {
- vxPermMap.setPermType(AppConstants.XA_PERM_TYPE_EXECUTE);
- map.put(AppConstants.XA_PERM_TYPE_EXECUTE, vxPermMap);
- }
- groupPermMap.put(groupId, map);
- }
-
- // [3] :
- for (Entry<Long, HashMap<Integer, VXPermMap>> entry : userPermMap
- .entrySet()) {
- for (Entry<Integer, VXPermMap> innerEntry : entry.getValue()
- .entrySet()) {
- updatedPermList.add(innerEntry.getValue());
- }
- }
-
- for (Entry<Long, HashMap<Integer, VXPermMap>> entry : groupPermMap
- .entrySet()) {
- for (Entry<Integer, VXPermMap> innerEntry : entry.getValue()
- .entrySet()) {
- updatedPermList.add(innerEntry.getValue());
- }
- }
-
- return updatedPermList;
- }
-
- public List<XXTrxLog> getTransactionLog(VXResource vResource, String action){
- return getTransactionLog(vResource, null, action);
- }
-
- public List<XXTrxLog> getTransactionLog(VXResource vObj, XXResource mObj, String action){
- if(vObj == null && (action == null || !action.equalsIgnoreCase("update"))){
- return null;
- }
-
- XXAsset xAsset = xADaoManager.getXXAsset().getById(vObj.getAssetId());
- String parentObjectName = xAsset.getName();
-
- List<XXTrxLog> trxLogList = new ArrayList<XXTrxLog>();
- Field[] fields = vObj.getClass().getDeclaredFields();
-
- Field nameField;
- try {
- nameField = vObj.getClass().getDeclaredField("name");
- nameField.setAccessible(true);
- String objectName = ""+nameField.get(vObj);
-
- for(Field field : fields){
- field.setAccessible(true);
- String fieldName = field.getName();
- if(!trxLogAttrs.containsKey(fieldName)){
- continue;
- }
-
- int policyType = vObj.getAssetType();
- if(policyType == AppConstants.ASSET_HDFS){
- String[] ignoredAttribs = {"tableType", "columnType", "isEncrypt", "databases",
- "tables", "columnFamilies", "columns", "udfs"};
- if(ArrayUtils.contains(ignoredAttribs, fieldName)){
- continue;
- }
- } else if(policyType == AppConstants.ASSET_HIVE) {
- String[] ignoredAttribs = {"name", "isRecursive", "isEncrypt", "columnFamilies"};
- if(ArrayUtils.contains(ignoredAttribs, fieldName)){
- continue;
- }
- } else if(policyType == AppConstants.ASSET_HBASE){
- String[] ignoredAttribs = {"name", "tableType", "columnType", "isRecursive", "databases",
- "udfs"};
- if(ArrayUtils.contains(ignoredAttribs, fieldName)){
- continue;
- }
- } else if(policyType == AppConstants.ASSET_KNOX || policyType == AppConstants.ASSET_STORM){
- String[] ignoredAttribs = {"name", "tableType", "columnType", "isEncrypt", "databases",
- "tables", "columnFamilies", "columns", "udfs"};
- if(ArrayUtils.contains(ignoredAttribs, fieldName)){
- continue;
- }
- }
-
- VTrxLogAttr vTrxLogAttr = trxLogAttrs.get(fieldName);
-
- XXTrxLog xTrxLog = new XXTrxLog();
- xTrxLog.setAttributeName(vTrxLogAttr.getAttribUserFriendlyName());
-
- String value = null;
- boolean isEnum = vTrxLogAttr.isEnum();
- if(isEnum){
- String enumName = XXResource.getEnumName(fieldName);
- if(enumName==null && fieldName.equals("assetType")){
- enumName="CommonEnums.AssetType";
- }
- int enumValue = field.get(vObj) == null ? 0 : Integer.parseInt(""+field.get(vObj));
- value = xaEnumUtil.getLabel(enumName, enumValue);
- } else {
- value = ""+field.get(vObj);
- if(value == null || value.equalsIgnoreCase("null")){
- continue;
- }
- }
-
- if(action.equalsIgnoreCase("create")){
- if(stringUtil.isEmpty(value)){
- continue;
- }
- xTrxLog.setNewValue(value);
- } else if(action.equalsIgnoreCase("delete")){
- xTrxLog.setPreviousValue(value);
- } else if(action.equalsIgnoreCase("update")){
- String oldValue = null;
- Field[] mFields = mObj.getClass().getDeclaredFields();
- for(Field mField : mFields){
- mField.setAccessible(true);
- String mFieldName = mField.getName();
- if(fieldName.equalsIgnoreCase(mFieldName)){
- if(isEnum){
- String enumName = XXResource.getEnumName(mFieldName);
- if(enumName==null && mFieldName.equals("assetType")){
- enumName="CommonEnums.AssetType";
- }
- int enumValue = mField.get(mObj) == null ? 0 : Integer.parseInt(""+mField.get(mObj));
- oldValue = xaEnumUtil.getLabel(enumName, enumValue);
- } else {
- oldValue = mField.get(mObj)+"";
- }
- break;
- }
- }
- if(value.equalsIgnoreCase(oldValue) && !fieldName.equals("policyName")){
- continue;
- }
- xTrxLog.setPreviousValue(oldValue);
- xTrxLog.setNewValue(value);
- }
-
- xTrxLog.setAction(action);
- xTrxLog.setObjectClassType(AppConstants.CLASS_TYPE_XA_RESOURCE);
- xTrxLog.setObjectId(vObj.getId());
- xTrxLog.setParentObjectClassType(AppConstants.CLASS_TYPE_XA_ASSET);
- xTrxLog.setParentObjectId(vObj.getAssetId());
- xTrxLog.setParentObjectName(parentObjectName);
- xTrxLog.setObjectName(objectName);
- trxLogList.add(xTrxLog);
-
- }
-
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (NoSuchFieldException e) {
- e.printStackTrace();
- } catch (SecurityException e) {
- e.printStackTrace();
- }
-
- if(trxLogList.size()==0){
- XXTrxLog xTrxLog = new XXTrxLog();
- xTrxLog.setAction(action);
- xTrxLog.setObjectClassType(AppConstants.CLASS_TYPE_XA_RESOURCE);
- xTrxLog.setObjectId(vObj.getId());
- xTrxLog.setObjectName(vObj.getName());
- xTrxLog.setParentObjectClassType(AppConstants.CLASS_TYPE_XA_ASSET);
- xTrxLog.setParentObjectId(vObj.getAssetId());
- xTrxLog.setParentObjectName(parentObjectName);
- trxLogList.add(xTrxLog);
- }
-
- return trxLogList;
- }
-
- @Override
- public VXResource readResource(Long id){
- VXResource vXResource = super.readResource(id);
-
- VXResponse vXResponse = xaBizUtil.hasPermission(vXResource,
- AppConstants.XA_PERM_TYPE_ADMIN);
- if (vXResponse.getStatusCode() == VXResponse.STATUS_ERROR) {
- throw restErrorUtil.createRESTException(
- "You don't have permission to perform this action",
- MessageEnums.OPER_NO_PERMISSION, id, "Resource",
- "Trying to read unauthorized resource.");
- }
-
- populateAssetProperties(vXResource);
- populatePermList(vXResource);
- populateAuditList(vXResource);
- return vXResource;
- }
-
- public VXResourceList searchXResourcesWithoutLogin(SearchCriteria searchCriteria) {
- VXResourceList returnList = super.searchXResources(searchCriteria);
- if(returnList!=null && returnList.getResultSize()>0){
- for (VXResource vXResource : returnList.getVXResources()) {
- populateAuditList(vXResource);
- }
- }
- return returnList;
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XResourceServiceBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XResourceServiceBase.java b/security-admin/src/main/java/com/xasecure/service/XResourceServiceBase.java
deleted file mode 100644
index 4007c34..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XResourceServiceBase.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-/**
- *
- */
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-import com.xasecure.view.*;
-import com.xasecure.service.*;
-
-public abstract class XResourceServiceBase<T extends XXResource, V extends VXResource>
- extends AbstractBaseResourceService<T, V> {
- public static final String NAME = "XResource";
-
- public XResourceServiceBase() {
-
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected XXResource mapViewToEntityBean(VXResource vObj, XXResource mObj, int OPERATION_CONTEXT) {
- mObj.setName( vObj.getName());
- mObj.setDescription( vObj.getDescription());
- mObj.setResourceType( vObj.getResourceType());
- mObj.setAssetId( vObj.getAssetId());
- mObj.setParentId( vObj.getParentId());
- mObj.setParentPath( vObj.getParentPath());
- mObj.setIsEncrypt( vObj.getIsEncrypt());
- mObj.setIsRecursive( vObj.getIsRecursive());
- mObj.setResourceGroup( vObj.getResourceGroup());
- mObj.setDatabases( vObj.getDatabases());
- mObj.setTables( vObj.getTables());
- mObj.setColumnFamilies( vObj.getColumnFamilies());
- mObj.setColumns( vObj.getColumns());
- mObj.setUdfs( vObj.getUdfs());
- mObj.setResourceStatus( vObj.getResourceStatus());
- mObj.setTableType( vObj.getTableType());
- mObj.setColumnType( vObj.getColumnType());
- mObj.setPolicyName( vObj.getPolicyName());
- mObj.setTopologies( vObj.getTopologies());
- mObj.setServices( vObj.getServices());
- return mObj;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected VXResource mapEntityToViewBean(VXResource vObj, XXResource mObj) {
- vObj.setName( mObj.getName());
- vObj.setDescription( mObj.getDescription());
- vObj.setResourceType( mObj.getResourceType());
- vObj.setAssetId( mObj.getAssetId());
- vObj.setParentId( mObj.getParentId());
- vObj.setParentPath( mObj.getParentPath());
- vObj.setIsEncrypt( mObj.getIsEncrypt());
- vObj.setIsRecursive( mObj.getIsRecursive());
- vObj.setResourceGroup( mObj.getResourceGroup());
- vObj.setDatabases( mObj.getDatabases());
- vObj.setTables( mObj.getTables());
- vObj.setColumnFamilies( mObj.getColumnFamilies());
- vObj.setColumns( mObj.getColumns());
- vObj.setUdfs( mObj.getUdfs());
- vObj.setResourceStatus( mObj.getResourceStatus());
- vObj.setTableType( mObj.getTableType());
- vObj.setColumnType( mObj.getColumnType());
- vObj.setPolicyName( mObj.getPolicyName());
- vObj.setTopologies( mObj.getTopologies());
- vObj.setServices( mObj.getServices());
- return vObj;
- }
-
- /**
- * @param searchCriteria
- * @return
- */
- public VXResourceList searchXResources(SearchCriteria searchCriteria) {
- VXResourceList returnList = new VXResourceList();
- List<VXResource> xResourceList = new ArrayList<VXResource>();
-
- @SuppressWarnings("unchecked")
- List<XXResource> resultList = (List<XXResource>)searchResources(searchCriteria,
- searchFields, sortFields, returnList);
-
- // Iterate over the result list and create the return list
- for (XXResource gjXResource : resultList) {
- @SuppressWarnings("unchecked")
- VXResource vXResource = populateViewBean((T)gjXResource);
- xResourceList.add(vXResource);
- }
-
- returnList.setVXResources(xResourceList);
- return returnList;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XTrxLogService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XTrxLogService.java b/security-admin/src/main/java/com/xasecure/service/XTrxLogService.java
deleted file mode 100644
index 66c445b..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XTrxLogService.java
+++ /dev/null
@@ -1,461 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-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.TypedQuery;
-import javax.persistence.criteria.CriteriaBuilder;
-import javax.persistence.criteria.CriteriaQuery;
-import javax.persistence.criteria.ParameterExpression;
-import javax.persistence.criteria.Predicate;
-import javax.persistence.criteria.Root;
-import javax.persistence.criteria.Subquery;
-import javax.persistence.metamodel.EntityType;
-import javax.persistence.metamodel.Metamodel;
-import javax.persistence.metamodel.SingularAttribute;
-
-import com.xasecure.common.SearchCriteria;
-import com.xasecure.common.SearchField;
-import com.xasecure.common.SortField;
-import com.xasecure.common.SortField.SORT_ORDER;
-import com.xasecure.db.XADaoManager;
-import com.xasecure.view.*;
-import com.xasecure.entity.*;
-import com.xasecure.entity.view.VXXTrxLog;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Service;
-
-@Service
-@Scope("singleton")
-public class XTrxLogService extends XTrxLogServiceBase<XXTrxLog, VXTrxLog> {
- @Autowired
- XADaoManager xADaoManager;
- public XTrxLogService(){
- searchFields.add(new SearchField("attributeName", "obj.attributeName",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
- searchFields.add(new SearchField("action", "obj.action",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
- searchFields.add(new SearchField("sessionId", "obj.sessionId",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL));
- searchFields.add(new SearchField("startDate", "obj.createTime",
- SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN));
- searchFields.add(new SearchField("endDate", "obj.createTime",
- SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.LESS_EQUAL_THAN));
- searchFields.add(new SearchField("owner", "obj.addedByUserId",
- SearchField.DATA_TYPE.INT_LIST, SearchField.SEARCH_TYPE.FULL));
- searchFields.add(new SearchField("objectClassType", "obj.objectClassType",
- SearchField.DATA_TYPE.INT_LIST, SearchField.SEARCH_TYPE.FULL));
-
- sortFields.add(new SortField("createDate", "obj.createTime", true, SORT_ORDER.DESC));
- }
-
- @Override
- protected void validateForCreate(VXTrxLog vObj) {}
-
- @Override
- protected void validateForUpdate(VXTrxLog vObj, XXTrxLog mObj) {}
-
- @Override
- public VXTrxLogList searchXTrxLogs(SearchCriteria searchCriteria) {
-
- EntityManager em = daoMgr.getEntityManager();
- CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
- Metamodel entityMetaModel = em.getMetamodel();
- Class<VXXTrxLog> klass = VXXTrxLog.class;
- EntityType<VXXTrxLog> entityType = entityMetaModel.entity(klass);
- CriteriaQuery<VXXTrxLog> selectCQ = criteriaBuilder.createQuery(klass);
- Root<VXXTrxLog> rootEntityType = selectCQ.from(klass);
- Predicate predicate = criteriaBuilder.conjunction();
- String fieldName=null;
- String clientFieldName =null;
- Object paramValue = null;
- boolean isListValue = false;
- SingularAttribute attr =null;
- Collection<Number> intValueList = null;
- Date fieldValue =null;
- Predicate stringPredicate =null;
- Predicate intPredicate = null;
- Predicate datePredicate =null;
- Map<String, Object> paramList = searchCriteria.getParamList();
- for(String key : paramList.keySet()){
- for(SearchField searchField : searchFields){
- fieldName = searchField.getFieldName();
- clientFieldName = searchField.getClientFieldName();
- paramValue = paramList.get(key);
- isListValue = false;
- if (paramValue != null && paramValue instanceof Collection) {
- isListValue = true;
- }
- if(fieldName != null){
- fieldName = fieldName.contains(".") ? fieldName.substring(fieldName.indexOf(".") + 1) : fieldName;
- }
- if(key.equalsIgnoreCase(clientFieldName)){
- // build where clause depending upon given parameters
- if(searchField.getDataType() == SearchField.DATA_TYPE.STRING) {
- // build where clause for String datatypes
- attr = entityType.getSingularAttribute(fieldName);
- if(attr != null){
- stringPredicate = criteriaBuilder.equal(rootEntityType.get(attr), paramValue);
- if (searchField.getSearchType().equals(SearchField.SEARCH_TYPE.PARTIAL)) {
- String val = "%" + paramValue + "%";
- stringPredicate = criteriaBuilder.like(rootEntityType.get(attr), val);
- }
- predicate = criteriaBuilder.and(predicate, stringPredicate);
-
- }
- } else if (searchField.getDataType() == SearchField.DATA_TYPE.INT_LIST ||
- isListValue && searchField.getDataType() == SearchField.DATA_TYPE.INTEGER) {
- // build where clause for integer lists or integers datatypes
- intValueList = null;
- if (paramValue != null && (paramValue instanceof Integer || paramValue instanceof Long)) {
- intValueList = new ArrayList<Number>();
- intValueList.add((Number) paramValue);
- } else {
- intValueList = (Collection<Number>) paramValue;
- }
- for(Number value : intValueList){
- attr = entityType.getSingularAttribute(fieldName);
- if(attr != null){
- intPredicate = criteriaBuilder.equal(rootEntityType.get(attr), value);
- predicate = criteriaBuilder.and(predicate, intPredicate);
- }
- }
-
- } else if (searchField.getDataType() == SearchField.DATA_TYPE.DATE){
- // build where clause for date datatypes
- fieldValue = (Date) paramList.get(searchField
- .getClientFieldName());
- attr = entityType.getSingularAttribute(fieldName);
- if (fieldValue != null) {
- if (searchField.getCustomCondition() == null) {
- datePredicate = criteriaBuilder.equal(rootEntityType.get(attr), fieldValue);
- if (searchField.getSearchType().equals(SearchField.SEARCH_TYPE.LESS_THAN)) {
- datePredicate = criteriaBuilder.lessThan(rootEntityType.get(attr), fieldValue);
- } else if (searchField.getSearchType().equals(SearchField.SEARCH_TYPE.LESS_EQUAL_THAN)) {
- datePredicate = criteriaBuilder.lessThanOrEqualTo(rootEntityType.get(attr), fieldValue);
- } else if (searchField.getSearchType().equals(SearchField.SEARCH_TYPE.GREATER_THAN)) {
- datePredicate = criteriaBuilder.greaterThan(rootEntityType.get(attr), fieldValue);
- } else if (searchField.getSearchType().equals(SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN)) {
- datePredicate = criteriaBuilder.greaterThanOrEqualTo(rootEntityType.get(attr), fieldValue);
- } else {
- datePredicate = criteriaBuilder.equal(rootEntityType.get(attr), fieldValue);
- }
- predicate = criteriaBuilder.and(predicate, datePredicate);
- }
- }
-
- }
- }
- }
- }
-
- selectCQ.where(predicate);
- if(searchCriteria.getSortType()!=null && searchCriteria.getSortType().equalsIgnoreCase("asc")){
- selectCQ.orderBy(criteriaBuilder.asc(rootEntityType.get("createTime")));
- }else{
- selectCQ.orderBy(criteriaBuilder.desc(rootEntityType.get("createTime")));
- }
- int startIndex = searchCriteria.getStartIndex();
- int pageSize = searchCriteria.getMaxRows();
- List<VXXTrxLog> resultList = em.createQuery(selectCQ).setFirstResult(startIndex).setMaxResults(pageSize).getResultList();
- VXTrxLogList vxTrxLogList = new VXTrxLogList();
- vxTrxLogList.setStartIndex(startIndex);
- vxTrxLogList.setPageSize(pageSize);
- List<VXTrxLog> trxLogList = new ArrayList<VXTrxLog>();
- XXPortalUser xXPortalUser=null;
- for(VXXTrxLog xTrxLog : resultList){
- VXTrxLog trxLog = mapCustomViewToViewObj(xTrxLog);
- xXPortalUser=null;
- if(trxLog.getUpdatedBy()!=null){
- xXPortalUser= xADaoManager.getXXPortalUser().getById(
- Long.parseLong(trxLog.getUpdatedBy()));
- }
- if(xXPortalUser!=null){
- trxLog.setOwner(xXPortalUser.getLoginId());
- }
- trxLogList.add(trxLog);
- }
- //vxTrxLogList.setTotalCount(count);
- vxTrxLogList.setVXTrxLogs(trxLogList);
- return vxTrxLogList;
- }
-
- public Long searchXTrxLogsCount(SearchCriteria searchCriteria) {
-
- EntityManager em = daoMgr.getEntityManager();
- CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
- Class<VXXTrxLog> klass = VXXTrxLog.class;
- CriteriaQuery<VXXTrxLog> criteriaQuery = criteriaBuilder.createQuery(klass);
- Root<VXXTrxLog> rootEntityType = criteriaQuery.from(klass);
- Metamodel entityMetaModel = em.getMetamodel();
- EntityType<VXXTrxLog> entityType = entityMetaModel.entity(klass);
- CriteriaQuery<VXXTrxLog> selectCQ = criteriaQuery.select(rootEntityType);
- Map<String, Object> paramList = searchCriteria.getParamList();
- CriteriaQuery<Long> countCQ = criteriaBuilder.createQuery(Long.class);
- Root<VXXTrxLog> countEntityType = countCQ.from(klass);
- Predicate predicate = criteriaBuilder.conjunction();
- String fieldName=null;
- String clientFieldName =null;
- Object paramValue = null;
- boolean isListValue = false;
- SingularAttribute attr =null;
- Collection<Number> intValueList = null;
- Date fieldValue =null;
- Predicate stringPredicate =null;
- Predicate intPredicate = null;
- Predicate datePredicate =null;
- for(String key : paramList.keySet()){
- for(SearchField searchField : searchFields){
- fieldName = searchField.getFieldName();
- clientFieldName = searchField.getClientFieldName();
- paramValue = paramList.get(key);
- isListValue = false;
- if (paramValue != null && paramValue instanceof Collection) {
- isListValue = true;
- }
- if(fieldName != null){
- fieldName = fieldName.contains(".") ? fieldName.substring(fieldName.indexOf(".") + 1) : fieldName;
- }
- if(key.equalsIgnoreCase(clientFieldName)){
- // build where clause depending upon given parameters
- if(searchField.getDataType() == SearchField.DATA_TYPE.STRING) {
- // build where clause for String datatypes
- attr = entityType.getSingularAttribute(fieldName);
- if(attr != null){
- stringPredicate = criteriaBuilder.equal(rootEntityType.get(attr), paramValue);
- if (searchField.getSearchType().equals(SearchField.SEARCH_TYPE.PARTIAL)) {
- String val = "%" + paramValue + "%";
- stringPredicate = criteriaBuilder.like(rootEntityType.get(attr), val);
- }
- predicate = criteriaBuilder.and(predicate, stringPredicate);
-
- }
- } else if (searchField.getDataType() == SearchField.DATA_TYPE.INT_LIST ||
- isListValue && searchField.getDataType() == SearchField.DATA_TYPE.INTEGER) {
- // build where clause for integer lists or integers datatypes
- intValueList = null;
- if (paramValue != null && (paramValue instanceof Integer || paramValue instanceof Long)) {
- intValueList = new ArrayList<Number>();
- intValueList.add((Number) paramValue);
- } else {
- intValueList = (Collection<Number>) paramValue;
- }
- for(Number value : intValueList){
- attr = entityType.getSingularAttribute(fieldName);
- if(attr != null){
- intPredicate = criteriaBuilder.equal(rootEntityType.get(attr), value);
- predicate = criteriaBuilder.and(predicate, intPredicate);
- }
- }
-
- } else if (searchField.getDataType() == SearchField.DATA_TYPE.DATE){
- // build where clause for date datatypes
- fieldValue = (Date) paramList.get(searchField
- .getClientFieldName());
- attr = entityType.getSingularAttribute(fieldName);
- if (fieldValue != null) {
- if (searchField.getCustomCondition() == null) {
- datePredicate = criteriaBuilder.equal(rootEntityType.get(attr), fieldValue);
- if (searchField.getSearchType().equals(SearchField.SEARCH_TYPE.LESS_THAN)) {
- datePredicate = criteriaBuilder.lessThan(rootEntityType.get(attr), fieldValue);
- } else if (searchField.getSearchType().equals(SearchField.SEARCH_TYPE.LESS_EQUAL_THAN)) {
- datePredicate = criteriaBuilder.lessThanOrEqualTo(rootEntityType.get(attr), fieldValue);
- } else if (searchField.getSearchType().equals(SearchField.SEARCH_TYPE.GREATER_THAN)) {
- datePredicate = criteriaBuilder.greaterThan(rootEntityType.get(attr), fieldValue);
- } else if (searchField.getSearchType().equals(SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN)) {
- datePredicate = criteriaBuilder.greaterThanOrEqualTo(rootEntityType.get(attr), fieldValue);
- } else {
- datePredicate = criteriaBuilder.equal(rootEntityType.get(attr), fieldValue);
- }
- predicate = criteriaBuilder.and(predicate, datePredicate);
- }
- }
-
- }
- }
- }
- }
- countCQ.select(criteriaBuilder.count(rootEntityType)).where(predicate);
- List<Long> countList = em.createQuery(countCQ).getResultList();
- Long count = 0L;
- if(countList != null && countList.size() > 0) {
- count = countList.get(0);
- if(count == null) {
- count = 0L;
- }
- }
- return count;
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- private Predicate buildWhereClause(Predicate predicate, Map<String, Object> paramList, EntityType<XXTrxLog> trxLogEntity,
- CriteriaBuilder criteriaBuilder, Root<XXTrxLog> root){
-
- for(String key : paramList.keySet()) {
- for(SearchField searchField : searchFields){
-
- String fieldName = searchField.getFieldName();
- String clientFieldName = searchField.getClientFieldName();
-
- Object paramValue = paramList.get(key);
- boolean isListValue = false;
-
- if (paramValue != null && paramValue instanceof Collection) {
- isListValue = true;
- }
-
- if(fieldName != null){
- fieldName = fieldName.contains(".") ? fieldName.substring(fieldName.indexOf(".") + 1) : fieldName;
- }
-
- if(key.equalsIgnoreCase(clientFieldName)){
- // build where clause depending upon given parameters
- if(searchField.getDataType() == SearchField.DATA_TYPE.STRING) {
- // build where clause for String datatypes
- SingularAttribute attr = trxLogEntity.getSingularAttribute(fieldName);
- if(attr != null){
- Predicate stringPredicate = criteriaBuilder.equal(root.get(attr), paramValue);
- predicate = criteriaBuilder.and(predicate, stringPredicate);
- }
- } else if (searchField.getDataType() == SearchField.DATA_TYPE.INT_LIST ||
- isListValue && searchField.getDataType() == SearchField.DATA_TYPE.INTEGER) {
- // build where clause for integer lists or integers datatypes
- 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;
- }
- for(Number value : intValueList){
- SingularAttribute attr = trxLogEntity.getSingularAttribute(fieldName);
- if(attr != null){
- Predicate intPredicate = criteriaBuilder.equal(root.get(attr), value);
- predicate = criteriaBuilder.and(predicate, intPredicate);
- }
- }
- } else if (searchField.getDataType() == SearchField.DATA_TYPE.DATE){
- // build where clause for date datatypes
- Date fieldValue = (Date) paramList.get(searchField
- .getClientFieldName());
- SingularAttribute attr = trxLogEntity.getSingularAttribute(fieldName);
- if (fieldValue != null) {
- if (searchField.getCustomCondition() == null) {
- Predicate datePredicate = criteriaBuilder.equal(root.get(attr), fieldValue);
- if (searchField.getSearchType().equals(SearchField.SEARCH_TYPE.LESS_THAN)) {
- datePredicate = criteriaBuilder.lessThan(root.get(attr), fieldValue);
- } else if (searchField.getSearchType().equals(SearchField.SEARCH_TYPE.LESS_EQUAL_THAN)) {
- datePredicate = criteriaBuilder.lessThanOrEqualTo(root.get(attr), fieldValue);
- } else if (searchField.getSearchType().equals(SearchField.SEARCH_TYPE.GREATER_THAN)) {
- datePredicate = criteriaBuilder.greaterThan(root.get(attr), fieldValue);
- } else if (searchField.getSearchType().equals(SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN)) {
- datePredicate = criteriaBuilder.greaterThanOrEqualTo(root.get(attr), fieldValue);
- } else {
- datePredicate = criteriaBuilder.equal(root.get(attr), fieldValue);
- }
- predicate = criteriaBuilder.and(predicate, datePredicate);
- }
- }
- }
- }
- }
- }
- return predicate;
- }
-
- private VXTrxLog mapCustomViewToViewObj(VXXTrxLog vXXTrxLog){
- VXTrxLog vXTrxLog = new VXTrxLog();
- vXTrxLog.setId(vXXTrxLog.getId());
- vXTrxLog.setAction(vXXTrxLog.getAction());
- vXTrxLog.setAttributeName(vXXTrxLog.getAttributeName());
- vXTrxLog.setCreateDate(vXXTrxLog.getCreateTime());
- vXTrxLog.setNewValue(vXXTrxLog.getNewValue());
- vXTrxLog.setPreviousValue(vXXTrxLog.getPreviousValue());
- vXTrxLog.setSessionId(vXXTrxLog.getSessionId());
- if(vXXTrxLog.getUpdatedByUserId()==null || vXXTrxLog.getUpdatedByUserId()==0){
- vXTrxLog.setUpdatedBy(null);
- }else{
- vXTrxLog.setUpdatedBy(String.valueOf(vXXTrxLog.getUpdatedByUserId()));
- }
- //We will have to get this from XXUser
- //vXTrxLog.setOwner(vXXTrxLog.getAddedByUserName());
- vXTrxLog.setParentObjectClassType(vXXTrxLog.getParentObjectClassType());
- vXTrxLog.setParentObjectName(vXXTrxLog.getParentObjectName());
- vXTrxLog.setObjectClassType(vXXTrxLog.getObjectClassType());
- vXTrxLog.setObjectId(vXXTrxLog.getObjectId());
- vXTrxLog.setObjectName(vXXTrxLog.getObjectName());
- vXTrxLog.setTransactionId(vXXTrxLog.getTransactionId());
- return vXTrxLog;
- }
-
- @Override
- protected XXTrxLog mapViewToEntityBean(VXTrxLog vObj, XXTrxLog mObj, int OPERATION_CONTEXT) {
- super.mapViewToEntityBean(vObj, mObj, OPERATION_CONTEXT);
- if(vObj!=null && mObj!=null){
- XXPortalUser xXPortalUser=null;
- if(mObj.getAddedByUserId()==null || mObj.getAddedByUserId()==0){
- if(!stringUtil.isEmpty(vObj.getOwner())){
- xXPortalUser=xADaoManager.getXXPortalUser().findByLoginId(vObj.getOwner());
- if(xXPortalUser!=null){
- mObj.setAddedByUserId(xXPortalUser.getId());
- }
- }
- }
- if(mObj.getUpdatedByUserId()==null || mObj.getUpdatedByUserId()==0){
- if(!stringUtil.isEmpty(vObj.getUpdatedBy())){
- xXPortalUser= xADaoManager.getXXPortalUser().findByLoginId(vObj.getUpdatedBy());
- if(xXPortalUser!=null){
- mObj.setUpdatedByUserId(xXPortalUser.getId());
- }
- }
- }
- }
- return mObj;
- }
-
- @Override
- protected VXTrxLog mapEntityToViewBean(VXTrxLog vObj, XXTrxLog mObj) {
- super.mapEntityToViewBean(vObj, mObj);
- if(mObj!=null && vObj!=null){
- XXPortalUser xXPortalUser=null;
- if(stringUtil.isEmpty(vObj.getOwner())){
- xXPortalUser= xADaoManager.getXXPortalUser().getById(mObj.getAddedByUserId());
- if(xXPortalUser!=null){
- vObj.setOwner(xXPortalUser.getLoginId());
- }
- }
- if(stringUtil.isEmpty(vObj.getUpdatedBy())){
- xXPortalUser= xADaoManager.getXXPortalUser().getById(mObj.getUpdatedByUserId());
- if(xXPortalUser!=null){
- vObj.setUpdatedBy(xXPortalUser.getLoginId());
- }
- }
- }
- return vObj;
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XTrxLogServiceBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XTrxLogServiceBase.java b/security-admin/src/main/java/com/xasecure/service/XTrxLogServiceBase.java
deleted file mode 100644
index 5fdf21f..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XTrxLogServiceBase.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-/**
- *
- */
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-import com.xasecure.view.*;
-import com.xasecure.service.*;
-
-public abstract class XTrxLogServiceBase<T extends XXTrxLog, V extends VXTrxLog>
- extends AbstractBaseResourceService<T, V> {
- public static final String NAME = "XTrxLog";
-
- public XTrxLogServiceBase() {
-
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected XXTrxLog mapViewToEntityBean(VXTrxLog vObj, XXTrxLog mObj, int OPERATION_CONTEXT) {
- mObj.setObjectClassType( vObj.getObjectClassType());
- mObj.setObjectId( vObj.getObjectId());
- mObj.setParentObjectId( vObj.getParentObjectId());
- mObj.setParentObjectClassType( vObj.getParentObjectClassType());
- mObj.setParentObjectName( vObj.getParentObjectName());
- mObj.setObjectName( vObj.getObjectName());
- mObj.setAttributeName( vObj.getAttributeName());
- mObj.setPreviousValue( vObj.getPreviousValue());
- mObj.setNewValue( vObj.getNewValue());
- mObj.setTransactionId( vObj.getTransactionId());
- mObj.setAction( vObj.getAction());
- mObj.setSessionId( vObj.getSessionId());
- mObj.setRequestId( vObj.getRequestId());
- mObj.setSessionType( vObj.getSessionType());
- return mObj;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected VXTrxLog mapEntityToViewBean(VXTrxLog vObj, XXTrxLog mObj) {
- vObj.setObjectClassType( mObj.getObjectClassType());
- vObj.setObjectId( mObj.getObjectId());
- vObj.setParentObjectId( mObj.getParentObjectId());
- vObj.setParentObjectClassType( mObj.getParentObjectClassType());
- vObj.setParentObjectName( mObj.getParentObjectName());
- vObj.setObjectName( mObj.getObjectName());
- vObj.setAttributeName( mObj.getAttributeName());
- vObj.setPreviousValue( mObj.getPreviousValue());
- vObj.setNewValue( mObj.getNewValue());
- vObj.setTransactionId( mObj.getTransactionId());
- vObj.setAction( mObj.getAction());
- vObj.setSessionId( mObj.getSessionId());
- vObj.setRequestId( mObj.getRequestId());
- vObj.setSessionType( mObj.getSessionType());
- return vObj;
- }
-
- /**
- * @param searchCriteria
- * @return
- */
- public VXTrxLogList searchXTrxLogs(SearchCriteria searchCriteria) {
- VXTrxLogList returnList = new VXTrxLogList();
- List<VXTrxLog> xTrxLogList = new ArrayList<VXTrxLog>();
-
- @SuppressWarnings("unchecked")
- List<XXTrxLog> resultList = (List<XXTrxLog>)searchResources(searchCriteria,
- searchFields, sortFields, returnList);
-
- // Iterate over the result list and create the return list
- for (XXTrxLog gjXTrxLog : resultList) {
- @SuppressWarnings("unchecked")
- VXTrxLog vXTrxLog = populateViewBean((T)gjXTrxLog);
- xTrxLogList.add(vXTrxLog);
- }
-
- returnList.setVXTrxLogs(xTrxLogList);
- return returnList;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XUserService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XUserService.java b/security-admin/src/main/java/com/xasecure/service/XUserService.java
deleted file mode 100644
index af44969..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XUserService.java
+++ /dev/null
@@ -1,380 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Set;
-
-import com.xasecure.common.XACommonEnums;
-import com.xasecure.common.MessageEnums;
-import com.xasecure.common.PropertiesUtil;
-import com.xasecure.common.SearchField;
-import com.xasecure.common.SortField;
-import com.xasecure.common.StringUtil;
-import com.xasecure.common.XAConstants;
-import com.xasecure.entity.XXPortalUser;
-import com.xasecure.entity.XXPortalUserRole;
-import com.xasecure.view.VXPortalUser;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Service;
-
-import com.xasecure.biz.XABizUtil;
-import com.xasecure.common.AppConstants;
-import com.xasecure.common.view.VTrxLogAttr;
-import com.xasecure.db.XADaoManager;
-import com.xasecure.entity.*;
-import com.xasecure.util.XAEnumUtil;
-import com.xasecure.view.*;
-
-@Service
-@Scope("singleton")
-public class XUserService extends XUserServiceBase<XXUser, VXUser> {
-
- public static Long createdByUserId = 1L;
-
- @Autowired
- XADaoManager daoManager;
-
- @Autowired
- XPermMapService xPermMapService;
-
- @Autowired
- StringUtil stringUtil;
-
- @Autowired
- XAEnumUtil xaEnumUtil;
-
- @Autowired
- XABizUtil xaBizUtil;
-
- String hiddenPasswordString;
-
- static HashMap<String, VTrxLogAttr> trxLogAttrs = new HashMap<String, VTrxLogAttr>();
- static {
- trxLogAttrs.put("name", new VTrxLogAttr("name", "Login ID", false));
- trxLogAttrs.put("firstName", new VTrxLogAttr("firstName", "First Name",
- false));
- trxLogAttrs.put("lastName", new VTrxLogAttr("lastName", "Last Name",
- false));
- trxLogAttrs.put("emailAddress", new VTrxLogAttr("emailAddress",
- "Email Address", false));
- trxLogAttrs.put("password", new VTrxLogAttr("password", "Password",
- false));
- trxLogAttrs.put("userRoleList", new VTrxLogAttr("userRoleList", "User Role",
- false));
-
- }
-
- public XUserService() {
- searchFields.add(new SearchField("name", "obj.name",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
-
- searchFields.add(new SearchField("emailAddress", "xXPortalUser.emailAddress",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL,
- "XXPortalUser xXPortalUser", "xXPortalUser.loginId = obj.name "));
-
- searchFields.add(new SearchField("userName", "obj.name",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL));
-
- searchFields.add(new SearchField("userSource", "xXPortalUser.userSource",
- SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL,
- "XXPortalUser xXPortalUser", "xXPortalUser.loginId = obj.name "));
-
- searchFields.add(new SearchField("userRoleList", "xXPortalUserRole.userRole",
- SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL,
- "XXPortalUser xXPortalUser, XXPortalUserRole xXPortalUserRole",
- "xXPortalUser.id=xXPortalUserRole.userId and xXPortalUser.loginId = obj.name "));
-
-
- createdByUserId = new Long(PropertiesUtil.getIntProperty(
- "xa.xuser.createdByUserId", 1));
-
- hiddenPasswordString = PropertiesUtil.getProperty("xa.password.hidden",
- "*****");
-
- sortFields.add(new SortField("name", "obj.name",true,SortField.SORT_ORDER.ASC));
-
- }
-
- @Override
- protected void validateForCreate(VXUser vObj) {
-
- XXUser xUser = daoManager.getXXUser().findByUserName(vObj.getName());
- if (xUser != null) {
- throw restErrorUtil.createRESTException("XUser already exists",
- MessageEnums.ERROR_DUPLICATE_OBJECT);
- }
-
- }
-
- @Override
- protected void validateForUpdate(VXUser vObj, XXUser mObj) {
- String vObjName = vObj.getName();
- String mObjName = mObj.getName();
- if (vObjName != null && mObjName != null) {
- if (!vObjName.trim().equals(mObjName.trim())) {
- validateForCreate(vObj);
- }
- }
- }
-
- public VXUser getXUserByUserName(String userName) {
- XXUser xxUser = daoManager.getXXUser().findByUserName(userName);
- if (xxUser == null) {
- throw restErrorUtil.createRESTException(userName + " is Not Found",
- MessageEnums.DATA_NOT_FOUND);
- }
- return super.populateViewBean(xxUser);
-
- }
-
- public VXUser createXUserWithOutLogin(VXUser vxUser) {
- XXUser xxUser = daoManager.getXXUser().findByUserName(vxUser.getName());
- boolean userExists = true;
- if (xxUser == null) {
- xxUser = new XXUser();
- userExists = false;
- }
-
- xxUser = mapViewToEntityBean(vxUser, xxUser, 0);
- XXPortalUser xXPortalUser = daoManager.getXXPortalUser().getById(createdByUserId);
- if (xXPortalUser != null) {
- xxUser.setAddedByUserId(createdByUserId);
- xxUser.setUpdatedByUserId(createdByUserId);
- }
-
- if (userExists) {
- xxUser = getDao().update(xxUser);
- } else {
- xxUser = getDao().create(xxUser);
- }
- vxUser = postCreate(xxUser);
- return vxUser;
- }
-
- public VXUser readResourceWithOutLogin(Long id) {
- XXUser resource = getDao().getById(id);
- if (resource == null) {
- // Returns code 400 with DATA_NOT_FOUND as the error message
- throw restErrorUtil.createRESTException(getResourceName()
- + " not found", MessageEnums.DATA_NOT_FOUND, id, null,
- "preRead: " + id + " not found.");
- }
-
- VXUser vxUser = populateViewBean(resource);
- return vxUser;
- }
-
- @Override
- protected VXUser mapEntityToViewBean(VXUser vObj, XXUser mObj) {
- super.mapEntityToViewBean(vObj, mObj);
- String userName = vObj.getName();
- populateUserAttributes(userName, vObj);
- return vObj;
- }
-
- @Override
- public VXUser populateViewBean(XXUser xUser) {
- VXUser vObj = super.populateViewBean(xUser);
- String userName = vObj.getName();
- populateUserAttributes(userName, vObj);
- populateGroupList(xUser.getId(), vObj);
- return vObj;
- }
-
- private void populateGroupList(Long xUserId, VXUser vObj) {
- List<XXGroupUser> xGroupUserList = daoManager.getXXGroupUser()
- .findByUserId(xUserId);
- Set<Long> groupIdList = new LinkedHashSet<Long>();
- Set<String> groupNameList = new LinkedHashSet<String>();
- if (xGroupUserList != null) {
- for (XXGroupUser xGroupUser : xGroupUserList) {
- groupIdList.add(xGroupUser.getParentGroupId());
- groupNameList.add(xGroupUser.getName());
- }
- }
- List<Long> groups = new ArrayList<Long>(groupIdList);
- List<String> groupNames = new ArrayList<String>(groupNameList);
- vObj.setGroupIdList(groups);
- vObj.setGroupNameList(groupNames);
- }
-
- private void populateUserAttributes(String userName, VXUser vObj) {
- if (userName != null && !userName.isEmpty()) {
- List<String> userRoleList =new ArrayList<String>();
- XXPortalUser xXPortalUser = daoManager.getXXPortalUser().findByLoginId(userName);
- if (xXPortalUser != null) {
- vObj.setFirstName(xXPortalUser.getFirstName());
- vObj.setLastName(xXPortalUser.getLastName());
- vObj.setPassword(PropertiesUtil
- .getProperty("xa.password.hidden"));
- String emailAddress = xXPortalUser.getEmailAddress();
- if (emailAddress != null
- && stringUtil.validateEmail(emailAddress)) {
- vObj.setEmailAddress(xXPortalUser.getEmailAddress());
- }
- vObj.setStatus(xXPortalUser.getStatus());
- vObj.setUserSource(xXPortalUser.getUserSource());
- List<XXPortalUserRole> gjUserRoleList = daoMgr.getXXPortalUserRole().findByParentId(
- xXPortalUser.getId());
-
- for (XXPortalUserRole gjUserRole : gjUserRoleList) {
- userRoleList.add(gjUserRole.getUserRole());
- }
- }
- if(userRoleList==null || userRoleList.size()==0){
- userRoleList.add(XAConstants.ROLE_USER);
- }
- vObj.setUserRoleList(userRoleList);
- }
- }
-
- public List<XXTrxLog> getTransactionLog(VXUser vResource, String action) {
- return getTransactionLog(vResource, null, action);
- }
-
- public List<XXTrxLog> getTransactionLog(VXUser vObj, VXPortalUser mObj,
- String action) {
- if (vObj == null
- && (action == null || !action.equalsIgnoreCase("update"))) {
- return null;
- }
-
- List<XXTrxLog> trxLogList = new ArrayList<XXTrxLog>();
- try {
- Field nameField = vObj.getClass().getDeclaredField("name");
- nameField.setAccessible(true);
- String objectName = "" + nameField.get(vObj);
- Field[] fields = vObj.getClass().getDeclaredFields();
-
- for (Field field : fields) {
- field.setAccessible(true);
- String fieldName = field.getName();
- if (!trxLogAttrs.containsKey(fieldName)) {
- continue;
- }
-
- VTrxLogAttr vTrxLogAttr = trxLogAttrs.get(fieldName);
-
- XXTrxLog xTrxLog = new XXTrxLog();
- xTrxLog.setAttributeName(vTrxLogAttr
- .getAttribUserFriendlyName());
-
- String value = null;
- if (vTrxLogAttr.isEnum()) {
- String enumName = XXUser.getEnumName(fieldName);
- int enumValue = field.get(vObj) == null ? 0 : Integer
- .parseInt("" + field.get(vObj));
- value = xaEnumUtil.getLabel(enumName, enumValue);
- } else {
- value = "" + field.get(vObj);
- if ((value == null || value.equalsIgnoreCase("null"))
- && !action.equalsIgnoreCase("update")) {
- continue;
- }
- }
-
- if (fieldName.equalsIgnoreCase("password")) {
- if (value.equalsIgnoreCase(hiddenPasswordString)) {
- continue;
- }
- }
-
- if (action.equalsIgnoreCase("create")) {
- if (stringUtil.isEmpty(value)
- || (fieldName.equalsIgnoreCase("emailAddress") && !stringUtil
- .validateEmail(value))) {
- continue;
- }
- xTrxLog.setNewValue(value);
- } else if (action.equalsIgnoreCase("delete")) {
- if (fieldName.equalsIgnoreCase("emailAddress")
- && !stringUtil.validateEmail(value)) {
- continue;
- }
- xTrxLog.setPreviousValue(value);
- } else if (action.equalsIgnoreCase("update")) {
- String oldValue = null;
- Field[] mFields = mObj.getClass().getDeclaredFields();
- for (Field mField : mFields) {
- mField.setAccessible(true);
- String mFieldName = mField.getName();
- if (mFieldName.equalsIgnoreCase("loginId")) {
- mFieldName = "name";
- }
- if (fieldName.equalsIgnoreCase(mFieldName)) {
- oldValue = mField.get(mObj) + "";
- break;
- }
- }
- if (oldValue.equalsIgnoreCase(value)) {
- continue;
- }
- if (fieldName.equalsIgnoreCase("emailAddress")) {
- if (stringUtil.validateEmail(oldValue)) {
- xTrxLog.setPreviousValue(oldValue);
- }
- if (stringUtil.validateEmail(value)) {
- xTrxLog.setNewValue(value);
- }
- } else {
- xTrxLog.setPreviousValue(oldValue);
- xTrxLog.setNewValue(value);
- }
- }
-
- xTrxLog.setAction(action);
- xTrxLog.setObjectClassType(AppConstants.CLASS_TYPE_XA_USER);
- xTrxLog.setObjectId(vObj.getId());
- xTrxLog.setObjectName(objectName);
-
- trxLogList.add(xTrxLog);
- }
-
- if (trxLogList.size() == 0) {
- XXTrxLog xTrxLog = new XXTrxLog();
- xTrxLog.setAction(action);
- xTrxLog.setObjectClassType(AppConstants.CLASS_TYPE_XA_USER);
- xTrxLog.setObjectId(vObj.getId());
- xTrxLog.setObjectName(objectName);
- trxLogList.add(xTrxLog);
- }
-
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (NoSuchFieldException e) {
- e.printStackTrace();
- } catch (SecurityException e) {
- e.printStackTrace();
- }
-
- return trxLogList;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/XUserServiceBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XUserServiceBase.java b/security-admin/src/main/java/com/xasecure/service/XUserServiceBase.java
deleted file mode 100644
index bf30a49..0000000
--- a/security-admin/src/main/java/com/xasecure/service/XUserServiceBase.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-/**
- *
- */
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-import com.xasecure.view.*;
-import com.xasecure.service.*;
-
-public abstract class XUserServiceBase<T extends XXUser, V extends VXUser>
- extends AbstractBaseResourceService<T, V> {
- public static final String NAME = "XUser";
-
- public XUserServiceBase() {
-
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected XXUser mapViewToEntityBean(VXUser vObj, XXUser mObj, int OPERATION_CONTEXT) {
- mObj.setName( vObj.getName());
- mObj.setDescription( vObj.getDescription());
- mObj.setCredStoreId( vObj.getCredStoreId());
- return mObj;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected VXUser mapEntityToViewBean(VXUser vObj, XXUser mObj) {
- vObj.setName( mObj.getName());
- vObj.setDescription( mObj.getDescription());
- vObj.setCredStoreId( mObj.getCredStoreId());
- return vObj;
- }
-
- /**
- * @param searchCriteria
- * @return
- */
- public VXUserList searchXUsers(SearchCriteria searchCriteria) {
- VXUserList returnList = new VXUserList();
- List<VXUser> xUserList = new ArrayList<VXUser>();
-
- @SuppressWarnings("unchecked")
- List<XXUser> resultList = (List<XXUser>)searchResources(searchCriteria,
- searchFields, sortFields, returnList);
-
- // Iterate over the result list and create the return list
- for (XXUser gjXUser : resultList) {
- @SuppressWarnings("unchecked")
- VXUser vXUser = populateViewBean((T)gjXUser);
- xUserList.add(vXUser);
- }
-
- returnList.setVXUsers(xUserList);
- return returnList;
- }
-
-}
[40/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/hbase/HBaseAuthDB.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/hbase/HBaseAuthDB.java b/agents-impl/src/main/java/org/apache/ranger/pdp/hbase/HBaseAuthDB.java
new file mode 100644
index 0000000..9f9affd
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/hbase/HBaseAuthDB.java
@@ -0,0 +1,488 @@
+/*
+ * 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.pdp.hbase;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.hbase.security.User;
+import org.apache.hadoop.hbase.security.access.Permission.Action;
+import org.apache.hadoop.hbase.security.access.UserPermission;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.util.StringUtils;
+import org.apache.ranger.authorization.hbase.HBaseAccessController;
+import org.apache.ranger.pdp.constants.RangerConstants;
+
+public class HBaseAuthDB implements HBaseAccessController {
+
+ private static final long MAX_CACHE_AUDIT_ENTRIES = 1000L ;
+ private static final long MAX_CACHE_ENCRYPT_ENTRIES = 1000L ;
+
+ private static final Log LOG = LogFactory.getLog(HBaseAuthDB.class) ;
+
+ private ArrayList<HBaseAuthRules> ruleList = null;
+ private ArrayList<HBaseAuthRules> globalList = null;
+ private ArrayList<HBaseAuthRules> tableList = null;
+
+ private ArrayList<String> auditList = null ;
+ private HashMap<byte[],Boolean> cachedAuditTable = new HashMap<byte[],Boolean>() ;
+
+ private ArrayList<String> encryptList = null ;
+
+ private HashSet<String> encryptTableList = null ;
+ private HashMap<byte[],Boolean> cachedEncryptedTable = new HashMap<byte[],Boolean>() ;
+
+
+ public HBaseAuthDB(ArrayList<HBaseAuthRules> ruleList, ArrayList<String> auditList, ArrayList<String> encryptList) {
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("+Creating HBaseAuthDB is creating with ruleList [" + (ruleList == null ? 0 : ruleList.size()) + "]" );
+ }
+
+ this.auditList = auditList;
+ this.encryptList = encryptList;
+
+
+ this.ruleList = new ArrayList<HBaseAuthRules>() ;
+ this.globalList = new ArrayList<HBaseAuthRules>() ;
+ this.tableList = new ArrayList<HBaseAuthRules>() ;
+
+ for(HBaseAuthRules rule : ruleList ) {
+ if (rule.isGlobalRule()) {
+ this.globalList.add(rule) ;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("RULE:[" + rule + "] is being added as GLOBAL Policy");
+ }
+ }
+ else if (rule.isTableRule()) {
+ this.tableList.add(rule) ;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("RULE:[" + rule + "] is being added as Table Policy");
+ }
+ }
+ else {
+ this.ruleList.add(rule) ;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("RULE:[" + rule + "] is being added as non-global, non-table Policy");
+ }
+ }
+ }
+
+ this.encryptTableList = new HashSet<String>() ;
+
+ if (encryptList != null && encryptList.size() > 0) {
+ for(String encryptKey : encryptList) {
+ String[] objKeys = encryptKey.split("/") ;
+ String tableName = objKeys[0] ;
+ if (! encryptTableList.contains(tableName)) {
+ encryptTableList.add(tableName) ;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("EncryptionList:[" + tableName + "] is being added encrypted table.");
+ }
+ }
+ }
+ }
+
+
+ }
+
+
+ public boolean isAccessAllowed(User user, Action accessAction) {
+
+
+ String access = accessAction.toString().toLowerCase() ;
+
+ if (user == null) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("rulecheck(GLOBAL," + access + ") => [FALSE] as user passed for check was null.");
+ }
+ return false ;
+ }
+
+
+ String username = user.getShortName() ;
+
+ String[] groups = user.getGroupNames() ;
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Init of Global access Verification - [" + access + "] for user [" + username + "], groups: [" + Arrays.toString(groups) + "]");
+ }
+
+ for (HBaseAuthRules rule : globalList) {
+
+ if (rule.getAccessType().equals(access)) {
+
+ String authorizedUser = rule.getUser() ;
+ String authorizedGroup = rule.getGroup();
+
+ if (authorizedGroup != null) {
+ if (RangerConstants.PUBLIC_ACCESS_ROLE.equals(authorizedGroup)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("rulecheck(GLOBAL," + access + "," + username + "," + StringUtils.arrayToString(groups) + ") => [TRUE] as matched for rule: " + rule);
+ }
+ return true ;
+ }
+
+ for (String group : groups) {
+ if (group.equals(authorizedGroup)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("rulecheck(GLOBAL," + access + "," + username + "," + StringUtils.arrayToString(groups) + ") => [TRUE] as matched for rule: " + rule);
+ }
+ return true;
+ }
+ }
+ }
+
+ if (authorizedUser != null) {
+ if (username.equals(authorizedUser)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("rulecheck(GLOBAL," + access + "," + username + "," + StringUtils.arrayToString(groups) + ") => [TRUE] as matched for rule: " + rule);
+ }
+ return true;
+ }
+ }
+ }
+ }
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("rulecheck(GLOBAL," + access + "," + username + "," + StringUtils.arrayToString(groups) + ") => [FALSE] as it did not match any rules.");
+ }
+
+ return false;
+ }
+
+ public boolean isAccessAllowed(User user, byte[] tableName, Action accessAction) {
+
+
+ if ( isAccessAllowed(user,accessAction)) { // Check Global Action
+ return true ;
+ }
+
+ String tableNameStr = Bytes.toString(tableName) ;
+
+ String access = accessAction.toString().toLowerCase() ;
+
+ if (user == null) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("rulecheck(" + tableNameStr + "," + access + ") => [FALSE] as user passed for check was null.");
+ }
+ return false ;
+ }
+
+ String username = user.getShortName() ;
+
+ String[] groups = user.getGroupNames() ;
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Init of Table access Verification - [" + access + "] for user [" + username + "], groups: [" + Arrays.toString(groups) + "], tableName: [" + tableNameStr + "]");
+ }
+
+ for (HBaseAuthRules rule : tableList) {
+
+ if (rule.isTableNameMatched(tableNameStr)) {
+ if (rule.getAccessType().equals(access)) {
+
+ String authorizedUser = rule.getUser() ;
+
+ String authorizedGroup = rule.getGroup();
+
+ if (authorizedGroup != null) {
+ if (RangerConstants.PUBLIC_ACCESS_ROLE.equals(authorizedGroup)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("rulecheck(" + tableNameStr + "," + access + "," + username + "," + StringUtils.arrayToString(groups) + ") => [TRUE] as matched for rule: " + rule);
+ }
+ return true ;
+ }
+
+ for (String group : groups) {
+ if (group.equals(authorizedGroup)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("rulecheck(" + tableNameStr + "," + access + "," + username + "," + StringUtils.arrayToString(groups) + ") => [TRUE] as matched for rule: " + rule);
+ }
+ return true;
+ }
+ }
+ }
+ if (authorizedUser != null && username.equals(authorizedUser)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("rulecheck(" + tableNameStr + "," + access + "," + username + "," + StringUtils.arrayToString(groups) + ") => [TRUE] as matched for rule: " + rule);
+ }
+ return true;
+ }
+ }
+ }
+ }
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("rulecheck(" + tableNameStr + "," + access + "," + username + "," + StringUtils.arrayToString(groups) + ") => [FALSE] as it did not match any rules.");
+ }
+
+ return false;
+ }
+
+
+
+
+
+
+ public boolean isAccessAllowed(User user, byte[] tableName, byte[] columnFamily, byte[] qualifier, Action accessAction) {
+
+ String FQColName = getFullyQualifiedColumnName(tableName, columnFamily, qualifier) ;
+
+ String access = accessAction.toString().toLowerCase() ;
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("isAccessAllowed on HBaseAuthDB: for FQColName [" + FQColName + "]");
+ }
+
+
+ if (user == null) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("rulecheck(" + FQColName + "," + access + ") => [FALSE] as as user passed for check was null.");
+ }
+ return false ;
+ }
+
+
+ if (isAccessAllowed(user, accessAction)) { // Check Global Action
+ return true ;
+ }
+
+ if (isAccessAllowed(user,tableName, accessAction)) { // Check Table Action
+ return true;
+ }
+
+
+ String username = user.getShortName() ;
+
+ String[] groups = user.getGroupNames() ;
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Init of Table access Verification - [" + access + "] for user [" + username + "], groups: [" + Arrays.toString(groups) + "], FQColumnFamily: [" + FQColName + "]");
+ }
+
+ for (HBaseAuthRules rule : ruleList) {
+
+ if (rule.isMatched(FQColName)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Rule [" + rule + "] matched [" + FQColName + "]");
+ }
+ if (rule.getAccessType().equals(access)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Access [" + rule.getAccessType() + "] matched [" + access + "]");
+ }
+ String authorizedUser = rule.getUser() ;
+
+ String authorizedGroup = rule.getGroup();
+
+ if (authorizedGroup != null) {
+ if (RangerConstants.PUBLIC_ACCESS_ROLE.equals(authorizedGroup)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("rulecheck(" + FQColName + "," + access + "," + username + "," + StringUtils.arrayToString(groups) + ") => [TRUE] as matched for rule: " + rule);
+ }
+ return true ;
+ }
+ for (String group : groups) {
+ if (group.equals(authorizedGroup)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("rulecheck(" + FQColName + "," + access + "," + username + "," + StringUtils.arrayToString(groups) + ") => [TRUE] as matched for rule: " + rule);
+ }
+ return true;
+ }
+ }
+ }
+
+ if (authorizedUser != null) {
+ if (username.equals(authorizedUser)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("rulecheck(" + FQColName + "," + access + "," + username + "," + StringUtils.arrayToString(groups) + ") => [TRUE] as matched for rule: " + rule);
+ }
+ return true;
+ }
+ }
+ }
+ else {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Access [" + rule.getAccessType() + "] DID NOT match [" + access + "]");
+ }
+ }
+ }
+ else {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Rule [" + rule + "] not matched [" + FQColName + "]");
+ }
+ }
+ }
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("rulecheck(" + FQColName + "," + access + "," + username + "," + StringUtils.arrayToString(groups) + ") => [FALSE] as it did not match any rules.");
+ }
+
+ return false;
+
+ }
+
+ public boolean isEncrypted(byte[] tableName, byte[] columnFamily, byte[] qualifier) {
+ String colName = getFullyQualifiedColumnName(tableName, columnFamily, qualifier) ;
+ for(String encryptable : encryptList) {
+ if (FilenameUtils.wildcardMatch(colName,encryptable)) {
+ return true ;
+ }
+ }
+ return false;
+ }
+
+ public boolean isAudited(byte[] tableName) {
+ Boolean ret = cachedAuditTable.get(tableName) ;
+ if (ret == null) {
+ ret = isAuditedFromTableList(tableName) ;
+ synchronized(cachedAuditTable) {
+ if (cachedAuditTable.size() > MAX_CACHE_AUDIT_ENTRIES) {
+ cachedAuditTable.clear();
+ }
+ cachedAuditTable.put(tableName,ret) ;
+ }
+ }
+ return ret.booleanValue();
+ }
+
+ private boolean isAuditedFromTableList(byte[] tableName) {
+ boolean ret = false ;
+ String tableNameStr = Bytes.toString(tableName) ;
+ for(String auditable : auditList) {
+ if (FilenameUtils.wildcardMatch(tableNameStr,auditable)) {
+ ret = true ;
+ break ;
+ }
+ }
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("isAudited(" + tableNameStr + "):" + ret) ;
+ }
+
+ return ret;
+ }
+
+
+ public boolean isTableHasEncryptedColumn(byte[] tableName) {
+ Boolean ret = cachedEncryptedTable.get(tableName) ;
+ if (ret == null) {
+ ret = isTableHasEncryptedColumnFromTableList(tableName) ;
+ synchronized(cachedEncryptedTable) {
+ if (cachedEncryptedTable.size() > MAX_CACHE_ENCRYPT_ENTRIES) {
+ cachedEncryptedTable.clear();
+ }
+ cachedEncryptedTable.put(tableName, ret) ;
+ }
+ }
+ return ret.booleanValue() ;
+ }
+
+
+ private boolean isTableHasEncryptedColumnFromTableList(byte[] tableName)
+ {
+ boolean ret = false ;
+
+ String tableNameStr = Bytes.toString(tableName) ;
+
+ for(String encryptTable : encryptTableList) {
+ ret = FilenameUtils.wildcardMatch(tableNameStr, encryptTable) ;
+ if (ret) {
+ break ;
+ }
+ }
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("isTableHasEncryptedColumn(" + tableNameStr + "):" + ret);
+ }
+
+ return ret ;
+ }
+
+
+
+ public static String getFullyQualifiedColumnName(byte[] tableName, byte[] columnFamily, byte[] qualifier) {
+ StringBuilder sb = new StringBuilder() ;
+
+ sb.append(((tableName != null && tableName.length > 0) ? Bytes.toString(tableName) : "*"))
+ .append("/")
+ .append(((columnFamily != null && columnFamily.length > 0) ? Bytes.toString(columnFamily) : "*"))
+ .append("/")
+ .append(((qualifier != null && qualifier.length > 0) ? Bytes.toString(qualifier) : "*")) ;
+
+ return sb.toString() ;
+ }
+
+ public List<UserPermission> getUserPermissions(User user) {
+ List<UserPermission> ret = new ArrayList<UserPermission>() ;
+
+ if (user != null) {
+ ArrayList<ArrayList<HBaseAuthRules>> allList = new ArrayList<ArrayList<HBaseAuthRules>>();
+ allList.add(globalList) ;
+ allList.add(tableList) ;
+ allList.add(ruleList) ;
+ for(ArrayList<HBaseAuthRules> rList : allList) {
+ for(HBaseAuthRules rule : rList) {
+ UserPermission perm = rule.getUserPermission(user) ;
+ if (perm != null) {
+ ret.add(perm) ;
+ }
+ }
+ }
+ }
+
+ return ret ;
+ }
+
+ public List<UserPermission> getUserPermissions(User user, byte[] tableName) {
+
+ String tableNameStr = Bytes.toString(tableName) ;
+
+ List<UserPermission> ret = new ArrayList<UserPermission>() ;
+
+ if (user != null) {
+ ArrayList<ArrayList<HBaseAuthRules>> allList = new ArrayList<ArrayList<HBaseAuthRules>>();
+ allList.add(globalList) ;
+ allList.add(tableList) ;
+ allList.add(ruleList) ;
+ for(ArrayList<HBaseAuthRules> rList : allList) {
+ for(HBaseAuthRules rule : rList) {
+ if (rule.isTableNameMatched(tableNameStr)) {
+ UserPermission perm = rule.getUserPermission(user) ;
+ if (perm != null) {
+ ret.add(perm) ;
+ }
+ }
+ }
+ }
+ }
+
+ return ret ;
+ }
+
+
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/hbase/HBaseAuthRules.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/hbase/HBaseAuthRules.java b/agents-impl/src/main/java/org/apache/ranger/pdp/hbase/HBaseAuthRules.java
new file mode 100644
index 0000000..ae3980d
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/hbase/HBaseAuthRules.java
@@ -0,0 +1,134 @@
+/*
+ * 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.pdp.hbase;
+
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.hbase.TableName;
+import org.apache.hadoop.hbase.security.User;
+import org.apache.hadoop.hbase.security.access.Permission;
+import org.apache.hadoop.hbase.security.access.UserPermission;
+import org.apache.ranger.pdp.constants.RangerConstants;
+
+public class HBaseAuthRules {
+ private String tableName ;
+ private String columnGroupName;
+ private String columnName ;
+ private String accessType ;
+ private String group ;
+ private String user ;
+ private String fullyQualifiedColumnName ;
+
+ private static final Log LOG = LogFactory.getLog(HBaseAuthRules.class) ;
+
+ public HBaseAuthRules(String tableName, String columnGroupName, String columnName, String accessType, String user, String group) {
+ this.tableName = tableName;
+ this.columnGroupName = columnGroupName;
+ this.columnName = columnName;
+ if (accessType != null) {
+ this.accessType = accessType.toLowerCase() ;
+ }
+ this.user = user ;
+ this.group = group;
+ this.fullyQualifiedColumnName = tableName + "/" + columnGroupName + "/" + columnName ;
+ }
+
+ public String getTableName() {
+ return tableName;
+ }
+ public String getColumnGroupName() {
+ return columnGroupName;
+ }
+ public String getColumnName() {
+ return columnName;
+ }
+ public String getAccessType() {
+ return accessType;
+ }
+ public String getGroup() {
+ return group;
+ }
+
+ public String getUser() {
+ return user;
+ }
+
+ @Override
+ public String toString() {
+ return "table: " + tableName + ", columnGroup:" + columnGroupName + ", columnName: " + columnName + ", accessType: " + accessType + ", user:" + user + ", group: " + group ;
+ }
+
+ public boolean isMatched(String FQColName) {
+ return FQColName.equals(fullyQualifiedColumnName) || FilenameUtils.wildcardMatch(FQColName,fullyQualifiedColumnName) ;
+ }
+
+ public boolean isGlobalRule() {
+ return ("*".equals(tableName) && "*".equals(columnGroupName) && "*".equals(columnName)) ;
+ }
+
+ public boolean isTableRule() {
+ return ( ("*".equals(columnGroupName) && "*".equals(columnName)) || ("admin".equals(accessType) || "control".equals(accessType)) ) ;
+ }
+
+ public boolean isTableNameMatched(String tableNameStr) {
+ boolean ret = (tableNameStr == null) || (tableNameStr.equals(tableName)) || FilenameUtils.wildcardMatch(tableNameStr,tableName) ;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("TableMatched returns (" + tableNameStr + ", rule:" + tableName + ") returns: " + ret );
+ }
+ return ret ;
+ }
+
+ public UserPermission getUserPermission(User aUser) {
+
+ if (user == null) {
+ return null ;
+ }
+
+ Permission.Action action = null ;
+
+ try {
+ action = Permission.Action.valueOf(accessType.toUpperCase()) ;
+ } catch (Throwable e) {
+ return null ;
+ }
+
+ if (RangerConstants.PUBLIC_ACCESS_ROLE.equals(group)) {
+ return new UserPermission("public".getBytes(), TableName.valueOf ( tableName ) , columnGroupName.getBytes(), columnName.getBytes(), action) ;
+ }
+
+ if (user != null) {
+ if (aUser.getShortName().equals(user)) {
+ return new UserPermission(("user:(" + aUser.getShortName() + ")").getBytes(), TableName.valueOf( tableName ) , columnGroupName.getBytes(), columnName.getBytes(), action) ;
+ }
+ }
+
+ if (group != null) {
+ for (String ugroups : aUser.getGroupNames()) {
+ if (ugroups.equals(group)) {
+ return new UserPermission(("group:(" + ugroups + ")").getBytes(), TableName.valueOf( tableName ) , columnGroupName.getBytes(), columnName.getBytes(), action) ;
+ }
+ }
+ }
+
+ return null;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/hbase/RangerAuthorizer.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/hbase/RangerAuthorizer.java b/agents-impl/src/main/java/org/apache/ranger/pdp/hbase/RangerAuthorizer.java
new file mode 100644
index 0000000..f832cfd
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/hbase/RangerAuthorizer.java
@@ -0,0 +1,107 @@
+/*
+ * 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.pdp.hbase;
+
+import java.util.List;
+
+import org.apache.hadoop.hbase.security.User;
+import org.apache.hadoop.hbase.security.access.Permission.Action;
+import org.apache.hadoop.hbase.security.access.UserPermission;
+import org.apache.ranger.authorization.hbase.HBaseAccessController;
+
+public class RangerAuthorizer implements HBaseAccessController {
+
+ private HBaseAccessController authDB = URLBasedAuthDB.getInstance();
+
+ @Override
+ public boolean isAccessAllowed(User user, Action accessAction) {
+ if (authDB != null) {
+ return authDB.isAccessAllowed(user, accessAction);
+ } else {
+ return false;
+ }
+ }
+
+ @Override
+ public boolean isAccessAllowed(User user, byte[] tableName, Action accessAction) {
+ if (authDB != null) {
+ return authDB.isAccessAllowed(user, tableName, accessAction);
+ } else {
+ return false;
+ }
+ }
+
+
+ @Override
+ public boolean isAccessAllowed(User user, byte[] tableName, byte[] columnFamily, byte[] qualifier, Action accessAction) {
+ if (authDB != null) {
+ return authDB.isAccessAllowed(user, tableName, columnFamily, qualifier, accessAction);
+ } else {
+ return false;
+ }
+ }
+
+ @Override
+ public boolean isEncrypted(byte[] tableName, byte[] columnFamily, byte[] qualifier) {
+ if (authDB != null) {
+ return authDB.isEncrypted(tableName, columnFamily, qualifier);
+ } else {
+ return false;
+ }
+ }
+
+ @Override
+ public boolean isTableHasEncryptedColumn(byte[] tableName) {
+ if (authDB != null) {
+ return authDB.isTableHasEncryptedColumn(tableName);
+ } else {
+ return false;
+ }
+ }
+
+
+ @Override
+ public boolean isAudited(byte[] tableName) {
+ if (authDB != null) {
+ return authDB.isAudited(tableName);
+ } else {
+ return false;
+ }
+ }
+
+ @Override
+ public List<UserPermission> getUserPermissions(User aUser) {
+ if (authDB != null) {
+ return authDB.getUserPermissions(aUser) ;
+ } else {
+ return null;
+ }
+ }
+
+ @Override
+ public List<UserPermission> getUserPermissions(User aUser, byte[] aTableName) {
+ if (authDB != null) {
+ return authDB.getUserPermissions(aUser, aTableName) ;
+ } else {
+ return null;
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/hbase/URLBasedAuthDB.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/hbase/URLBasedAuthDB.java b/agents-impl/src/main/java/org/apache/ranger/pdp/hbase/URLBasedAuthDB.java
new file mode 100644
index 0000000..b0e543a
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/hbase/URLBasedAuthDB.java
@@ -0,0 +1,233 @@
+/*
+ * 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.pdp.hbase;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.hbase.security.User;
+import org.apache.hadoop.hbase.security.access.Permission.Action;
+import org.apache.hadoop.hbase.security.access.UserPermission;
+import org.apache.ranger.authorization.hadoop.config.RangerConfiguration;
+import org.apache.ranger.authorization.hbase.HBaseAccessController;
+import org.apache.ranger.pdp.config.PolicyChangeListener;
+import org.apache.ranger.pdp.config.PolicyRefresher;
+import org.apache.ranger.pdp.constants.RangerConstants;
+import org.apache.ranger.pdp.model.Policy;
+import org.apache.ranger.pdp.model.PolicyContainer;
+import org.apache.ranger.pdp.model.RolePermission;
+
+public class URLBasedAuthDB implements HBaseAccessController, PolicyChangeListener {
+
+ private static final Log LOG = LogFactory.getLog(URLBasedAuthDB.class);
+
+ private HBaseAuthDB authDB = null;
+
+ private static URLBasedAuthDB me = null ;
+
+ private PolicyRefresher refresher = null ;
+
+ public static URLBasedAuthDB getInstance() {
+ if (me == null) {
+ synchronized(URLBasedAuthDB.class) {
+ URLBasedAuthDB temp = me ;
+ if (temp == null) {
+ me = new URLBasedAuthDB() ;
+ me.init() ;
+ }
+ }
+ }
+ return me ;
+ }
+
+
+ private URLBasedAuthDB() {
+ String url = RangerConfiguration.getInstance().get(RangerConstants.RANGER_HBASE_POLICYMGR_URL_PROP);
+ long refreshInMilli = RangerConfiguration.getInstance().getLong(
+ RangerConstants.RANGER_HBASE_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_PROP,
+ RangerConstants.RANGER_HBASE_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_DEFAULT);
+
+ String lastStoredFileName = RangerConfiguration.getInstance().get(RangerConstants.RANGER_HBASE_LAST_SAVED_POLICY_FILE_PROP) ;
+
+ String sslConfigFileName = RangerConfiguration.getInstance().get(RangerConstants.RANGER_HBASE_POLICYMGR_SSL_CONFIG_FILE_PROP) ;
+ refresher = new PolicyRefresher(url, refreshInMilli,sslConfigFileName,lastStoredFileName) ;
+
+ String saveAsFileName = RangerConfiguration.getInstance().get(RangerConstants.RANGER_HBASE_POLICYMGR_URL_SAVE_FILE_PROP) ;
+ if (saveAsFileName != null) {
+ refresher.setSaveAsFileName(saveAsFileName) ;
+ }
+
+ if (lastStoredFileName != null) {
+ refresher.setLastStoredFileName(lastStoredFileName);
+ }
+ }
+
+ private void init() {
+ refresher.setPolicyChangeListener(this);
+ }
+
+ public boolean isAccessAllowed(User user, Action accessAction) {
+ if (authDB != null) {
+ return authDB.isAccessAllowed(user, accessAction);
+ } else {
+ return false;
+ }
+ }
+
+ public boolean isAccessAllowed(User user, byte[] tableName, Action accessAction) {
+ if (authDB != null) {
+ return authDB.isAccessAllowed(user, tableName, accessAction);
+ } else {
+ return false;
+ }
+ }
+
+
+ public boolean isAccessAllowed(User user, byte[] tableName, byte[] columnFamily, byte[] qualifier, Action accessAction) {
+ if (authDB != null) {
+ return authDB.isAccessAllowed(user, tableName, columnFamily, qualifier, accessAction);
+ } else {
+ return false;
+ }
+ }
+
+ public boolean isEncrypted(byte[] tableName, byte[] columnFamily, byte[] qualifier) {
+ if (authDB != null) {
+ return authDB.isEncrypted(tableName, columnFamily, qualifier);
+ } else {
+ return false;
+ }
+ }
+
+ public boolean isTableHasEncryptedColumn(byte[] tableName) {
+ if (authDB != null) {
+ return authDB.isTableHasEncryptedColumn(tableName);
+ } else {
+ return false;
+ }
+ }
+
+
+ public boolean isAudited(byte[] tableName) {
+ if (authDB != null) {
+ return authDB.isAudited(tableName);
+ } else {
+ return false;
+ }
+ }
+
+ public List<UserPermission> getUserPermissions(User aUser) {
+ if (authDB != null) {
+ return authDB.getUserPermissions(aUser) ;
+ } else {
+ return null;
+ }
+ }
+
+ public List<UserPermission> getUserPermissions(User aUser, byte[] aTableName) {
+ if (authDB != null) {
+ return authDB.getUserPermissions(aUser, aTableName) ;
+ } else {
+ return null;
+ }
+ }
+
+ @Override
+ public void OnPolicyChange(PolicyContainer aPolicyContainer) {
+
+ if (aPolicyContainer == null) {
+ return ;
+ }
+
+ ArrayList<HBaseAuthRules> ruleListTemp = new ArrayList<HBaseAuthRules>();
+
+ HBaseAuthRules globalRule = new HBaseAuthRules(".META.", "*", "*", "read", null, RangerConstants.PUBLIC_ACCESS_ROLE) ;
+ ruleListTemp.add(globalRule) ;
+ globalRule = new HBaseAuthRules("-ROOT-", "*", "*", "read", null, RangerConstants.PUBLIC_ACCESS_ROLE) ;
+ ruleListTemp.add(globalRule) ;
+
+ ArrayList<String> auditListTemp = new ArrayList<String>();
+
+ ArrayList<String> encryptList = new ArrayList<String>();
+
+ for(Policy acl : aPolicyContainer.getAcl()) {
+
+ if (! acl.isEnabled()) {
+ LOG.debug("Diabled acl found [" + acl + "]. Skipping this acl ...") ;
+ continue ;
+ }
+
+ for(String table : acl.getTableList()) {
+ for(String colfamily : acl.getColumnFamilyList()) {
+ for(String col : acl.getColumnList()) {
+ if (table == null || table.isEmpty()) {
+ table = "*" ;
+ }
+ if (colfamily == null || colfamily.isEmpty()) {
+ colfamily = "*" ;
+ }
+ if (col == null || col.isEmpty()) {
+ col = "*" ;
+ }
+
+ if (acl.getAuditInd() == 1) {
+ if (!auditListTemp.contains(table)) {
+ LOG.debug("Adding [" + table + "] to audit list");
+ auditListTemp.add(table);
+ }
+ }
+
+ if (acl.getEncryptInd() == 1) {
+ String fqn = table + "/" + colfamily + "/" + col ;
+ if (!encryptList.contains(fqn)) {
+ LOG.debug("Adding [" + fqn + "] to encrypt list");
+ encryptList.add(fqn);
+ }
+ }
+
+ for(RolePermission rp : acl.getPermissions()) {
+ for (String accessLevel : rp.getAccess() ) {
+ if (rp.getGroups() != null && rp.getGroups().size() > 0) {
+ for (String group : rp.getGroups()) {
+ HBaseAuthRules rule = new HBaseAuthRules(table, colfamily, col, accessLevel, null, group);
+ LOG.debug("Adding (group) rule: [" + rule + "]") ;
+ ruleListTemp.add(rule);
+ }
+ }
+ if (rp.getUsers() != null && rp.getUsers().size() > 0) {
+ for (String user : rp.getUsers()) {
+ HBaseAuthRules rule = new HBaseAuthRules(table, colfamily, col, accessLevel, user, null);
+ LOG.debug("Adding (user) rule: [" + rule + "]") ;
+ ruleListTemp.add(rule);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ HBaseAuthDB authDBTemp = new HBaseAuthDB(ruleListTemp, auditListTemp, encryptList);
+ authDB = authDBTemp;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/hdfs/AdminPolicyChecker.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/hdfs/AdminPolicyChecker.java b/agents-impl/src/main/java/org/apache/ranger/pdp/hdfs/AdminPolicyChecker.java
new file mode 100644
index 0000000..919a7a1
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/hdfs/AdminPolicyChecker.java
@@ -0,0 +1,183 @@
+/*
+ * 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.pdp.hdfs;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Random;
+
+import org.apache.commons.io.FilenameUtils;
+
+public class AdminPolicyChecker {
+
+ private static final String PATH_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrst0123456789-_." ;
+ private static char[] PATH_CHAR_SET = PATH_CHARS.toCharArray() ;
+ private static int PATH_CHAR_SET_LEN = PATH_CHAR_SET.length ;
+
+
+ public static List<String> adminUserList = new ArrayList<String>() ; // "cli@adfpros.com"
+ public static List<String> adminGroupList = new ArrayList<String>() ;
+
+ static {
+ adminUserList.add("cli@adfpros.com") ;
+ adminGroupList.add("policymgradmin") ;
+ }
+
+
+ public void checkAdminAccessForResource(String selectedResourcePath, boolean isRecursiveFlag, String username) {
+
+ if (adminUserList.contains(username)) {
+ return ;
+ }
+
+ List<String> groups = getUserGroupsForUser(username) ;
+
+ if (adminGroupList.contains(groups)) {
+
+ }
+
+ checkAdminAccessForResource(new Path(selectedResourcePath, isRecursiveFlag), username) ;
+ }
+
+ private void checkAdminAccessForResource(Path resourcePath, String username) {
+
+ List<Path> adminPathList = getAdminPathFromDB(username) ;
+
+ if (!adminPathList.isEmpty()) {
+ for(Path adminPath : adminPathList ) {
+ if (adminPath.isMatched(resourcePath)) {
+ return ;
+ }
+ }
+ }
+
+ throw new SecurityException("User [" + username + "] does not have admin privileges on path [" + resourcePath + "]") ;
+
+ }
+
+ class Path {
+ String fullPath ;
+ boolean recursiveFlag ;
+
+ Path(String fullPath, boolean recursiveFlag) {
+ this.fullPath = fullPath;
+ this.recursiveFlag = recursiveFlag;
+ }
+
+ public boolean isMatched(Path resourcePath) {
+ // Since it is a Regular Expression Compared with Regular Expression
+ // We will expand the resourcepath to a normalized form and see if it matches with the fullpath using a WildCardMatch
+ // THIS IS JUST A WORK-AROUND. Need more permanent solution - 11/19/2013
+
+ String expandedPath = repaceMetaChars(resourcePath) ;
+
+ if (recursiveFlag) {
+ return URLBasedAuthDB.isRecursiveWildCardMatch(expandedPath, fullPath) ;
+ }
+ else {
+ return FilenameUtils.wildcardMatch(expandedPath, fullPath) ;
+ }
+ }
+
+ private String repaceMetaChars(Path regEx) {
+
+ String expandedPath = regEx.fullPath ;
+
+ if (expandedPath.contains("*")) {
+ String replacement = getRandomString(5,60) ;
+ expandedPath.replaceAll("\\*", replacement) ;
+ }
+
+ if (expandedPath.contains("?")) {
+ String replacement = getRandomString(1,1) ;
+ expandedPath.replaceAll("\\?", replacement) ;
+ }
+
+ if (regEx.recursiveFlag) {
+ int level = getRandomInt(3,10) ;
+ if (! expandedPath.endsWith("/")) {
+ expandedPath = expandedPath + "/" ;
+ }
+ expandedPath = expandedPath + getRandomString(5,60) ;
+
+ for(int i = 1 ; i < level ; i++) {
+ expandedPath = expandedPath + "/" + getRandomString(5,60) ;
+ }
+ }
+ return expandedPath ;
+ }
+
+
+ private Random random = new Random() ;
+
+ private String getRandomString(int minLen, int maxLen) {
+ StringBuilder sb = new StringBuilder() ;
+ int len = getRandomInt(minLen,maxLen) ;
+ for(int i = 0 ; i < len ; i++) {
+ int charIdx = random.nextInt(PATH_CHAR_SET_LEN) ;
+ sb.append( PATH_CHAR_SET[charIdx] ) ;
+ }
+ return null;
+ }
+
+ private int getRandomInt(int min, int max) {
+ if (min == max) {
+ return min ;
+ }
+ else {
+ int interval = max - min ;
+ return ((random.nextInt() % interval) + min) ;
+ }
+ }
+
+ }
+
+
+ private List<Path> getAdminPathFromDB(String username) {
+
+ List<Path> ret = new ArrayList<Path>() ;
+
+ //
+ // TODO: database work to get ACL ....
+ //
+
+ // Get all policy acl where the user has ADMIN permission +
+ // Get all policy acl where group associated with user has ADMIN permission
+ // For each of the acl
+ // For path in acl.getResourcePath().splitBy(",")
+ // ret.add(new Path(path, acl.recursiveFlag)) ;
+
+ return ret;
+ }
+
+
+ private List<String> getUserGroupsForUser(String username) {
+ List<String> groupList = new ArrayList<String>() ;
+
+ //
+ // TODO: database work to get List of groups ....
+ //
+
+ return groupList ;
+ }
+
+
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/hdfs/RangerAuthorizer.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/hdfs/RangerAuthorizer.java b/agents-impl/src/main/java/org/apache/ranger/pdp/hdfs/RangerAuthorizer.java
new file mode 100644
index 0000000..da6dd65
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/hdfs/RangerAuthorizer.java
@@ -0,0 +1,40 @@
+/*
+ * 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.pdp.hdfs;
+
+import java.util.Set;
+
+import org.apache.ranger.authorization.hadoop.HDFSAccessVerifier;
+
+public class RangerAuthorizer implements HDFSAccessVerifier {
+
+ private static URLBasedAuthDB authDB = URLBasedAuthDB.getInstance() ;
+
+ @Override
+ public boolean isAccessGranted(String aPathName, String aPathOwnerName, String access, String username, Set<String> groups) {
+ return authDB.isAccessGranted(aPathName, aPathOwnerName, access, username, groups);
+ }
+
+ @Override
+ public boolean isAuditLogEnabled(String aPathName) {
+ return authDB.isAuditLogEnabled(aPathName) ;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/hdfs/URLBasedAuthDB.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/hdfs/URLBasedAuthDB.java b/agents-impl/src/main/java/org/apache/ranger/pdp/hdfs/URLBasedAuthDB.java
new file mode 100644
index 0000000..4136c6d
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/hdfs/URLBasedAuthDB.java
@@ -0,0 +1,479 @@
+/*
+ * 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.pdp.hdfs;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.log4j.Level;
+import org.apache.log4j.LogManager;
+import org.apache.ranger.authorization.hadoop.HDFSAccessVerifier;
+import org.apache.ranger.authorization.hadoop.config.RangerConfiguration;
+import org.apache.ranger.pdp.config.PolicyChangeListener;
+import org.apache.ranger.pdp.config.PolicyRefresher;
+import org.apache.ranger.pdp.constants.RangerConstants;
+import org.apache.ranger.pdp.model.Policy;
+import org.apache.ranger.pdp.model.PolicyContainer;
+import org.apache.ranger.pdp.model.ResourcePath;
+import org.apache.ranger.pdp.model.RolePermission;
+
+public class URLBasedAuthDB implements HDFSAccessVerifier, PolicyChangeListener {
+
+ private static final Log LOG = LogFactory.getLog(URLBasedAuthDB.class) ;
+
+ private static URLBasedAuthDB me = null;
+
+ private PolicyRefresher refresher = null ;
+
+ private PolicyContainer policyContainer = null;
+
+ private HashMap<String,Boolean> cachedAuditFlag = new HashMap<String,Boolean>() ; // needs to be cleaned when ruleList changes
+
+ private static final long MAX_NO_OF_AUDIT_CACHE_ENTRIES = 1000L ;
+
+
+ public static URLBasedAuthDB getInstance() {
+ if (me == null) {
+ synchronized (URLBasedAuthDB.class) {
+ URLBasedAuthDB temp = me;
+ if (temp == null) {
+ me = new URLBasedAuthDB();
+ me.init() ;
+ }
+ }
+ }
+ return me;
+ }
+
+ private URLBasedAuthDB() {
+ String url = RangerConfiguration.getInstance().get(RangerConstants.RANGER_HDFS_POLICYMGR_URL_PROP);
+ long refreshInMilli = RangerConfiguration.getInstance().getLong(
+ RangerConstants.RANGER_HDFS_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_PROP ,
+ RangerConstants.RANGER_HDFS_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_DEFAULT);
+ String sslConfigFileName = RangerConfiguration.getInstance().get(RangerConstants.RANGER_HDFS_POLICYMGR_SSL_CONFIG_FILE_PROP) ;
+
+ String lastStoredFileName = RangerConfiguration.getInstance().get(RangerConstants.RANGER_HDFS_LAST_SAVED_POLICY_FILE_PROP) ;
+
+ refresher = new PolicyRefresher(url, refreshInMilli,sslConfigFileName,lastStoredFileName) ;
+
+ String saveAsFileName = RangerConfiguration.getInstance().get(RangerConstants.RANGER_HDFS_POLICYMGR_URL_SAVE_FILE_PROP) ;
+ if (saveAsFileName != null) {
+ refresher.setSaveAsFileName(saveAsFileName) ;
+ }
+
+ if (lastStoredFileName != null) {
+ refresher.setLastStoredFileName(lastStoredFileName);
+ }
+ }
+
+ private void init() {
+ refresher.setPolicyChangeListener(this);
+ }
+
+ @Override
+ public void OnPolicyChange(PolicyContainer aPolicyContainer) {
+ setPolicyContainer(aPolicyContainer);
+ }
+
+
+ @Override
+ public boolean isAccessGranted(String aPathName, String pathOwnerName, String access, String username, Set<String> groups) {
+
+ PolicyContainer pc = getPolicyContainer() ;
+
+ if (pc == null) {
+ return false ;
+ }
+
+ for(Policy acl : pc.getAcl()) {
+
+ if (! acl.isEnabled()) {
+ LOG.debug("Diabled acl found [" + acl + "]. Skipping this acl ...") ;
+ continue ;
+ }
+
+ for(ResourcePath resource : acl.getResourceList()) {
+
+ String path = resource.getPath() ;
+
+ boolean rulePathMatched = false ;
+
+ if (acl.getRecursiveInd() == 1) {
+ if (resource.isWildcardPath()) {
+ rulePathMatched = isRecursiveWildCardMatch(aPathName, path) ;
+ }
+ else {
+ rulePathMatched = aPathName.startsWith(path) ;
+ }
+ }
+ else {
+ if (resource.isWildcardPath()) {
+ rulePathMatched = FilenameUtils.wildcardMatch(aPathName, path) ;
+ }
+ else {
+ rulePathMatched = aPathName.equals(path) ;
+ }
+ }
+
+
+ if (rulePathMatched) {
+ for (RolePermission rp : acl.getPermissions()) {
+ if (rp.getAccess().contains(access)) {
+ if ( rp.getUsers().contains(username) ) {
+ return true ;
+ }
+ for(String ug : groups) {
+ if ( rp.getGroups().contains(ug)) {
+ return true ;
+ }
+ }
+ if (rp.getGroups().contains(RangerConstants.PUBLIC_ACCESS_ROLE)) {
+ return true ;
+ }
+ }
+ }
+ }
+
+ }
+ }
+
+ return false ;
+
+ }
+
+ public static boolean isRecursiveWildCardMatch(String pathToCheck, String wildcardPath) {
+ if (pathToCheck != null) {
+ StringBuilder sb = new StringBuilder() ;
+ for(String p : pathToCheck.split(File.separator) ) {
+ sb.append(p) ;
+ boolean matchFound = FilenameUtils.wildcardMatch(sb.toString(), wildcardPath) ;
+ if (matchFound) {
+ return true ;
+ }
+ sb.append(File.separator) ;
+ }
+ sb = null;
+ }
+ return false;
+ }
+
+ public PolicyContainer getPolicyContainer() {
+ return policyContainer;
+ }
+
+ private synchronized void setPolicyContainer(PolicyContainer aPolicyContainer) {
+
+ for(Policy p : aPolicyContainer.getAcl()) {
+ for(RolePermission rp : p.getPermissions()) {
+ List<String> rpaccess = rp.getAccess() ;
+ if (rpaccess != null && rpaccess.size() > 0) {
+ List<String> temp = new ArrayList<String>() ;
+ for(String s : rpaccess) {
+ temp.add(s.toLowerCase()) ;
+ }
+ rp.setAccess(temp);
+ }
+ }
+ }
+
+ this.policyContainer = aPolicyContainer ;
+ this.cachedAuditFlag.clear();
+ }
+
+
+
+ public UserPermission printPermissionInfo(UserGroupInformation ugi) {
+ return printPermissionInfo(ugi, null) ;
+ }
+
+ public UserPermission printPermissionInfo(UserGroupInformation ugi, String aPathName) {
+
+ String username = ugi.getShortUserName() ;
+
+ String[] groups = ugi.getGroupNames() ;
+
+ UserPermission up = new UserPermission(username,groups, aPathName) ;
+
+ PolicyContainer pc = getPolicyContainer() ;
+
+ if (pc != null) {
+
+ for(Policy acl : pc.getAcl()) {
+
+ for(ResourcePath resource : acl.getResourceList()) {
+
+ String path = resource.getPath() ;
+
+ boolean rulePathMatched = false ;
+
+ if (acl.getRecursiveInd() == 1) {
+ if (resource.isWildcardPath()) {
+ rulePathMatched = isRecursiveWildCardMatch(aPathName, path) ;
+ }
+ else {
+ rulePathMatched = aPathName.startsWith(path) ;
+ }
+ }
+ else {
+ if (resource.isWildcardPath()) {
+ rulePathMatched = FilenameUtils.wildcardMatch(aPathName, path) ;
+ }
+ else {
+ rulePathMatched = aPathName.equals(path) ;
+ }
+ }
+
+
+ if (rulePathMatched) {
+ for (RolePermission rp : acl.getPermissions()) {
+ boolean isAccessGranted = false ;
+ if (! isAccessGranted ) {
+ if ( rp.getUsers().contains(username) ) {
+ up.add(resource, acl.getRecursiveInd(), username, null, rp.getAccess());
+ isAccessGranted = true ;
+ }
+ }
+ if ( ! isAccessGranted ) {
+ for(String ug : groups) {
+ if ( rp.getGroups().contains(ug)) {
+ up.add(resource, acl.getRecursiveInd(), null, ug, rp.getAccess());
+ }
+ }
+ }
+ if (! isAccessGranted ) {
+ if (rp.getGroups().contains(RangerConstants.PUBLIC_ACCESS_ROLE)) {
+ up.add(resource, acl.getRecursiveInd(), null, RangerConstants.PUBLIC_ACCESS_ROLE, rp.getAccess());
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return up ;
+ }
+
+
+ class UserPermission {
+
+ private String userName ;
+ private String groups ;
+ private String pathName ;
+ private HashMap<String,HashSet<String>> userPermissionMap = new HashMap<String,HashSet<String>>() ;
+
+ public UserPermission(String userName, String[] groupList, String pathName) {
+ this.userName = userName ;
+ this.pathName = pathName ;
+ StringBuilder sb = new StringBuilder() ;
+ boolean first = true ;
+ TreeSet<String> gl = new TreeSet<String>() ;
+ for(String g : groupList) {
+ gl.add(g) ;
+ }
+ for(String group : gl) {
+ if (first) {
+ first = false ;
+ }
+ else {
+ sb.append(",") ;
+ }
+ sb.append(group) ;
+ }
+ this.groups = sb.toString() ;
+ }
+
+
+ public void add(ResourcePath resource, int recursiveInd, String userName, String groupName, List<String> accessList) {
+
+ String path = resource.getPath() ;
+
+ if (recursiveInd == 1) {
+ if (path.endsWith("/")) {
+ path = path + "**" ;
+ }
+ else {
+ path = path + "/" + "**" ;
+ }
+ }
+
+ HashSet<String> permMap = userPermissionMap.get(path) ;
+
+ if (permMap == null) {
+ permMap = new HashSet<String>() ;
+ userPermissionMap.put(path,permMap) ;
+ }
+
+ for(String access : accessList) {
+ if (! permMap.contains(access)) {
+ permMap.add(access) ;
+ }
+ }
+
+ }
+
+ public void printUserInfo() {
+ System.out.println("# USER INFORMATION") ;
+ System.out.println("USER: " + userName ) ;
+ System.out.println("GROUPS: " + groups ) ;
+ }
+
+ public void print() {
+ if (pathName != null) {
+ System.out.println("# PERMISSION INFORMATION FOR PATH [" + pathName + "]" + (userPermissionMap.size() == 0 ? " - NO RULES FOUND" : "")) ;
+ }
+ else {
+ System.out.println("# PERMISSION INFORMATION" + (userPermissionMap.size() == 0 ? " - NO RULES FOUND" : "")) ;
+ }
+
+
+ if (userPermissionMap.size() > 0) {
+ TreeSet<String> pathSet = new TreeSet<String>() ;
+ pathSet.addAll(userPermissionMap.keySet()) ;
+ StringBuilder sb = new StringBuilder();
+ for(String path : pathSet) {
+ sb.setLength(0) ;
+ sb.append(String.format("%-50s", path)).append("|") ;
+ TreeSet<String> permSet = new TreeSet<String>() ;
+ permSet.addAll(userPermissionMap.get(path)) ;
+ boolean first = true ;
+ for(String perm: permSet) {
+ if (! first) {
+ sb.append(",") ;
+ }
+ else {
+ first = false ;
+ }
+ sb.append(perm) ;
+ }
+ System.out.println(sb.toString()) ;
+ }
+ }
+
+ }
+ }
+
+
+ @Override
+ public boolean isAuditLogEnabled(String aPathName) {
+ boolean ret = false ;
+
+ HashMap<String,Boolean> tempCachedAuditFlag = cachedAuditFlag ;
+
+ Boolean auditResult = (tempCachedAuditFlag == null ? null : tempCachedAuditFlag.get(aPathName)) ;
+
+ if (auditResult != null) {
+ ret = auditResult ;
+ }
+ else {
+ ret = isAuditLogEnabledByACL(aPathName) ;
+ if (tempCachedAuditFlag != null) {
+ // tempCachedAuditFlag.put(aPathName,Boolean.valueOf(ret)) ;
+ synchronized(tempCachedAuditFlag) {
+ if (tempCachedAuditFlag.size() > MAX_NO_OF_AUDIT_CACHE_ENTRIES) {
+ tempCachedAuditFlag.clear();
+ }
+ tempCachedAuditFlag.put(aPathName,Boolean.valueOf(ret)) ;
+ }
+ }
+ }
+
+ return ret ;
+
+ }
+
+
+ public boolean isAuditLogEnabledByACL(String aPathName) {
+
+ boolean ret = false ;
+
+ PolicyContainer pc = getPolicyContainer() ;
+
+ if (pc == null) {
+ return false ;
+ }
+
+ for(Policy acl : pc.getAcl()) {
+
+ for(ResourcePath resource : acl.getResourceList()) {
+
+ String path = resource.getPath() ;
+
+ boolean rulePathMatched = false ;
+
+ if (acl.getRecursiveInd() == 1) {
+ if (resource.isWildcardPath()) {
+ rulePathMatched = isRecursiveWildCardMatch(aPathName, path) ;
+ }
+ else {
+ rulePathMatched = aPathName.startsWith(path) ;
+ }
+ }
+ else {
+ if (resource.isWildcardPath()) {
+ rulePathMatched = FilenameUtils.wildcardMatch(aPathName, path) ;
+ }
+ else {
+ rulePathMatched = aPathName.equals(path) ;
+ }
+ }
+
+
+ if (rulePathMatched) {
+ ret = ( acl.getAuditInd() == 1) ;
+ break ;
+ }
+ }
+ }
+
+ return ret ;
+ }
+
+ public static void main(String[] args) throws Throwable {
+ LogManager.getLogger(URLBasedAuthDB.class).setLevel(Level.ERROR);
+ URLBasedAuthDB authDB = URLBasedAuthDB.getInstance() ;
+ UserPermission up = null;
+ if (args.length == 0) {
+ up = authDB.printPermissionInfo(UserGroupInformation.getCurrentUser());
+ up.printUserInfo() ;
+ up.print();
+ }
+ else {
+ up = authDB.printPermissionInfo(UserGroupInformation.getCurrentUser());
+ up.printUserInfo() ;
+ for(String path : args) {
+ up = authDB.printPermissionInfo(UserGroupInformation.getCurrentUser(), path);
+ up.print();
+ System.out.println();
+ }
+ }
+ System.exit(0);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/hive/HiveAuthDB.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/hive/HiveAuthDB.java b/agents-impl/src/main/java/org/apache/ranger/pdp/hive/HiveAuthDB.java
new file mode 100644
index 0000000..f9bdedf
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/hive/HiveAuthDB.java
@@ -0,0 +1,306 @@
+/*
+ * 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.pdp.hive;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.ranger.authorization.hive.RangerHiveObjectAccessInfo;
+import org.apache.ranger.authorization.hive.RangerHiveObjectAccessInfo.HiveAccessType;
+import org.apache.ranger.authorization.hive.RangerHiveObjectAccessInfo.HiveObjectType;
+import org.apache.ranger.authorization.utils.StringUtil;
+
+public class HiveAuthDB {
+
+ private static final Log LOG = LogFactory.getLog(HiveAuthDB.class);
+
+ private ArrayList<HiveAuthRule> allRuleList = null;
+ private ArrayList<HiveAuthRule> tblRuleList = null;
+ private ArrayList<HiveAuthRule> colRuleList = null;
+
+ public HiveAuthDB() {
+ this(null) ;
+ }
+
+
+ public HiveAuthDB(ArrayList<HiveAuthRule> aRuleList) {
+
+ if (aRuleList == null) {
+ aRuleList = new ArrayList<HiveAuthRule>() ;
+ }
+
+ LOG.info("Number of Rules in the PolicyContainer: " + ((aRuleList == null) ? 0 : aRuleList.size()) ) ;
+
+ allRuleList = new ArrayList<HiveAuthRule>() ;
+ colRuleList = new ArrayList<HiveAuthRule>();
+ tblRuleList = new ArrayList<HiveAuthRule>() ;
+
+ allRuleList = aRuleList ;
+
+ for (HiveAuthRule rule : aRuleList) {
+ if (rule.isTableRule()) {
+ this.tblRuleList.add(rule);
+ } else {
+ this.colRuleList.add(rule);
+ }
+ }
+
+ }
+
+ public boolean isAccessAllowed(UserGroupInformation ugi, RangerHiveObjectAccessInfo objAccessInfo) {
+ boolean ret = false;
+
+ if(objAccessInfo.getAccessType() == HiveAccessType.NONE || objAccessInfo.getObjectType() == HiveObjectType.NONE) {
+ return true;
+ }
+
+ String accessType = objAccessInfo.getAccessType().name();
+
+ switch(objAccessInfo.getObjectType()) {
+ case DATABASE:
+ ret = isAccessAllowed(ugi, accessType, objAccessInfo.getDatabase());
+ break;
+
+ case TABLE:
+ case INDEX:
+ case PARTITION:
+ ret = isAccessAllowed(ugi, accessType, objAccessInfo.getDatabase(), objAccessInfo.getTable());
+ break;
+
+ case VIEW:
+ ret = isAccessAllowed(ugi, accessType, objAccessInfo.getDatabase(), objAccessInfo.getView());
+ break;
+
+ case COLUMN:
+ {
+ String deniedColumn = findDeniedColumn(ugi, accessType, objAccessInfo.getDatabase(), objAccessInfo.getTable(), objAccessInfo.getColumns());
+
+ ret = StringUtil.isEmpty(deniedColumn);
+
+ if(! ret) {
+ objAccessInfo.setDeinedObjectName(RangerHiveObjectAccessInfo.getObjectName(objAccessInfo.getDatabase(), objAccessInfo.getTable(), deniedColumn));
+ }
+ }
+ break;
+
+ case FUNCTION:
+ ret = isUDFAccessAllowed(ugi, accessType, objAccessInfo.getDatabase(), objAccessInfo.getFunction());
+ break;
+
+ case URI:
+ // Handled in RangerHiveAuthorizer
+ break;
+
+ case NONE:
+ break;
+ }
+
+ return ret;
+ }
+
+ public boolean isAudited(RangerHiveObjectAccessInfo objAccessInfo) {
+ boolean ret = false;
+
+ if( objAccessInfo.getAccessType() == HiveAccessType.NONE
+ || objAccessInfo.getObjectType() == HiveObjectType.NONE
+ || objAccessInfo.getObjectType() == HiveObjectType.URI
+ ) {
+ return false;
+ }
+
+ String database = null;
+ String table = null;
+ List<String> columns = null;
+ boolean isUDF = false;
+
+ switch(objAccessInfo.getObjectType()) {
+ case DATABASE:
+ database = objAccessInfo.getDatabase();
+ break;
+
+ case TABLE:
+ case INDEX:
+ case PARTITION:
+ database = objAccessInfo.getDatabase();
+ table = objAccessInfo.getTable();
+ break;
+
+ case VIEW:
+ database = objAccessInfo.getDatabase();
+ table = objAccessInfo.getView();
+ break;
+
+ case COLUMN:
+ database = objAccessInfo.getDatabase();
+ table = objAccessInfo.getTable();
+ columns = objAccessInfo.getColumns();
+ break;
+
+ case FUNCTION:
+ database = objAccessInfo.getDatabase();
+ table = objAccessInfo.getFunction();
+ isUDF = true;
+ break;
+
+ case NONE:
+ case URI:
+ break;
+ }
+
+ if(StringUtil.isEmpty(columns)) {
+ for (HiveAuthRule rule : allRuleList) {
+ if(isUDF != rule.isUdf()) {
+ continue;
+ }
+
+ if (rule.isTableMatch(database, table)) {
+ ret = rule.isAudited() ;
+
+ if (ret) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("isAudited(database=" + database + ", table=" + table + ", columns=" + StringUtil.toString(columns) + ") => [" + ret + "] as matched for rule: " + rule);
+ }
+
+ break ;
+ }
+ }
+ }
+ } else {
+ // is audit enabled for any one column being accessed?
+ for(String colName : columns) {
+ for (HiveAuthRule rule : allRuleList) {
+ if(isUDF != rule.isUdf()) {
+ continue;
+ }
+
+ ret = rule.isMatched(database, table, colName) && rule.isAudited();
+
+ if (ret) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("isAudited(database=" + database + ", table=" + table + ", columns=" + StringUtil.toString(columns) + ") => [" + ret + "] as matched for rule: " + rule);
+ }
+
+ break ;
+ }
+ }
+
+ if(ret) {
+ break;
+ }
+ }
+ }
+
+ return ret ;
+ }
+
+ private boolean isAccessAllowed(UserGroupInformation ugi, String accessType, String database) {
+ boolean ret = false;
+
+ for (HiveAuthRule rule : allRuleList) {
+ ret = rule.isMatched(database, ugi.getShortUserName(), ugi.getGroupNames(), accessType);
+
+ if(ret) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("isAccessAllowed(user=" + ugi.getShortUserName() + ", groups=" + StringUtil.toString(ugi.getGroupNames()) + ", accessType=" + accessType + ", database=" + database + ") => [" + ret + "] as matched for rule: " + rule);
+ }
+
+ break;
+ }
+ }
+
+ return ret;
+ }
+
+ private boolean isAccessAllowed(UserGroupInformation ugi, String accessType, String database, String tableOrView) {
+ boolean ret = false;
+
+ for (HiveAuthRule rule : tblRuleList) {
+ ret = rule.isMatched(database, tableOrView, ugi.getShortUserName(), ugi.getGroupNames(), accessType);
+
+ if(ret) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("isAccessAllowed(user=" + ugi.getShortUserName() + ", groups=" + StringUtil.toString(ugi.getGroupNames()) + ", accessType=" + accessType + ", database=" + database + ", tableOrView=" + tableOrView + ") => [" + ret + "] as matched for rule: " + rule);
+ }
+
+ break;
+ }
+ }
+
+ return ret;
+ }
+
+ private String findDeniedColumn(UserGroupInformation ugi, String accessType, String database, String tableOrView, List<String> columns) {
+ String deinedColumn = null;
+
+ boolean isAllowed = isAccessAllowed(ugi, accessType, database, tableOrView); // check if access is allowed at the table level
+
+ if(!isAllowed && !StringUtil.isEmpty(columns)) {
+ for(String column : columns) {
+ for (HiveAuthRule rule : colRuleList) {
+ isAllowed = rule.isMatched(database, tableOrView, column, ugi.getShortUserName(), ugi.getGroupNames(), accessType);
+
+ if(isAllowed) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("isAccessAllowed(user=" + ugi.getShortUserName() + ", groups=" + StringUtil.toString(ugi.getGroupNames()) + ", accessType=" + accessType + ", database=" + database + ", tableOrView=" + tableOrView + ", column=" + column + ") => [" + isAllowed + "] as matched for rule: " + rule);
+ }
+
+ break;
+ }
+ }
+
+ if(!isAllowed) {
+ deinedColumn = column;
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("isAccessAllowed(user=" + ugi.getShortUserName() + ", groups=" + StringUtil.toString(ugi.getGroupNames()) + ", accessType=" + accessType + ", database=" + database + ", tableOrView=" + tableOrView + ", column=" + column + ") => [" + isAllowed + "]");
+ }
+ break;
+ }
+ }
+ }
+
+ return deinedColumn;
+ }
+
+ private boolean isUDFAccessAllowed(UserGroupInformation ugi, String accessType, String database, String udfName) {
+ boolean ret = false;
+
+ for (HiveAuthRule rule : tblRuleList) {
+ if(! rule.isUdf()) {
+ continue;
+ }
+
+ ret = rule.isMatched(database, udfName, ugi.getShortUserName(), ugi.getGroupNames(), accessType);
+
+ if(ret) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("isAccessAllowed(user=" + ugi.getShortUserName() + ", groups=" + StringUtil.toString(ugi.getGroupNames()) + ", accessType=" + accessType + ", database=" + database + ", udfName=" + udfName + ") => [" + ret + "] as matched for rule: " + rule);
+ }
+
+ break;
+ }
+ }
+
+ return ret;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/hive/HiveAuthRule.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/hive/HiveAuthRule.java b/agents-impl/src/main/java/org/apache/ranger/pdp/hive/HiveAuthRule.java
new file mode 100644
index 0000000..21bd7c1
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/hive/HiveAuthRule.java
@@ -0,0 +1,222 @@
+/*
+ * 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.pdp.hive;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.authorization.hive.RangerHiveObjectAccessInfo.HiveAccessType;
+import org.apache.ranger.authorization.hive.constants.RangerHiveConstants;
+import org.apache.ranger.authorization.utils.StringUtil;
+
+
+public class HiveAuthRule {
+
+ private static final Log LOG = LogFactory.getLog(HiveAuthRule.class) ;
+
+ public static final String WILDCARD_OBJECT = ".*" ;
+
+ private String databaseName;
+ private String tableName;
+ private String columnName;
+ private String accessType;
+ private String group;
+ private String user;
+ private boolean tableRule = false;
+ private boolean allGranted = false;
+ private boolean udf = false;
+ private boolean tableExcluded = false;
+ private boolean columnExcluded = false;
+ private boolean audited = false;
+ private boolean encrypted = false;
+
+ public HiveAuthRule(String dbName, String tableName, String colName, String permission, String user, String group) {
+ this(false, dbName,tableName,colName,permission,user,group, false, false) ;
+ }
+
+ public HiveAuthRule(boolean udfInd, String dbName, String tableName, String colName, String permission, String user, String group, boolean tableExclusionFlag, boolean columnExclusionFlag) {
+ this.udf = udfInd ;
+ this.databaseName = StringUtil.toLower(dbName);
+ this.tableName = StringUtil.toLower(tableName);
+ this.columnName = StringUtil.toLower(colName);
+ this.accessType = permission ;
+ this.user = user;
+ this.group = group ;
+ this.tableExcluded = tableExclusionFlag ;
+ this.columnExcluded = columnExclusionFlag ;
+
+ this.allGranted = StringUtil.equalsIgnoreCase(HiveAccessType.ALL.name(), accessType);
+
+ tableRule = StringUtil.isEmpty(columnName) || WILDCARD_OBJECT.matches(columnName) ;
+ }
+
+ @Override
+ public String toString() {
+ return "db:" + databaseName + ", table: " + tableName + ", columnName: " + columnName + ", accessType: " + accessType + ",user: " + user + ", group: " + group + ",isTable:" + tableRule + ",audited:" + audited + ",encrypted:" + encrypted ;
+ }
+
+ public boolean isMatched(String user, String[] groups, String accessType) {
+ String dbName = null;
+ String tblName = null;
+ String colName = null;
+
+ return isMatched(dbName, tblName, colName, user, groups, accessType) ;
+ }
+
+ public boolean isMatched(String dbName, String user, String[] groups, String accessType) {
+ String tblName = null;
+ String colName = null;
+
+ return isMatched(dbName, tblName, colName, user, groups, accessType) ;
+ }
+
+ public boolean isMatched(String dbName, String tblName, String user, String[] groups, String accessType) {
+ String colName = null;
+
+ return isMatched(dbName, tblName, colName, user, groups, accessType) ;
+ }
+
+ public boolean isMatched(String dbName, String tblName, String colName, String user, String[] groups, String accessType) {
+ boolean ret = isMatched(dbName, tblName, colName);
+
+ if(ret) {
+ // does accessType match?
+ ret = StringUtil.equalsIgnoreCase(accessType, this.accessType);
+
+ if(! ret && !StringUtil.equalsIgnoreCase(accessType, HiveAccessType.ADMIN.name())) {
+ ret = this.isAllGranted() || StringUtil.equalsIgnoreCase(accessType, "USE");
+ }
+
+ if(ret) {
+ // does user/group match?
+ ret = StringUtil.equals(user, this.user) ||
+ StringUtil.equals(RangerHiveConstants.PUBLIC_ACCESS_ROLE, this.group) ||
+ StringUtil.contains(groups, this.group);
+ }
+ }
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("isMatched(db=" + dbName + ", table=" + tblName + ", col=" + colName + ", user=" + user + ", groups=" + StringUtil.toString(groups) + ", accessType=" + accessType + ") => rule[" + this.databaseName + ":" + this.tableName + ":" + this.columnName + ":" + this.user + ":" + this.group + ":" + this.accessType + "] returns [" + ret + "]");
+ }
+
+ return ret ;
+ }
+
+ public boolean isMatched(String dbName, String tblName, String colName) {
+ boolean ret = isTableMatch(dbName, tblName);
+
+ if (ret) {
+ colName = StringUtil.toLower(colName);
+
+ if (colName != null) {
+ ret = colName.matches(this.columnName);
+
+ if (columnExcluded) {
+ ret = (! ret) ;
+ }
+ }
+ }
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("isMatched(db=" + dbName + ", table=" + tblName + ", col=" + colName + ") => rule[" + this.databaseName + ":" + this.tableName + ":" + this.columnName + "] returns [" + ret + "]");
+ }
+
+ return ret ;
+ }
+
+ public boolean isTableMatch(String dbName, String tblName) {
+ boolean ret = isDBMatch(dbName);
+
+ if(ret) {
+ tblName = StringUtil.toLower(tblName);
+
+ if(tblName != null) {
+ ret = tblName.matches(this.tableName);
+
+ if(tableExcluded) {
+ ret = !ret;
+ }
+ }
+ }
+
+ return ret;
+ }
+
+ public boolean isDBMatch(String dbName) {
+ boolean ret = false;
+
+ dbName = StringUtil.toLower(dbName);
+
+ ret = dbName == null || dbName.matches(this.databaseName);
+
+ return ret;
+ }
+
+ public String getDbName() {
+ return databaseName;
+ }
+
+ public String getTableName() {
+ return tableName;
+ }
+
+ public String getColumnName() {
+ return columnName;
+ }
+
+ public String getAccessType() {
+ return accessType;
+ }
+
+ public String getUser() {
+ return user;
+ }
+
+ public String getGroup() {
+ return group;
+ }
+
+ public boolean isTableRule() {
+ return tableRule;
+ }
+
+ public boolean isAllGranted() {
+ return allGranted ;
+ }
+
+ public boolean isUdf() {
+ return udf;
+ }
+
+ public boolean isAudited() {
+ return audited;
+ }
+
+ public void setAudited(boolean audited) {
+ this.audited = audited;
+ }
+
+ public boolean isEncrypted() {
+ return encrypted;
+ }
+
+ public void setEncrypted(boolean encrypted) {
+ this.encrypted = encrypted;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/hive/HiveAuthorizationProviderBase.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/hive/HiveAuthorizationProviderBase.java b/agents-impl/src/main/java/org/apache/ranger/pdp/hive/HiveAuthorizationProviderBase.java
new file mode 100644
index 0000000..894d2df
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/hive/HiveAuthorizationProviderBase.java
@@ -0,0 +1,64 @@
+/*
+ * 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.pdp.hive;
+
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.hive.ql.metadata.AuthorizationException;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.ranger.authorization.hive.RangerHiveAccessVerifier;
+import org.apache.ranger.authorization.hive.RangerHiveObjectAccessInfo;
+
+public class HiveAuthorizationProviderBase implements RangerHiveAccessVerifier {
+
+ private static final Log LOG = LogFactory.getLog(HiveAuthorizationProviderBase.class);
+
+ protected HiveAuthDB authDB = new HiveAuthDB() ;
+
+
+ public HiveAuthDB getAuthDB() {
+ return authDB ;
+ }
+
+ @Override
+ public boolean isAccessAllowed(UserGroupInformation ugi, RangerHiveObjectAccessInfo objAccessInfo) {
+ HiveAuthDB ldb = authDB ;
+
+ if (ldb == null) {
+ throw new AuthorizationException("No Authorization Agent is available for AuthorizationCheck") ;
+ }
+
+ boolean ret = ldb.isAccessAllowed(ugi, objAccessInfo);
+
+ return ret;
+ }
+
+ @Override
+ public boolean isAudited(RangerHiveObjectAccessInfo objAccessInfo) {
+ HiveAuthDB ldb = authDB ;
+
+ if (ldb == null) {
+ throw new AuthorizationException("No Authorization Agent is available for AuthorizationCheck") ;
+ }
+
+ return ldb.isAudited(objAccessInfo) ;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/hive/RangerAuthorizer.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/hive/RangerAuthorizer.java b/agents-impl/src/main/java/org/apache/ranger/pdp/hive/RangerAuthorizer.java
new file mode 100644
index 0000000..fc4291c
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/hive/RangerAuthorizer.java
@@ -0,0 +1,47 @@
+/*
+ * 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.pdp.hive;
+
+import org.apache.hadoop.hive.ql.metadata.AuthorizationException;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.ranger.authorization.hive.RangerHiveAccessVerifier;
+import org.apache.ranger.authorization.hive.RangerHiveObjectAccessInfo;
+
+public class RangerAuthorizer implements RangerHiveAccessVerifier {
+
+ private RangerHiveAccessVerifier authDB = URLBasedAuthDB.getInstance() ;
+
+
+ @Override
+ public boolean isAccessAllowed(UserGroupInformation ugi, RangerHiveObjectAccessInfo objAccessInfo) {
+ if (authDB == null) {
+ throw new AuthorizationException("No Authorization Agent is available for AuthorizationCheck") ;
+ }
+ return authDB.isAccessAllowed(ugi, objAccessInfo);
+ }
+
+ @Override
+ public boolean isAudited(RangerHiveObjectAccessInfo objAccessInfo) {
+ if (authDB == null) {
+ throw new AuthorizationException("No Authorization Agent is available for AuthorizationCheck") ;
+ }
+ return authDB.isAudited(objAccessInfo) ;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/hive/URLBasedAuthDB.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/hive/URLBasedAuthDB.java b/agents-impl/src/main/java/org/apache/ranger/pdp/hive/URLBasedAuthDB.java
new file mode 100644
index 0000000..9de2bf4
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/hive/URLBasedAuthDB.java
@@ -0,0 +1,221 @@
+/*
+ * 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.pdp.hive;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.authorization.hadoop.config.RangerConfiguration;
+import org.apache.ranger.pdp.config.PolicyChangeListener;
+import org.apache.ranger.pdp.config.PolicyRefresher;
+import org.apache.ranger.pdp.constants.RangerConstants;
+import org.apache.ranger.pdp.model.Policy;
+import org.apache.ranger.pdp.model.PolicyContainer;
+import org.apache.ranger.pdp.model.RolePermission;
+
+public class URLBasedAuthDB extends HiveAuthorizationProviderBase implements PolicyChangeListener {
+
+ private static final Log LOG = LogFactory.getLog(URLBasedAuthDB.class) ;
+
+ private static URLBasedAuthDB me = null ;
+
+ private PolicyContainer policyContainer = null ;
+
+ private PolicyRefresher refresher = null ;
+
+
+ public static URLBasedAuthDB getInstance() {
+ if (me == null) {
+ synchronized(URLBasedAuthDB.class) {
+ URLBasedAuthDB temp = me ;
+ if (temp == null) {
+ me = new URLBasedAuthDB() ;
+ me.init() ;
+ }
+ }
+ }
+ return me ;
+ }
+
+ private URLBasedAuthDB() {
+ String url = RangerConfiguration.getInstance().get(RangerConstants.RANGER_HIVE_POLICYMGR_URL_PROP);
+ long refreshInMilli = RangerConfiguration.getInstance().getLong(
+ RangerConstants.RANGER_HIVE_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_PROP ,
+ RangerConstants.RANGER_HIVE_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_DEFAULT);
+
+ String lastStoredFileName = RangerConfiguration.getInstance().get(RangerConstants.RANGER_HIVE_LAST_SAVED_POLICY_FILE_PROP) ;
+
+ String sslConfigFileName = RangerConfiguration.getInstance().get(RangerConstants.RANGER_HIVE_POLICYMGR_SSL_CONFIG_FILE_PROP) ;
+ refresher = new PolicyRefresher(url, refreshInMilli,sslConfigFileName,lastStoredFileName) ;
+
+ String saveAsFileName = RangerConfiguration.getInstance().get(RangerConstants.RANGER_HIVE_POLICYMGR_URL_SAVE_FILE_PROP) ;
+ if (saveAsFileName != null) {
+ refresher.setSaveAsFileName(saveAsFileName) ;
+ }
+
+ if (lastStoredFileName != null) {
+ refresher.setLastStoredFileName(lastStoredFileName);
+ }
+
+ }
+
+ private void init() {
+ refresher.setPolicyChangeListener(this);
+ }
+
+ public PolicyContainer getPolicyContainer() {
+ return policyContainer;
+ }
+
+ @Override
+ public void OnPolicyChange(PolicyContainer policyContainer) {
+
+ LOG.debug("OnPolicyChange() has been called with new PolicyContainer .....") ;
+
+ try {
+
+ ArrayList<HiveAuthRule> ruleListTemp = new ArrayList<HiveAuthRule>();
+
+ this.policyContainer = policyContainer;
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Number of acl found (before isEnabled check): " + ( policyContainer.getAcl() == null ? 0 : policyContainer.getAcl().size() ) );
+ }
+
+ for(Policy acl : policyContainer.getAcl()) {
+
+ if (! acl.isEnabled()) {
+ LOG.debug("Diabled acl found [" + acl + "]. Skipping this acl ...") ;
+ continue ;
+ }
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Number of database found in acl [" + acl + "] " + ( acl.getDatabaseList() == null ? 0 : acl.getDatabaseList().size() ) );
+ LOG.debug("Number of Tables found in acl [" + acl + "] " + ( acl.getTableList() == null ? 0 : acl.getTableList().size() ) );
+ LOG.debug("Number of Columns found in acl [" + acl + "] " + ( acl.getColumnList()== null ? 0 : acl.getColumnList().size() ) );
+ }
+
+ boolean isUDF = false ;
+
+ List<String> dbList = new ArrayList<String>() ;
+ String dbs = replaceFileBasedRegEx(acl.getDatabases()) ;
+ dbList.add(getRegExFormatted(dbs)) ;
+
+ List<String> tableList = new ArrayList<String>() ;
+ String udfs = acl.getUdfs() ;
+ if (udfs != null) {
+ isUDF = true ;
+ dbList.clear();
+ dbList.add(HiveAuthRule.WILDCARD_OBJECT) ;
+ tableList.clear();
+ udfs = replaceFileBasedRegEx(udfs) ;
+ tableList.add(getRegExFormatted(udfs)) ;
+ }
+ else {
+ String tables = replaceFileBasedRegEx(acl.getTables()) ;
+ tableList.add(getRegExFormatted(tables)) ;
+ }
+
+ List<String> columnList = new ArrayList<String>() ;
+ String columns = replaceFileBasedRegEx(acl.getColumns()) ;
+ columnList.add(getRegExFormatted(columns)) ;
+
+
+ boolean isAudited = (acl.getAuditInd() == 1) ;
+
+ boolean isEncrypted = (acl.getEncryptInd() == 1) ;
+
+ for(String db : dbList) {
+
+ for(String table : tableList) {
+
+ for(String col : columnList) {
+
+ for(RolePermission rp : acl.getPermissions()) {
+ for (String accessLevel : rp.getAccess() ) {
+ for (String group : rp.getGroups()) {
+ HiveAuthRule rule = new HiveAuthRule(isUDF, db, table, col, accessLevel.toLowerCase(), null, group, acl.isTableSelectionExcluded(), acl.isColumnSelectionExcluded());
+ rule.setAudited(isAudited);
+ rule.setEncrypted(isEncrypted);
+ LOG.debug("Adding rule [" + rule + "] to the authdb.");
+ ruleListTemp.add(rule);
+ }
+ for (String user : rp.getUsers()) {
+ HiveAuthRule rule = new HiveAuthRule(isUDF, db, table, col, accessLevel.toLowerCase(), user, null,acl.isTableSelectionExcluded(), acl.isColumnSelectionExcluded());
+ rule.setAudited(isAudited);
+ rule.setEncrypted(isEncrypted);
+ LOG.debug("Adding rule [" + rule + "] to the authdb.");
+ ruleListTemp.add(rule);
+ }
+ }
+ }
+
+
+ }
+ }
+ }
+ }
+ HiveAuthDB authDBTemp = new HiveAuthDB(ruleListTemp);
+ authDB = authDBTemp;
+ }
+ catch(Throwable t) {
+ LOG.error("OnPolicyChange has failed with an exception", t);
+ }
+ }
+
+ public static String getRegExFormatted(String userEnteredStr) {
+
+ if (userEnteredStr == null || userEnteredStr.trim().length() == 0) {
+ return HiveAuthRule.WILDCARD_OBJECT ;
+ }
+
+ StringBuilder sb = new StringBuilder() ;
+
+ for(String s : userEnteredStr.split(",")) {
+ if (sb.length() == 0) {
+ sb.append("(") ;
+ }
+ else {
+ sb.append("|") ;
+ }
+ sb.append(s.trim()) ;
+ }
+
+ if (sb.length() > 0) {
+ sb.append(")") ;
+ }
+
+ return sb.toString() ;
+ }
+
+
+ public static String replaceFileBasedRegEx(String userEnteredStr) {
+ if (userEnteredStr != null) {
+ userEnteredStr = userEnteredStr.replaceAll("\\.", "\\.")
+ .replaceAll("\\?", "\\.")
+ .replaceAll("\\*", ".*") ;
+ }
+ return userEnteredStr ;
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/knox/RangerAuthorizer.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/knox/RangerAuthorizer.java b/agents-impl/src/main/java/org/apache/ranger/pdp/knox/RangerAuthorizer.java
new file mode 100644
index 0000000..4d14ce0
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/knox/RangerAuthorizer.java
@@ -0,0 +1,64 @@
+/**
+ * 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.pdp.knox;
+
+import java.util.Set;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.authorization.knox.KnoxAccessVerifier;
+
+public class RangerAuthorizer implements KnoxAccessVerifier {
+
+ private static final Log LOG = LogFactory.getLog(RangerAuthorizer.class) ;
+
+ private static URLBasedAuthDB authDB = URLBasedAuthDB.getInstance() ;
+
+ public RangerAuthorizer() {
+ }
+
+ @Override
+ public boolean isAccessAllowed(String topologyName, String serviceName, String accessType,
+ String userName, Set<String> groups, String requestIp) {
+ boolean accessAllowed = authDB.isAccessGranted(topologyName, serviceName, accessType, userName, groups,
+ requestIp);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Computed access permission for topology: " + topologyName +
+ ", service: " + serviceName +
+ ", access: " + accessType +
+ ", requestingIp: " +requestIp +
+ ", requestingUser: " + userName +
+ ", requestingUserGroups: " + groups +
+ ", permitted: " + accessAllowed);
+ }
+ return accessAllowed;
+ }
+
+ @Override
+ public boolean isAuditEnabled(String topologyName, String serviceName) {
+ boolean auditEnabled = authDB.isAuditEnabled(topologyName, serviceName);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Computed audit enabled for topology: " + topologyName +
+ ", service: " + serviceName +
+ ", auditLogEnabled: " + auditEnabled);
+ }
+ return auditEnabled;
+ }
+
+}
[13/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/filter/XARESTAPIFilter.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/filter/XARESTAPIFilter.java b/security-admin/src/main/java/com/xasecure/service/filter/XARESTAPIFilter.java
deleted file mode 100644
index 4e1d69a..0000000
--- a/security-admin/src/main/java/com/xasecure/service/filter/XARESTAPIFilter.java
+++ /dev/null
@@ -1,281 +0,0 @@
-/*
- * 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 com.xasecure.service.filter;
-
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.core.MultivaluedMap;
-
-import com.xasecure.common.PropertiesUtil;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.config.BeanDefinition;
-import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
-
-import com.sun.jersey.api.container.filter.LoggingFilter;
-import com.sun.jersey.api.uri.UriTemplate;
-import com.sun.jersey.spi.container.ContainerRequest;
-import com.sun.jersey.spi.container.ContainerResponse;
-import com.xasecure.security.context.XAContextHolder;
-
-public class XARESTAPIFilter extends LoggingFilter {
- Logger logger = Logger.getLogger(XARESTAPIFilter.class);
- static boolean initDone = false;
-
- boolean logStdOut = true;
- HashMap<String, String> regexPathMap = new HashMap<String, String>();
- HashMap<String, Pattern> regexPatternMap = new HashMap<String, Pattern>();
- List<String> regexList = new ArrayList<String>();
- List<String> loggedRestPathErrors = new ArrayList<String>();
- private final Object lock = new Object();
-
- void init() {
- if (initDone) {
- return;
- }
- synchronized (lock) {
- if (initDone) {
- return;
- }
-
- logStdOut = PropertiesUtil.getBooleanProperty(
- "xa.restapi.log.enabled", initDone);
-
- // Build hash map
- try {
- loadPathPatterns();
- } catch (Throwable t) {
- logger.error(
- "Error parsing REST classes for PATH patterns. Error ignored, but should be fixed immediately",
- t);
- }
- initDone = true;
- }
-
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * com.sun.jersey.spi.container.ContainerRequestFilter#filter(com.sun.jersey
- * .spi.container.ContainerRequest)
- */
- @Override
- public ContainerRequest filter(ContainerRequest request) {
- if (!initDone) {
- init();
- }
- if (logStdOut) {
- String path = request.getRequestUri().getPath();
-
- // mediaType=multipart/form-data;boundary=----WebKitFormBoundaryTHan76r5AkgpAuVG
- if (request.getMediaType() != null) {
- // logger.info("DELETE ME: mediaType=" + request.getMediaType()
- // + ", getType()" + request.getMediaType().getType()
- // + ", getSubType()="
- // + request.getMediaType().getSubtype());
- } else {
- logger.info("DELETE ME: mediaType is null. path=" + path);
- }
- if ((request.getMediaType() == null || !request.getMediaType()
- .getType().equals("multipart"))
- && !path.endsWith("/service/general/logs")) {
- try {
- request = super.filter(request);
- } catch (Throwable t) {
- logger.error("Error FILTER logging. path=" + path, t);
- }
- }
- }
-
- return request;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * com.sun.jersey.spi.container.ContainerResponseFilter#filter(com.sun.jersey
- * .spi.container.ContainerRequest,
- * com.sun.jersey.spi.container.ContainerResponse)
- */
- @Override
- public ContainerResponse filter(ContainerRequest request,
- ContainerResponse response) {
- if (logStdOut) {
- // If it is image, then don't call super
- if (response.getMediaType() != null) {
- // logger.info("DELETE ME: Response= mediaType="
- // + response.getMediaType() + ", getType()"
- // + response.getMediaType().getType() + ", getSubType()="
- // + response.getMediaType().getSubtype());
- } else {
- logger.info("DELETE ME: Response= mediaType is null");
- }
- if (response.getMediaType() == null
- || !response.getMediaType().getType().equals("image")) {
-
- response = super.filter(request, response);
- }
- }
-
- return response;
- }
-
- private void loadPathPatterns() throws ClassNotFoundException {
- String pkg = "com.xasecure.service";
- // List<Class> cList = findClasses(new File(dir), pkg);
- @SuppressWarnings("rawtypes")
- List<Class> cList = findClasses(pkg);
- for (@SuppressWarnings("rawtypes")
- Class klass : cList) {
- Annotation[] annotations = klass.getAnnotations();
- for (Annotation annotation : annotations) {
- if (!(annotation instanceof Path)) {
- continue;
- }
- Path path = (Path) annotation;
- if (path.value().startsWith("crud")) {
- continue;
- }
- // logger.info("path=" + path.value());
- // Loop over the class methods
- for (Method m : klass.getMethods()) {
- Annotation[] methodAnnotations = m.getAnnotations();
- String httpMethod = null;
- String servicePath = null;
- for (int ma = 0; ma < methodAnnotations.length; ma++) {
- if (methodAnnotations[ma] instanceof GET) {
- httpMethod = "GET";
- } else if (methodAnnotations[ma] instanceof PUT) {
- httpMethod = "PUT";
- } else if (methodAnnotations[ma] instanceof POST) {
- httpMethod = "POST";
- } else if (methodAnnotations[ma] instanceof DELETE) {
- httpMethod = "DELETE";
- } else if (methodAnnotations[ma] instanceof Path) {
- servicePath = ((Path) methodAnnotations[ma])
- .value();
- }
- }
-
- if (httpMethod == null) {
- continue;
- }
-
- String fullPath = path.value();
- String regEx = httpMethod + ":" + path.value();
- if (servicePath != null) {
- if (!servicePath.startsWith("/")) {
- servicePath = "/" + servicePath;
- }
- UriTemplate ut = new UriTemplate(servicePath);
- regEx = httpMethod + ":" + path.value()
- + ut.getPattern().getRegex();
- fullPath += servicePath;
- }
- Pattern regexPattern = Pattern.compile(regEx);
-
- if (regexPatternMap.containsKey(regEx)) {
- logger.warn("Duplicate regex=" + regEx + ", fullPath="
- + fullPath);
- }
- regexList.add(regEx);
- regexPathMap.put(regEx, fullPath);
- regexPatternMap.put(regEx, regexPattern);
-
- logger.info("path=" + path.value() + ", servicePath="
- + servicePath + ", fullPath=" + fullPath
- + ", regEx=" + regEx);
- }
- }
- }
- // ReOrder list
- int i = 0;
- for (i = 0; i < 10; i++) {
- boolean foundMatches = false;
- List<String> tmpList = new ArrayList<String>();
- for (int x = 0; x < regexList.size(); x++) {
- boolean foundMatch = false;
- String rX = regexList.get(x);
- for (int y = 0; y < x; y++) {
- String rY = regexList.get(y);
- Matcher matcher = regexPatternMap.get(rY).matcher(rX);
- if (matcher.matches()) {
- foundMatch = true;
- foundMatches = true;
- // logger.info("rX " + rX + " matched with rY=" + rY
- // + ". Moving rX to the top. Loop count=" + i);
- break;
- }
- }
- if (foundMatch) {
- tmpList.add(0, rX);
- } else {
- tmpList.add(rX);
- }
- }
- regexList = tmpList;
- if (!foundMatches) {
- logger.info("Done rearranging. loopCount=" + i);
- break;
- }
- }
- if (i == 10) {
- logger.warn("Couldn't rearrange even after " + i + " loops");
- }
-
- logger.info("Loaded " + regexList.size() + " API methods.");
- // for (String regEx : regexList) {
- // logger.info("regEx=" + regEx);
- // }
- }
-
- @SuppressWarnings("rawtypes")
- private List<Class> findClasses(String packageName)
- throws ClassNotFoundException {
- List<Class> classes = new ArrayList<Class>();
-
- ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
- true);
-
- // scanner.addIncludeFilter(new
- // AnnotationTypeFilter(<TYPE_YOUR_ANNOTATION_HERE>.class));
-
- for (BeanDefinition bd : scanner.findCandidateComponents(packageName)) {
- classes.add(Class.forName(bd.getBeanClassName()));
- }
-
- return classes;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/util/CLIUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/util/CLIUtil.java b/security-admin/src/main/java/com/xasecure/util/CLIUtil.java
deleted file mode 100644
index 9bd7490..0000000
--- a/security-admin/src/main/java/com/xasecure/util/CLIUtil.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * 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 com.xasecure.util;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.support.ClassPathXmlApplicationContext;
-
-import com.xasecure.common.PropertiesUtil;
-import com.xasecure.security.standalone.StandaloneSecurityHandler;
-
-/**
- *
- *
- */
-@Component
-public class CLIUtil {
- static Logger logger = Logger.getLogger(CLIUtil.class);
-
- @Autowired
- StandaloneSecurityHandler securityHandler;
-
- static ApplicationContext context = null;
-
- public static void init() {
- if (context == null) {
- context = new ClassPathXmlApplicationContext(
- "applicationContext.xml",
- "security-applicationContext.xml",
- "asynctask-applicationContext.xml");
- }
- }
-
- public static Object getBean(Class<?> beanClass) {
- init();
- return context.getBean(beanClass);
- }
-
- public void authenticate() throws Exception {
- String user = PropertiesUtil.getProperty("xa.cli.user");
- String pwd = PropertiesUtil.getProperty("xa.cli.password");
- logger.info("Authenticating user:" + user);
- securityHandler.login(user, pwd, context);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/util/RestUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/util/RestUtil.java b/security-admin/src/main/java/com/xasecure/util/RestUtil.java
deleted file mode 100644
index 11b18ca..0000000
--- a/security-admin/src/main/java/com/xasecure/util/RestUtil.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * 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 com.xasecure.util;
-
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
-
-import org.springframework.stereotype.Component;
-
-import com.xasecure.security.context.XAContextHolder;
-
-@Component
-public class RestUtil {
-
- public static final String timeOffsetCookieName = "clientTimeOffset";
-
- public static Integer getTimeOffset(HttpServletRequest request) {
- Integer cookieVal = 0;
- try{
- Cookie[] cookies = request.getCookies();
- String timeOffset = null;
-
- if (cookies != null) {
- for (Cookie cookie : cookies) {
- try {
- if (cookie.getName().equals(timeOffsetCookieName)) {
- timeOffset = cookie.getValue();
- if (timeOffset != null) {
- cookieVal = Integer.parseInt(timeOffset);
- }
- break;
- }
- } catch (Exception ex) {
- cookieVal = 0;
- }
- }
- }
- }catch(Exception ex){
-
- }
- return cookieVal;
- }
-
- public static int getClientTimeOffset(){
- int clientTimeOffsetInMinute = 0;
- try{
- clientTimeOffsetInMinute= XAContextHolder.getSecurityContext().getRequestContext().getClientTimeOffsetInMinute();
- }catch(Exception ex){
-
- }
- if(clientTimeOffsetInMinute==0){
- try{
- clientTimeOffsetInMinute= XAContextHolder.getSecurityContext().getUserSession().getClientTimeOffsetInMinute();
- }catch(Exception ex){
-
- }
- }
- return clientTimeOffsetInMinute;
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/util/XAEnumUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/util/XAEnumUtil.java b/security-admin/src/main/java/com/xasecure/util/XAEnumUtil.java
deleted file mode 100644
index 7d0715d..0000000
--- a/security-admin/src/main/java/com/xasecure/util/XAEnumUtil.java
+++ /dev/null
@@ -1,2023 +0,0 @@
-/*
- * 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 com.xasecure.util;
-
-/**
- *
- */
-
-import java.util.*;
-import org.apache.log4j.Logger;
-import org.springframework.stereotype.Component;
-import com.xasecure.view.*;
-import com.xasecure.common.view.*;
-import com.xasecure.util.*;
-
-@Component
-public class XAEnumUtil {
-
- static final Logger logger = Logger.getLogger(XAEnumUtil.class);
- public final static String ENUM_CommonEnums_ActiveStatus = "CommonEnums.ActiveStatus";
- public final static String ENUM_CommonEnums_ActivationStatus = "CommonEnums.ActivationStatus";
- public final static String ENUM_CommonEnums_BooleanValue = "CommonEnums.BooleanValue";
- public final static String ENUM_CommonEnums_DataType = "CommonEnums.DataType";
- public final static String ENUM_CommonEnums_DeviceType = "CommonEnums.DeviceType";
- public final static String ENUM_CommonEnums_DiffLevel = "CommonEnums.DiffLevel";
- public final static String ENUM_CommonEnums_FileType = "CommonEnums.FileType";
- public final static String ENUM_CommonEnums_FreqType = "CommonEnums.FreqType";
- public final static String ENUM_CommonEnums_MimeType = "CommonEnums.MimeType";
- public final static String ENUM_CommonEnums_NumberFormat = "CommonEnums.NumberFormat";
- public final static String ENUM_CommonEnums_ObjectStatus = "CommonEnums.ObjectStatus";
- public final static String ENUM_CommonEnums_PasswordResetStatus = "CommonEnums.PasswordResetStatus";
- public final static String ENUM_CommonEnums_PriorityType = "CommonEnums.PriorityType";
- public final static String ENUM_CommonEnums_ProgressStatus = "CommonEnums.ProgressStatus";
- public final static String ENUM_CommonEnums_RelationType = "CommonEnums.RelationType";
- public final static String ENUM_CommonEnums_UserSource = "CommonEnums.UserSource";
- public final static String ENUM_CommonEnums_AssetType = "CommonEnums.AssetType";
- public final static String ENUM_CommonEnums_AccessResult = "CommonEnums.AccessResult";
- public final static String ENUM_CommonEnums_PolicyType = "CommonEnums.PolicyType";
- public final static String ENUM_CommonEnums_XAAuditType = "CommonEnums.XAAuditType";
- public final static String ENUM_CommonEnums_ResourceType = "CommonEnums.ResourceType";
- public final static String ENUM_CommonEnums_XAGroupType = "CommonEnums.XAGroupType";
- public final static String ENUM_CommonEnums_XAPermForType = "CommonEnums.XAPermForType";
- public final static String ENUM_CommonEnums_XAPermType = "CommonEnums.XAPermType";
- public final static String ENUM_CommonEnums_ClassTypes = "CommonEnums.ClassTypes";
- public final static String ENUM_XXAuthSession_AuthStatus = "XXAuthSession.AuthStatus";
- public final static String ENUM_XXAuthSession_AuthType = "XXAuthSession.AuthType";
- public final static String ENUM_XResponse_ResponseStatus = "XResponse.ResponseStatus";
-
- protected Hashtable<String, VEnum> enumMap = new Hashtable<String, VEnum>();
- protected List<VEnum> enumList = new ArrayList<VEnum>();
-
- public List<VEnum> getEnums() {
- if (enumList.size() == 0) {
- init();
- }
- return enumList;
- }
-
- public VEnum getEnum(String enumName) {
- if (enumList.size() == 0) {
- init();
- }
- return enumMap.get(enumName);
- }
-
- public String getLabel(String enumName, int enumValue) {
- VEnum vEnum = getEnum(enumName);
- if (vEnum == null) {
- logger.error("Enum " + enumName + " not found.", new Throwable());
- return "";
- }
- for (VEnumElement vEnumElement : vEnum.getElementList()) {
- if (vEnumElement.getElementValue() == enumValue) {
- return vEnumElement.getElementLabel();
- }
- }
- logger.error("Enum value not found. enum=" + enumName + ", value="
- + enumValue, new Throwable());
- return "";
- }
-
- public int getValue(String enumName, String elementName) {
- VEnum vEnum = getEnum(enumName);
- if (vEnum == null) {
- logger.error("Enum " + enumName + " not found.", new Throwable());
- return -1;
- }
- for (VEnumElement vEnumElement : vEnum.getElementList()) {
- if (vEnumElement.getElementName().equalsIgnoreCase(elementName)) {
- return vEnumElement.getElementValue();
- }
- }
- logger.error("Enum value not found. enum=" + enumName
- + ", elementName=" + elementName, new Throwable());
- return -1;
- }
-
- protected void init() {
- VEnum vEnum;
- VEnumElement vElement;
-
- ///////////////////////////////////
- // CommonEnums::ActiveStatus
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_ActiveStatus);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("STATUS_DISABLED");
- vElement.setElementValue(0);
- vElement.setElementLabel("Disabled");
- vElement.setRbKey("xa.enum.ActiveStatus.STATUS_DISABLED");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("STATUS_ENABLED");
- vElement.setElementValue(1);
- vElement.setElementLabel("Enabled");
- vElement.setRbKey("xa.enum.ActiveStatus.STATUS_ENABLED");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("STATUS_DELETED");
- vElement.setElementValue(2);
- vElement.setElementLabel("Deleted");
- vElement.setRbKey("xa.enum.ActiveStatus.STATUS_DELETED");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // CommonEnums::ActivationStatus
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_ActivationStatus);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("ACT_STATUS_DISABLED");
- vElement.setElementValue(0);
- vElement.setElementLabel("Disabled");
- vElement.setRbKey("xa.enum.ActivationStatus.ACT_STATUS_DISABLED");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("ACT_STATUS_ACTIVE");
- vElement.setElementValue(1);
- vElement.setElementLabel("Active");
- vElement.setRbKey("xa.enum.ActivationStatus.ACT_STATUS_ACTIVE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("ACT_STATUS_PENDING_APPROVAL");
- vElement.setElementValue(2);
- vElement.setElementLabel("Pending Approval");
- vElement.setRbKey("xa.enum.ActivationStatus.ACT_STATUS_PENDING_APPROVAL");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("ACT_STATUS_PENDING_ACTIVATION");
- vElement.setElementValue(3);
- vElement.setElementLabel("Pending Activation");
- vElement.setRbKey("xa.enum.ActivationStatus.ACT_STATUS_PENDING_ACTIVATION");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("ACT_STATUS_REJECTED");
- vElement.setElementValue(4);
- vElement.setElementLabel("Rejected");
- vElement.setRbKey("xa.enum.ActivationStatus.ACT_STATUS_REJECTED");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("ACT_STATUS_DEACTIVATED");
- vElement.setElementValue(5);
- vElement.setElementLabel("Deactivated");
- vElement.setRbKey("xa.enum.ActivationStatus.ACT_STATUS_DEACTIVATED");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("ACT_STATUS_PRE_REGISTRATION");
- vElement.setElementValue(6);
- vElement.setElementLabel("Registration Pending");
- vElement.setRbKey("xa.enum.ActivationStatus.ACT_STATUS_PRE_REGISTRATION");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("ACT_STATUS_NO_LOGIN");
- vElement.setElementValue(7);
- vElement.setElementLabel("No login privilege");
- vElement.setRbKey("xa.enum.ActivationStatus.ACT_STATUS_NO_LOGIN");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // CommonEnums::BooleanValue
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_BooleanValue);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("BOOL_NONE");
- vElement.setElementValue(0);
- vElement.setElementLabel("None");
- vElement.setRbKey("xa.enum.BooleanValue.BOOL_NONE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("BOOL_TRUE");
- vElement.setElementValue(1);
- vElement.setElementLabel("True");
- vElement.setRbKey("xa.enum.BooleanValue.BOOL_TRUE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("BOOL_FALSE");
- vElement.setElementValue(2);
- vElement.setElementLabel("False");
- vElement.setRbKey("xa.enum.BooleanValue.BOOL_FALSE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // CommonEnums::DataType
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_DataType);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("DATA_TYPE_UNKNOWN");
- vElement.setElementValue(0);
- vElement.setElementLabel("Unknown");
- vElement.setRbKey("xa.enum.DataType.DATA_TYPE_UNKNOWN");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("DATA_TYPE_INTEGER");
- vElement.setElementValue(1);
- vElement.setElementLabel("Integer");
- vElement.setRbKey("xa.enum.DataType.DATA_TYPE_INTEGER");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("DATA_TYPE_DOUBLE");
- vElement.setElementValue(2);
- vElement.setElementLabel("Double");
- vElement.setRbKey("xa.enum.DataType.DATA_TYPE_DOUBLE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("DATA_TYPE_STRING");
- vElement.setElementValue(3);
- vElement.setElementLabel("String");
- vElement.setRbKey("xa.enum.DataType.DATA_TYPE_STRING");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("DATA_TYPE_BOOLEAN");
- vElement.setElementValue(4);
- vElement.setElementLabel("Boolean");
- vElement.setRbKey("xa.enum.DataType.DATA_TYPE_BOOLEAN");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("DATA_TYPE_DATE");
- vElement.setElementValue(5);
- vElement.setElementLabel("Date");
- vElement.setRbKey("xa.enum.DataType.DATA_TYPE_DATE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("DATA_TYPE_STRING_ENUM");
- vElement.setElementValue(6);
- vElement.setElementLabel("String enumeration");
- vElement.setRbKey("xa.enum.DataType.DATA_TYPE_STRING_ENUM");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("DATA_TYPE_LONG");
- vElement.setElementValue(7);
- vElement.setElementLabel("Long");
- vElement.setRbKey("xa.enum.DataType.DATA_TYPE_LONG");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("DATA_TYPE_INTEGER_ENUM");
- vElement.setElementValue(8);
- vElement.setElementLabel("Integer enumeration");
- vElement.setRbKey("xa.enum.DataType.DATA_TYPE_INTEGER_ENUM");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // CommonEnums::DeviceType
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_DeviceType);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("DEVICE_UNKNOWN");
- vElement.setElementValue(0);
- vElement.setElementLabel("Unknown");
- vElement.setRbKey("xa.enum.DeviceType.DEVICE_UNKNOWN");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("DEVICE_BROWSER");
- vElement.setElementValue(1);
- vElement.setElementLabel("Browser");
- vElement.setRbKey("xa.enum.DeviceType.DEVICE_BROWSER");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("DEVICE_IPHONE");
- vElement.setElementValue(2);
- vElement.setElementLabel("iPhone");
- vElement.setRbKey("xa.enum.DeviceType.DEVICE_IPHONE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("DEVICE_IPAD");
- vElement.setElementValue(3);
- vElement.setElementLabel("iPad");
- vElement.setRbKey("xa.enum.DeviceType.DEVICE_IPAD");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("DEVICE_IPOD");
- vElement.setElementValue(4);
- vElement.setElementLabel("iPod");
- vElement.setRbKey("xa.enum.DeviceType.DEVICE_IPOD");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("DEVICE_ANDROID");
- vElement.setElementValue(5);
- vElement.setElementLabel("Android");
- vElement.setRbKey("xa.enum.DeviceType.DEVICE_ANDROID");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // CommonEnums::DiffLevel
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_DiffLevel);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("DIFF_UNKNOWN");
- vElement.setElementValue(0);
- vElement.setElementLabel("Unknown");
- vElement.setRbKey("xa.enum.DiffLevel.DIFF_UNKNOWN");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("DIFF_LOW");
- vElement.setElementValue(1);
- vElement.setElementLabel("Low");
- vElement.setRbKey("xa.enum.DiffLevel.DIFF_LOW");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("DIFF_MEDIUM");
- vElement.setElementValue(2);
- vElement.setElementLabel("Medium");
- vElement.setRbKey("xa.enum.DiffLevel.DIFF_MEDIUM");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("DIFF_HIGH");
- vElement.setElementValue(3);
- vElement.setElementLabel("High");
- vElement.setRbKey("xa.enum.DiffLevel.DIFF_HIGH");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // CommonEnums::FileType
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_FileType);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("FILE_FILE");
- vElement.setElementValue(0);
- vElement.setElementLabel("File");
- vElement.setRbKey("xa.enum.FileType.FILE_FILE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("FILE_DIR");
- vElement.setElementValue(1);
- vElement.setElementLabel("Directory");
- vElement.setRbKey("xa.enum.FileType.FILE_DIR");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // CommonEnums::FreqType
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_FreqType);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("FREQ_NONE");
- vElement.setElementValue(0);
- vElement.setElementLabel("None");
- vElement.setRbKey("xa.enum.FreqType.FREQ_NONE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("FREQ_MANUAL");
- vElement.setElementValue(1);
- vElement.setElementLabel("Manual");
- vElement.setRbKey("xa.enum.FreqType.FREQ_MANUAL");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("FREQ_HOURLY");
- vElement.setElementValue(2);
- vElement.setElementLabel("Hourly");
- vElement.setRbKey("xa.enum.FreqType.FREQ_HOURLY");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("FREQ_DAILY");
- vElement.setElementValue(3);
- vElement.setElementLabel("Daily");
- vElement.setRbKey("xa.enum.FreqType.FREQ_DAILY");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("FREQ_WEEKLY");
- vElement.setElementValue(4);
- vElement.setElementLabel("Weekly");
- vElement.setRbKey("xa.enum.FreqType.FREQ_WEEKLY");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("FREQ_BI_WEEKLY");
- vElement.setElementValue(5);
- vElement.setElementLabel("Bi Weekly");
- vElement.setRbKey("xa.enum.FreqType.FREQ_BI_WEEKLY");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("FREQ_MONTHLY");
- vElement.setElementValue(6);
- vElement.setElementLabel("Monthly");
- vElement.setRbKey("xa.enum.FreqType.FREQ_MONTHLY");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // CommonEnums::MimeType
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_MimeType);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("MIME_UNKNOWN");
- vElement.setElementValue(0);
- vElement.setElementLabel("Unknown");
- vElement.setRbKey("xa.enum.MimeType.MIME_UNKNOWN");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("MIME_TEXT");
- vElement.setElementValue(1);
- vElement.setElementLabel("Text");
- vElement.setRbKey("xa.enum.MimeType.MIME_TEXT");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("MIME_HTML");
- vElement.setElementValue(2);
- vElement.setElementLabel("Html");
- vElement.setRbKey("xa.enum.MimeType.MIME_HTML");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("MIME_PNG");
- vElement.setElementValue(3);
- vElement.setElementLabel("png");
- vElement.setRbKey("xa.enum.MimeType.MIME_PNG");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("MIME_JPEG");
- vElement.setElementValue(4);
- vElement.setElementLabel("jpeg");
- vElement.setRbKey("xa.enum.MimeType.MIME_JPEG");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // CommonEnums::NumberFormat
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_NumberFormat);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("NUM_FORMAT_NONE");
- vElement.setElementValue(0);
- vElement.setElementLabel("None");
- vElement.setRbKey("xa.enum.NumberFormat.NUM_FORMAT_NONE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("NUM_FORMAT_NUMERIC");
- vElement.setElementValue(1);
- vElement.setElementLabel("Numeric");
- vElement.setRbKey("xa.enum.NumberFormat.NUM_FORMAT_NUMERIC");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("NUM_FORMAT_ALPHA");
- vElement.setElementValue(2);
- vElement.setElementLabel("Alphabhet");
- vElement.setRbKey("xa.enum.NumberFormat.NUM_FORMAT_ALPHA");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("NUM_FORMAT_ROMAN");
- vElement.setElementValue(3);
- vElement.setElementLabel("Roman");
- vElement.setRbKey("xa.enum.NumberFormat.NUM_FORMAT_ROMAN");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // CommonEnums::ObjectStatus
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_ObjectStatus);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("OBJ_STATUS_ACTIVE");
- vElement.setElementValue(0);
- vElement.setElementLabel("Active");
- vElement.setRbKey("xa.enum.ObjectStatus.OBJ_STATUS_ACTIVE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("OBJ_STATUS_DELETED");
- vElement.setElementValue(1);
- vElement.setElementLabel("Deleted");
- vElement.setRbKey("xa.enum.ObjectStatus.OBJ_STATUS_DELETED");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("OBJ_STATUS_ARCHIVED");
- vElement.setElementValue(2);
- vElement.setElementLabel("Archived");
- vElement.setRbKey("xa.enum.ObjectStatus.OBJ_STATUS_ARCHIVED");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // CommonEnums::PasswordResetStatus
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_PasswordResetStatus);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("PWD_RESET_ACTIVE");
- vElement.setElementValue(0);
- vElement.setElementLabel("Active");
- vElement.setRbKey("xa.enum.PasswordResetStatus.PWD_RESET_ACTIVE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("PWD_RESET_USED");
- vElement.setElementValue(1);
- vElement.setElementLabel("Used");
- vElement.setRbKey("xa.enum.PasswordResetStatus.PWD_RESET_USED");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("PWD_RESET_EXPIRED");
- vElement.setElementValue(2);
- vElement.setElementLabel("Expired");
- vElement.setRbKey("xa.enum.PasswordResetStatus.PWD_RESET_EXPIRED");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("PWD_RESET_DISABLED");
- vElement.setElementValue(3);
- vElement.setElementLabel("Disabled");
- vElement.setRbKey("xa.enum.PasswordResetStatus.PWD_RESET_DISABLED");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // CommonEnums::PriorityType
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_PriorityType);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("PRIORITY_NORMAL");
- vElement.setElementValue(0);
- vElement.setElementLabel("Normal");
- vElement.setRbKey("xa.enum.PriorityType.PRIORITY_NORMAL");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("PRIORITY_LOW");
- vElement.setElementValue(1);
- vElement.setElementLabel("Low");
- vElement.setRbKey("xa.enum.PriorityType.PRIORITY_LOW");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("PRIORITY_MEDIUM");
- vElement.setElementValue(2);
- vElement.setElementLabel("Medium");
- vElement.setRbKey("xa.enum.PriorityType.PRIORITY_MEDIUM");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("PRIORITY_HIGH");
- vElement.setElementValue(3);
- vElement.setElementLabel("High");
- vElement.setRbKey("xa.enum.PriorityType.PRIORITY_HIGH");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // CommonEnums::ProgressStatus
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_ProgressStatus);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("PROGRESS_PENDING");
- vElement.setElementValue(0);
- vElement.setElementLabel("Pending");
- vElement.setRbKey("xa.enum.ProgressStatus.PROGRESS_PENDING");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("PROGRESS_IN_PROGRESS");
- vElement.setElementValue(1);
- vElement.setElementLabel("In Progress");
- vElement.setRbKey("xa.enum.ProgressStatus.PROGRESS_IN_PROGRESS");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("PROGRESS_COMPLETE");
- vElement.setElementValue(2);
- vElement.setElementLabel("Complete");
- vElement.setRbKey("xa.enum.ProgressStatus.PROGRESS_COMPLETE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("PROGRESS_ABORTED");
- vElement.setElementValue(3);
- vElement.setElementLabel("Aborted");
- vElement.setRbKey("xa.enum.ProgressStatus.PROGRESS_ABORTED");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("PROGRESS_FAILED");
- vElement.setElementValue(4);
- vElement.setElementLabel("Failed");
- vElement.setRbKey("xa.enum.ProgressStatus.PROGRESS_FAILED");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // CommonEnums::RelationType
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_RelationType);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("REL_NONE");
- vElement.setElementValue(0);
- vElement.setElementLabel("None");
- vElement.setRbKey("xa.enum.RelationType.REL_NONE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("REL_SELF");
- vElement.setElementValue(1);
- vElement.setElementLabel("Self");
- vElement.setRbKey("xa.enum.RelationType.REL_SELF");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // CommonEnums::UserSource
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_UserSource);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("USER_APP");
- vElement.setElementValue(0);
- vElement.setElementLabel("Application");
- vElement.setRbKey("xa.enum.UserSource.USER_APP");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("USER_GOOGLE");
- vElement.setElementValue(1);
- vElement.setElementLabel("Google");
- vElement.setRbKey("xa.enum.UserSource.USER_GOOGLE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("USER_FB");
- vElement.setElementValue(2);
- vElement.setElementLabel("FaceBook");
- vElement.setRbKey("xa.enum.UserSource.USER_FB");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // CommonEnums::AssetType
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_AssetType);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("ASSET_UNKNOWN");
- vElement.setElementValue(0);
- vElement.setElementLabel("Unknown");
- vElement.setRbKey("xa.enum.AssetType.ASSET_UNKNOWN");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("ASSET_HDFS");
- vElement.setElementValue(1);
- vElement.setElementLabel("HDFS");
- vElement.setRbKey("xa.enum.AssetType.ASSET_HDFS");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("ASSET_HBASE");
- vElement.setElementValue(2);
- vElement.setElementLabel("HBase");
- vElement.setRbKey("xa.enum.AssetType.ASSET_HBASE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("ASSET_HIVE");
- vElement.setElementValue(3);
- vElement.setElementLabel("Hive");
- vElement.setRbKey("xa.enum.AssetType.ASSET_HIVE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("ASSET_AGENT");
- vElement.setElementValue(4);
- vElement.setElementLabel("Agent");
- vElement.setRbKey("xa.enum.AssetType.ASSET_AGENT");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("ASSET_KNOX");
- vElement.setElementValue(5);
- vElement.setElementLabel("Knox");
- vElement.setRbKey("xa.enum.AssetType.ASSET_KNOX");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- vElement = new VEnumElement();
- vElement.setElementName("ASSET_STORM");
- vElement.setElementValue(6);
- vElement.setElementLabel("Storm");
- vElement.setRbKey("xa.enum.AssetType.ASSET_STORM");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
- ///////////////////////////////////
- // CommonEnums::AccessResult
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_AccessResult);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("ACCESS_RESULT_DENIED");
- vElement.setElementValue(0);
- vElement.setElementLabel("Denied");
- vElement.setRbKey("xa.enum.AccessResult.ACCESS_RESULT_DENIED");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("ACCESS_RESULT_ALLOWED");
- vElement.setElementValue(1);
- vElement.setElementLabel("Allowed");
- vElement.setRbKey("xa.enum.AccessResult.ACCESS_RESULT_ALLOWED");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // CommonEnums::PolicyType
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_PolicyType);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("POLICY_INCLUSION");
- vElement.setElementValue(0);
- vElement.setElementLabel("Inclusion");
- vElement.setRbKey("xa.enum.PolicyType.POLICY_INCLUSION");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("POLICY_EXCLUSION");
- vElement.setElementValue(1);
- vElement.setElementLabel("Exclusion");
- vElement.setRbKey("xa.enum.PolicyType.POLICY_EXCLUSION");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // CommonEnums::XAAuditType
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_XAAuditType);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_AUDIT_TYPE_UNKNOWN");
- vElement.setElementValue(0);
- vElement.setElementLabel("Unknown");
- vElement.setRbKey("xa.enum.XAAuditType.XA_AUDIT_TYPE_UNKNOWN");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_AUDIT_TYPE_ALL");
- vElement.setElementValue(1);
- vElement.setElementLabel("All");
- vElement.setRbKey("xa.enum.XAAuditType.XA_AUDIT_TYPE_ALL");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_AUDIT_TYPE_READ");
- vElement.setElementValue(2);
- vElement.setElementLabel("Read");
- vElement.setRbKey("xa.enum.XAAuditType.XA_AUDIT_TYPE_READ");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_AUDIT_TYPE_WRITE");
- vElement.setElementValue(3);
- vElement.setElementLabel("Write");
- vElement.setRbKey("xa.enum.XAAuditType.XA_AUDIT_TYPE_WRITE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_AUDIT_TYPE_CREATE");
- vElement.setElementValue(4);
- vElement.setElementLabel("Create");
- vElement.setRbKey("xa.enum.XAAuditType.XA_AUDIT_TYPE_CREATE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_AUDIT_TYPE_DELETE");
- vElement.setElementValue(5);
- vElement.setElementLabel("Delete");
- vElement.setRbKey("xa.enum.XAAuditType.XA_AUDIT_TYPE_DELETE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_AUDIT_TYPE_LOGIN");
- vElement.setElementValue(6);
- vElement.setElementLabel("Login");
- vElement.setRbKey("xa.enum.XAAuditType.XA_AUDIT_TYPE_LOGIN");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // CommonEnums::ResourceType
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_ResourceType);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("RESOURCE_UNKNOWN");
- vElement.setElementValue(0);
- vElement.setElementLabel("Unknown");
- vElement.setRbKey("xa.enum.ResourceType.RESOURCE_UNKNOWN");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("RESOURCE_PATH");
- vElement.setElementValue(1);
- vElement.setElementLabel("Path");
- vElement.setRbKey("xa.enum.ResourceType.RESOURCE_PATH");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("RESOURCE_DB");
- vElement.setElementValue(2);
- vElement.setElementLabel("Database");
- vElement.setRbKey("xa.enum.ResourceType.RESOURCE_DB");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("RESOURCE_TABLE");
- vElement.setElementValue(3);
- vElement.setElementLabel("Table");
- vElement.setRbKey("xa.enum.ResourceType.RESOURCE_TABLE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("RESOURCE_COL_FAM");
- vElement.setElementValue(4);
- vElement.setElementLabel("Column Family");
- vElement.setRbKey("xa.enum.ResourceType.RESOURCE_COL_FAM");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("RESOURCE_COLUMN");
- vElement.setElementValue(5);
- vElement.setElementLabel("Column");
- vElement.setRbKey("xa.enum.ResourceType.RESOURCE_COLUMN");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("RESOURCE_VIEW");
- vElement.setElementValue(6);
- vElement.setElementLabel("VIEW");
- vElement.setRbKey("xa.enum.ResourceType.RESOURCE_VIEW");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("RESOURCE_UDF");
- vElement.setElementValue(7);
- vElement.setElementLabel("UDF");
- vElement.setRbKey("xa.enum.ResourceType.RESOURCE_UDF");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("RESOURCE_VIEW_COL");
- vElement.setElementValue(8);
- vElement.setElementLabel("View Column");
- vElement.setRbKey("xa.enum.ResourceType.RESOURCE_VIEW_COL");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("RESOURCE_TOPOLOGY");
- vElement.setElementValue(9);
- vElement.setElementLabel("Topology");
- vElement.setRbKey("xa.enum.ResourceType.RESOURCE_TOPOLOGY");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("RESOURCE_SERVICE");
- vElement.setElementValue(10);
- vElement.setElementLabel("Service");
- vElement.setRbKey("xa.enum.ResourceType.RESOURCE_SERVICE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // CommonEnums::XAGroupType
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_XAGroupType);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_GROUP_UNKNOWN");
- vElement.setElementValue(0);
- vElement.setElementLabel("Unknown");
- vElement.setRbKey("xa.enum.XAGroupType.XA_GROUP_UNKNOWN");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_GROUP_USER");
- vElement.setElementValue(1);
- vElement.setElementLabel("User");
- vElement.setRbKey("xa.enum.XAGroupType.XA_GROUP_USER");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_GROUP_GROUP");
- vElement.setElementValue(2);
- vElement.setElementLabel("Group");
- vElement.setRbKey("xa.enum.XAGroupType.XA_GROUP_GROUP");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_GROUP_ROLE");
- vElement.setElementValue(3);
- vElement.setElementLabel("Role");
- vElement.setRbKey("xa.enum.XAGroupType.XA_GROUP_ROLE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // CommonEnums::XAPermForType
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_XAPermForType);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_FOR_UNKNOWN");
- vElement.setElementValue(0);
- vElement.setElementLabel("Unknown");
- vElement.setRbKey("xa.enum.XAPermForType.XA_PERM_FOR_UNKNOWN");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_FOR_USER");
- vElement.setElementValue(1);
- vElement.setElementLabel("Permission for Users");
- vElement.setRbKey("xa.enum.XAPermForType.XA_PERM_FOR_USER");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_FOR_GROUP");
- vElement.setElementValue(2);
- vElement.setElementLabel("Permission for Groups");
- vElement.setRbKey("xa.enum.XAPermForType.XA_PERM_FOR_GROUP");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // CommonEnums::XAPermType
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_XAPermType);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_UNKNOWN");
- vElement.setElementValue(0);
- vElement.setElementLabel("Unknown");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_UNKNOWN");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_RESET");
- vElement.setElementValue(1);
- vElement.setElementLabel("Reset");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_RESET");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_READ");
- vElement.setElementValue(2);
- vElement.setElementLabel("Read");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_READ");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_WRITE");
- vElement.setElementValue(3);
- vElement.setElementLabel("Write");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_WRITE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_CREATE");
- vElement.setElementValue(4);
- vElement.setElementLabel("Create");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_CREATE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_DELETE");
- vElement.setElementValue(5);
- vElement.setElementLabel("Delete");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_DELETE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_ADMIN");
- vElement.setElementValue(6);
- vElement.setElementLabel("Admin");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_ADMIN");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_OBFUSCATE");
- vElement.setElementValue(7);
- vElement.setElementLabel("Obfuscate");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_OBFUSCATE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_MASK");
- vElement.setElementValue(8);
- vElement.setElementLabel("Mask");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_MASK");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_EXECUTE");
- vElement.setElementValue(9);
- vElement.setElementLabel("Execute");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_EXECUTE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_SELECT");
- vElement.setElementValue(10);
- vElement.setElementLabel("Select");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_SELECT");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_UPDATE");
- vElement.setElementValue(11);
- vElement.setElementLabel("Update");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_UPDATE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_DROP");
- vElement.setElementValue(12);
- vElement.setElementLabel("Drop");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_DROP");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_ALTER");
- vElement.setElementValue(13);
- vElement.setElementLabel("Alter");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_ALTER");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_INDEX");
- vElement.setElementValue(14);
- vElement.setElementLabel("Index");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_INDEX");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_LOCK");
- vElement.setElementValue(15);
- vElement.setElementLabel("Lock");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_LOCK");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_ALL");
- vElement.setElementValue(16);
- vElement.setElementLabel("All");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_ALL");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_ALLOW");
- vElement.setElementValue(17);
- vElement.setElementLabel("Allow");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_ALLOW");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_SUBMIT_TOPOLOGY");
- vElement.setElementValue(18);
- vElement.setElementLabel("Submit Topology");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_SUBMIT_TOPOLOGY");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_FILE_UPLOAD");
- vElement.setElementValue(19);
- vElement.setElementLabel("File Upload");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_FILE_UPLOAD");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_GET_NIMBUS");
- vElement.setElementValue(20);
- vElement.setElementLabel("Get Nimbus Conf");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_GET_NIMBUS");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_GET_CLUSTER_INFO");
- vElement.setElementValue(21);
- vElement.setElementLabel("Get Cluster Info");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_GET_CLUSTER_INFO");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_FILE_DOWNLOAD");
- vElement.setElementValue(22);
- vElement.setElementLabel("File Download");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_FILE_DOWNLOAD");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_KILL_TOPOLOGY");
- vElement.setElementValue(23);
- vElement.setElementLabel("Kill Topology");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_KILL_TOPOLOGY");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_REBALANCE");
- vElement.setElementValue(24);
- vElement.setElementLabel("Rebalance");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_REBALANCE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_ACTIVATE");
- vElement.setElementValue(25);
- vElement.setElementLabel("Activate");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_ACTIVATE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_DEACTIVATE");
- vElement.setElementValue(26);
- vElement.setElementLabel("Deactivate");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_DEACTIVATE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_GET_TOPOLOGY_CONF");
- vElement.setElementValue(27);
- vElement.setElementLabel("Get Topology Conf");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_GET_TOPOLOGY_CONF");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_GET_TOPOLOGY");
- vElement.setElementValue(28);
- vElement.setElementLabel("Get Topology");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_GET_TOPOLOGY");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_GET_USER_TOPOLOGY");
- vElement.setElementValue(29);
- vElement.setElementLabel("Get User Topology");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_GET_USER_TOPOLOGY");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_GET_TOPOLOGY_INFO");
- vElement.setElementValue(30);
- vElement.setElementLabel("Get Topology Info");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_GET_TOPOLOGY_INFO");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("XA_PERM_TYPE_UPLOAD_NEW_CREDENTIAL");
- vElement.setElementValue(31);
- vElement.setElementLabel("Upload New Credential");
- vElement.setRbKey("xa.enum.XAPermType.XA_PERM_TYPE_UPLOAD_NEW_CREDENTIAL");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // CommonEnums::ClassTypes
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_CommonEnums_ClassTypes);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_NONE");
- vElement.setElementValue(0);
- vElement.setElementLabel("None");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_NONE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_MESSAGE");
- vElement.setElementValue(1);
- vElement.setElementLabel("Message");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_MESSAGE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_USER_PROFILE");
- vElement.setElementValue(2);
- vElement.setElementLabel("User Profile");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_USER_PROFILE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_AUTH_SESS");
- vElement.setElementValue(3);
- vElement.setElementLabel("Authentication Session");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_AUTH_SESS");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_DATA_OBJECT");
- vElement.setElementValue(4);
- vElement.setElementLabel("CLASS_TYPE_DATA_OBJECT");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_DATA_OBJECT");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_NAMEVALUE");
- vElement.setElementValue(5);
- vElement.setElementLabel("CLASS_TYPE_NAMEVALUE");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_NAMEVALUE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_LONG");
- vElement.setElementValue(6);
- vElement.setElementLabel("CLASS_TYPE_LONG");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_LONG");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_PASSWORD_CHANGE");
- vElement.setElementValue(7);
- vElement.setElementLabel("CLASS_TYPE_PASSWORD_CHANGE");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_PASSWORD_CHANGE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_STRING");
- vElement.setElementValue(8);
- vElement.setElementLabel("CLASS_TYPE_STRING");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_STRING");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_ENUM");
- vElement.setElementValue(9);
- vElement.setElementLabel("CLASS_TYPE_ENUM");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_ENUM");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_ENUM_ELEMENT");
- vElement.setElementValue(10);
- vElement.setElementLabel("CLASS_TYPE_ENUM_ELEMENT");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_ENUM_ELEMENT");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_RESPONSE");
- vElement.setElementValue(11);
- vElement.setElementLabel("Response");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_RESPONSE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_XA_ASSET");
- vElement.setElementValue(1000);
- vElement.setElementLabel("Asset");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_XA_ASSET");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_XA_RESOURCE");
- vElement.setElementValue(1001);
- vElement.setElementLabel("Resource");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_XA_RESOURCE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_XA_GROUP");
- vElement.setElementValue(1002);
- vElement.setElementLabel("XA Group");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_XA_GROUP");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_XA_USER");
- vElement.setElementValue(1003);
- vElement.setElementLabel("XA User");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_XA_USER");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_XA_GROUP_USER");
- vElement.setElementValue(1004);
- vElement.setElementLabel("XA Group of Users");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_XA_GROUP_USER");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_XA_GROUP_GROUP");
- vElement.setElementValue(1005);
- vElement.setElementLabel("XA Group of groups");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_XA_GROUP_GROUP");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_XA_PERM_MAP");
- vElement.setElementValue(1006);
- vElement.setElementLabel("XA permissions for resource");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_XA_PERM_MAP");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_XA_AUDIT_MAP");
- vElement.setElementValue(1007);
- vElement.setElementLabel("XA audits for resource");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_XA_AUDIT_MAP");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_XA_CRED_STORE");
- vElement.setElementValue(1008);
- vElement.setElementLabel("XA credential store");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_XA_CRED_STORE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_XA_POLICY_EXPORT_AUDIT");
- vElement.setElementValue(1009);
- vElement.setElementLabel("XA Policy Export Audit");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_XA_POLICY_EXPORT_AUDIT");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_TRX_LOG");
- vElement.setElementValue(1010);
- vElement.setElementLabel("Transaction log");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_TRX_LOG");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_XA_ACCESS_AUDIT");
- vElement.setElementValue(1011);
- vElement.setElementLabel("Access Audit");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_XA_ACCESS_AUDIT");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("CLASS_TYPE_XA_TRANSACTION_LOG_ATTRIBUTE");
- vElement.setElementValue(1012);
- vElement.setElementLabel("Transaction log attribute");
- vElement.setRbKey("xa.enum.ClassTypes.CLASS_TYPE_XA_TRANSACTION_LOG_ATTRIBUTE");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // XXAuthSession::AuthStatus
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_XXAuthSession_AuthStatus);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("AUTH_STATUS_UNKNOWN");
- vElement.setElementValue(0);
- vElement.setElementLabel("Unknown");
- vElement.setRbKey("xa.enum.AuthStatus.AUTH_STATUS_UNKNOWN");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("AUTH_STATUS_SUCCESS");
- vElement.setElementValue(1);
- vElement.setElementLabel("Success");
- vElement.setRbKey("xa.enum.AuthStatus.AUTH_STATUS_SUCCESS");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("AUTH_STATUS_WRONG_PASSWORD");
- vElement.setElementValue(2);
- vElement.setElementLabel("Wrong Password");
- vElement.setRbKey("xa.enum.AuthStatus.AUTH_STATUS_WRONG_PASSWORD");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("AUTH_STATUS_DISABLED");
- vElement.setElementValue(3);
- vElement.setElementLabel("Account Disabled");
- vElement.setRbKey("xa.enum.AuthStatus.AUTH_STATUS_DISABLED");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("AUTH_STATUS_LOCKED");
- vElement.setElementValue(4);
- vElement.setElementLabel("Locked");
- vElement.setRbKey("xa.enum.AuthStatus.AUTH_STATUS_LOCKED");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("AUTH_STATUS_PASSWORD_EXPIRED");
- vElement.setElementValue(5);
- vElement.setElementLabel("Password Expired");
- vElement.setRbKey("xa.enum.AuthStatus.AUTH_STATUS_PASSWORD_EXPIRED");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("AUTH_STATUS_USER_NOT_FOUND");
- vElement.setElementValue(6);
- vElement.setElementLabel("User not found");
- vElement.setRbKey("xa.enum.AuthStatus.AUTH_STATUS_USER_NOT_FOUND");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // XXAuthSession::AuthType
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_XXAuthSession_AuthType);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("AUTH_TYPE_UNKNOWN");
- vElement.setElementValue(0);
- vElement.setElementLabel("Unknown");
- vElement.setRbKey("xa.enum.AuthType.AUTH_TYPE_UNKNOWN");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("AUTH_TYPE_PASSWORD");
- vElement.setElementValue(1);
- vElement.setElementLabel("Username/Password");
- vElement.setRbKey("xa.enum.AuthType.AUTH_TYPE_PASSWORD");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- ///////////////////////////////////
- // XResponse::ResponseStatus
- ///////////////////////////////////
- vEnum = new VEnum();
- vEnum.setEnumName(ENUM_XResponse_ResponseStatus);
- vEnum.setElementList(new ArrayList<VEnumElement>());
- enumList.add(vEnum);
- enumMap.put(vEnum.getEnumName(), vEnum);
-
- vElement = new VEnumElement();
- vElement.setElementName("STATUS_SUCCESS");
- vElement.setElementValue(0);
- vElement.setElementLabel("Success");
- vElement.setRbKey("xa.enum.ResponseStatus.STATUS_SUCCESS");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("STATUS_ERROR");
- vElement.setElementValue(1);
- vElement.setElementLabel("Error");
- vElement.setRbKey("xa.enum.ResponseStatus.STATUS_ERROR");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("STATUS_VALIDATION");
- vElement.setElementValue(2);
- vElement.setElementLabel("Validation Error");
- vElement.setRbKey("xa.enum.ResponseStatus.STATUS_VALIDATION");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("STATUS_WARN");
- vElement.setElementValue(3);
- vElement.setElementLabel("Warning");
- vElement.setRbKey("xa.enum.ResponseStatus.STATUS_WARN");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("STATUS_INFO");
- vElement.setElementValue(4);
- vElement.setElementLabel("Information");
- vElement.setRbKey("xa.enum.ResponseStatus.STATUS_INFO");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
- vElement = new VEnumElement();
- vElement.setElementName("STATUS_PARTIAL_SUCCESS");
- vElement.setElementValue(5);
- vElement.setElementLabel("Partial Success");
- vElement.setRbKey("xa.enum.ResponseStatus.STATUS_PARTIAL_SUCCESS");
- vElement.setEnumName(vEnum.getEnumName());
-
- vEnum.getElementList().add(vElement);
-
-
- }
-
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/util/XARestUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/util/XARestUtil.java b/security-admin/src/main/java/com/xasecure/util/XARestUtil.java
deleted file mode 100644
index f174846..0000000
--- a/security-admin/src/main/java/com/xasecure/util/XARestUtil.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * 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 com.xasecure.util;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import com.xasecure.common.XAConfigUtil;
-import com.xasecure.common.MessageEnums;
-import com.xasecure.common.RESTErrorUtil;
-import com.xasecure.common.StringUtil;
-import com.xasecure.entity.XXPortalUser;
-import com.xasecure.view.VXMessage;
-import com.xasecure.view.VXResponse;
-import com.xasecure.view.VXPortalUser;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-@Component
-public class XARestUtil {
- static final Logger logger = Logger.getLogger(XARestUtil.class);
-
- @Autowired
- StringUtil stringUtil;
-
- @Autowired
- RESTErrorUtil restErrorUtil;
-
- @Autowired
- XAConfigUtil configUtil;
-
- void splitUserRoleList(Collection<String> collection) {
- Collection<String> newCollection = new ArrayList<String>();
- for (String role : collection) {
- String roles[] = role.split(",");
- for (int i = 0; i < roles.length; i++) {
- String str = roles[i];
- newCollection.add(str);
- }
- }
- collection.clear();
- collection.addAll(newCollection);
- }
-
- /**
- * This method cleans up the data provided by the user for update
- *
- * @param userProfile
- * @return
- */
- public void validateVUserProfileForUpdate(XXPortalUser gjUser,
- VXPortalUser userProfile) {
-
- List<VXMessage> messageList = new ArrayList<VXMessage>();
-
- // Email Update is allowed.
- // if (userProfile.getEmailAddress() != null
- // && !userProfile.getEmailAddress().equalsIgnoreCase(
- // gjUser.getEmailAddress())) {
- // throw restErrorUtil.createRESTException(
- // "Email address can't be updated",
- // MessageEnums.DATA_NOT_UPDATABLE, null, "emailAddress",
- // userProfile.getEmailAddress());
- // }
-
- // Login Id can't be changed
- if (userProfile.getLoginId() != null
- && !gjUser.getLoginId().equalsIgnoreCase(
- userProfile.getLoginId())) {
- throw restErrorUtil.createRESTException(
- "Username can't be updated",
- MessageEnums.DATA_NOT_UPDATABLE, null, "loginId",
- userProfile.getLoginId());
- }
- // }
- userProfile.setFirstName(restErrorUtil.validateStringForUpdate(
- userProfile.getFirstName(), gjUser.getFirstName(),
- StringUtil.VALIDATION_NAME, "Invalid first name",
- MessageEnums.INVALID_INPUT_DATA, null, "firstName"));
-
- userProfile.setFirstName(restErrorUtil.validateStringForUpdate(
- userProfile.getFirstName(), gjUser.getFirstName(),
- StringUtil.VALIDATION_NAME, "Invalid first name",
- MessageEnums.INVALID_INPUT_DATA, null, "firstName"));
-
- userProfile.setLastName(restErrorUtil.validateStringForUpdate(
- userProfile.getLastName(), gjUser.getLastName(),
- StringUtil.VALIDATION_NAME, "Invalid last name",
- MessageEnums.INVALID_INPUT_DATA, null, "lastName"));
-
- // firstName
- if (!stringUtil.isValidName(userProfile.getFirstName())) {
- logger.info("Invalid first name." + userProfile);
- messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null,
- "firstName"));
- }
-
- // lastName
- if (!stringUtil.isValidName(userProfile.getLastName())) {
- logger.info("Invalid last name." + userProfile);
- messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null,
- "lastName"));
- }
-
- // create the public screen name
- userProfile.setPublicScreenName(userProfile.getFirstName() + " "
- + userProfile.getLastName());
-
- userProfile.setNotes(restErrorUtil.validateStringForUpdate(
- userProfile.getNotes(), gjUser.getNotes(),
- StringUtil.VALIDATION_NAME, "Invalid notes",
- MessageEnums.INVALID_INPUT_DATA, null, "notes"));
-
- // validate user roles
- if (userProfile.getUserRoleList() != null) {
- // First let's normalize it
- splitUserRoleList(userProfile.getUserRoleList());
- for (String userRole : userProfile.getUserRoleList()) {
- restErrorUtil.validateStringList(userRole,
- configUtil.getRoles(), "Invalid role", null,
- "userRoleList");
- }
-
- }
- if (messageList.size() > 0) {
- VXResponse gjResponse = new VXResponse();
- gjResponse.setStatusCode(VXResponse.STATUS_ERROR);
- gjResponse.setMsgDesc("Validation failure");
- gjResponse.setMessageList(messageList);
- logger.info("Validation Error in updateUser() userProfile="
- + userProfile + ", error=" + gjResponse);
- throw restErrorUtil.createRESTException(gjResponse);
- }
-
- }
-
-}
\ No newline at end of file
[39/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/knox/URLBasedAuthDB.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/knox/URLBasedAuthDB.java b/agents-impl/src/main/java/org/apache/ranger/pdp/knox/URLBasedAuthDB.java
new file mode 100644
index 0000000..d5aa16e
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/knox/URLBasedAuthDB.java
@@ -0,0 +1,452 @@
+/**
+ * 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.pdp.knox;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.authorization.hadoop.config.RangerConfiguration;
+import org.apache.ranger.pdp.config.Jersey2PolicyRefresher;
+import org.apache.ranger.pdp.config.PolicyChangeListener;
+import org.apache.ranger.pdp.constants.RangerConstants;
+import org.apache.ranger.pdp.model.Policy;
+import org.apache.ranger.pdp.model.PolicyContainer;
+import org.apache.ranger.pdp.model.RolePermission;
+
+public class URLBasedAuthDB implements PolicyChangeListener {
+
+ private static final Log LOG = LogFactory.getLog(URLBasedAuthDB.class) ;
+
+ private static URLBasedAuthDB me = null;
+
+ private Jersey2PolicyRefresher refresher = null ;
+
+ private PolicyContainer policyContainer = null;
+
+ private HashMap<String,Boolean> cachedAuditFlag = new HashMap<String,Boolean>() ; // needs to be cleaned when ruleList changes
+
+ public static URLBasedAuthDB getInstance() {
+ if (me == null) {
+ synchronized (URLBasedAuthDB.class) {
+ URLBasedAuthDB temp = me;
+ if (temp == null) {
+ me = new URLBasedAuthDB();
+ me.init() ;
+ }
+ }
+ }
+ return me;
+ }
+
+ public static URLBasedAuthDB getInstanceWithBackEndMocked() {
+ return new URLBasedAuthDB("instanceWithBackednMocked");
+ }
+
+ private URLBasedAuthDB() {
+ String url = RangerConfiguration.getInstance().get(RangerConstants.RANGER_KNOX_POLICYMGR_URL_PROP);
+ long refreshInMilli = RangerConfiguration.getInstance().getLong(
+ RangerConstants.RANGER_KNOX_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_PROP ,
+ RangerConstants.RANGER_KNOX_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_DEFAULT);
+ String sslConfigFileName = RangerConfiguration.getInstance().get(RangerConstants.RANGER_KNOX_POLICYMGR_SSL_CONFIG_FILE_PROP) ;
+
+ String lastStoredFileName = RangerConfiguration.getInstance().get(RangerConstants.RANGER_KNOX_LAST_SAVED_POLICY_FILE_PROP) ;
+
+ refresher = new Jersey2PolicyRefresher(url, refreshInMilli,sslConfigFileName,lastStoredFileName) ;
+
+ String saveAsFileName = RangerConfiguration.getInstance().get(RangerConstants.RANGER_KNOX_POLICYMGR_URL_SAVE_FILE_PROP) ;
+ if (saveAsFileName != null) {
+ refresher.setSaveAsFileName(saveAsFileName) ;
+ }
+
+ if (lastStoredFileName != null) {
+ refresher.setLastStoredFileName(lastStoredFileName);
+ }
+ }
+
+ private URLBasedAuthDB(String mockName) {
+ }
+
+ private void init() {
+ refresher.setPolicyChangeListener(this);
+ }
+
+
+ @Override
+ public void OnPolicyChange(PolicyContainer aPolicyContainer) {
+ setPolicyContainer(aPolicyContainer);
+ }
+
+
+ public boolean isAccessGranted(String topology, String service, String access, String userName, Set<String> groups,
+ String requestIp) {
+
+ boolean accessGranted = false;
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Evaluating access for topology: " + topology +
+ ", service: " + service +
+ ", access: " + access +
+ ", requestingIp: " +requestIp +
+ ", requestingUser: " + userName +
+ ", requestingUserGroups: " + groups);
+ }
+ PolicyContainer policyContainer = getPolicyContainer() ;
+
+ if (policyContainer == null) {
+ LOG.warn("Denying access: policyContainer is null") ;
+ return false ;
+ }
+
+ for(Policy policy : policyContainer.getAcl()) {
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Evaluating policy: " + policy.toString() ) ;
+ }
+
+ if (!policy.isEnabled()) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Skipping policy: " + policy + ", policy disabled") ;
+ }
+ continue; // jump to next policy
+ }
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Evaluating topology match for policyTopologyList: " + policy.getTopologyList() +
+ ", requestTopology: " + topology) ;
+ }
+
+ boolean topologyMatched = false;
+
+ List<String> topologyList = policy.getTopologyList();
+ if (topologyList == null || topologyList.isEmpty()) {
+ LOG.debug("Denying access: policy topologyList is empty") ;
+ continue; // jump to next policy
+ }
+
+ if (topologyList.contains("*") || topologyList.contains(topology)) {
+ topologyMatched = true;
+ LOG.debug("Policy topologyList matches requested topology");
+ }
+
+ if (!topologyMatched) {
+ for (String policyTopology : topologyList) {
+ if (FilenameUtils.wildcardMatch(topology, policyTopology)) {
+ topologyMatched = true;
+ LOG.debug("Policy topologyList matches requested topology");
+ break; // break out of topologyList
+ }
+ }
+ }
+ if (!topologyMatched) {
+ LOG.debug("Denying access: policy topologyList does not match requested topology") ;
+ continue; // jump to next policy
+ } else {
+ LOG.debug("policy topologyList matches requested topology");
+ }
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Evaluating service match for policyServiceList: " + policy.getServiceList() +
+ ", requestService: " + service) ;
+ }
+
+ boolean serviceMatched = false;
+
+ List<String> serviceList = policy.getServiceList();
+ if (serviceList == null || serviceList.isEmpty()) {
+ LOG.debug("Denying access: policy serviceList is empty") ;
+ continue; // jump to next policy
+ }
+
+ if (serviceList.contains("*") || serviceList.contains(service)) {
+ serviceMatched = true;
+ LOG.debug("Policy serviceList matches requested service");
+ }
+
+ if (!serviceMatched) {
+ for (String policyService : serviceList) {
+ if (FilenameUtils.wildcardMatch(service, policyService)) {
+ serviceMatched = true;
+ LOG.debug("Policy serviceList matches requested service");
+ break; // break out of serviceList
+ }
+ }
+ }
+ if (!serviceMatched) {
+ LOG.debug("Denying access: policy serviceList does not match requested service") ;
+ continue; // jump to next policy
+ } else {
+ LOG.debug("Policy serviceList matches requested service");
+ }
+
+ LOG.debug("Checking accessType, IP, User, Group based permission");
+ if ( policy.getPermissions() == null
+ || policy.getPermissions().isEmpty()) {
+ LOG.debug("Policy not applicable, no user or group based permission");
+ }
+
+ for (RolePermission rp : policy.getPermissions()) {
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Evaluating RolePermission: " + rp);
+ }
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Checking accessTypeMatch for rolePermissionAccesType: "
+ + rp.getAccess() + ", requestAccessType: " + access);
+ }
+
+ if (rp.getAccess().contains(access)) {
+
+ LOG.debug("RolePermission accessType matches request accessType");
+
+ boolean ipMatched = false;
+ List<String> ipList = rp.getIpAddress();
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Checking ipMatch for rolePermissionIpList: " + ipList +
+ ", requestIP: " + requestIp);
+ }
+
+ if (ipList == null || ipList.isEmpty()) {
+ LOG.debug("RolePermission does not require IP Matching");
+ ipMatched = true;
+ } else if ( ipList.contains("*") ) {
+ LOG.debug("RolePermission allows any IP: *");
+ ipMatched = true;
+ } else {
+ for (String ip : ipList) {
+ if (ipMatches(ip, requestIp)) {
+ LOG.debug("RolePermission IP matches request IP");
+ ipMatched = true;
+ break;// break out of ipList
+ }
+ }
+ }
+
+ if (!ipMatched) {
+ // ip not matched, jump to next RolePermission check
+ LOG.debug("Request IP does not match RolePermission");
+ continue; // jump to next rolePermission
+ } else {
+ LOG.debug("Request IP matches RolePermission");
+ }
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Checking userMatch for rolePermissionUsers: "
+ + rp.getUsers() + ", requestUser: " + userName);
+ }
+
+ if ( rp.getUsers() != null && rp.getUsers().contains(userName) ) {
+ LOG.debug("Request user matches RolePermission");
+ return true ;
+ }
+ LOG.debug("RolePermission does not permit request by request user, would check by groups");
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Checking groupMatch for rolePermissionGroups: "
+ + rp.getGroups() + ", requestGroups: " + groups);
+ }
+
+ for(String ug : groups) {
+ if ( rp.getGroups() != null && rp.getGroups().contains(ug)) {
+ LOG.debug("Request userGroups matches RolePermission");
+ return true ;
+ }
+ }
+ LOG.debug("RolePermission does not permit request by request user groups");
+
+ if (rp.getGroups().contains(RangerConstants.PUBLIC_ACCESS_ROLE)) {
+ LOG.debug("RolePermission applies to public group");
+ return true ;
+ }
+
+ LOG.debug("RolePermission does not permit by users, groups or public group");
+ } else {
+ LOG.debug("rolePermissionAccessType does not match requestAccessType");
+ }
+ }
+ }
+ LOG.debug("No matching policy permission found, denying access");
+ return accessGranted;
+ }
+
+ public boolean isAuditEnabled(String topology, String service) {
+
+ boolean auditEnabled = false;
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Checcking whether audit is enabled for topology: " + topology +
+ ", service: " + service );
+ }
+
+ PolicyContainer policyContainer = getPolicyContainer() ;
+ if (policyContainer == null) {
+ LOG.warn("PolicyContainer is null") ;
+ return false ;
+ }
+
+ for(Policy policy : policyContainer.getAcl()) {
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Evaluating policy: " + policy) ;
+ }
+
+ if (!policy.isEnabled()) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Skipping policy: " + policy + ", policy disabled") ;
+ }
+ continue; // jump to next policy
+ }
+
+ if (policy.getAuditInd() == 0) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Skipping policy: " + policy + ", policy audit disabled") ;
+ }
+ continue; // jump to next policy
+ }
+
+ boolean topologyMatched = false;
+
+ List<String> topologyList = policy.getTopologyList();
+ if (topologyList == null || topologyList.isEmpty()) {
+ LOG.debug("Policy not applicable: policy topologyList is empty") ;
+ continue; // jump to next policy
+ }
+
+ if (topologyList.contains("*") || topologyList.contains(topology)) {
+ topologyMatched = true;
+ LOG.debug("Policy topologyList matches requested topology");
+ }
+
+ if (!topologyMatched) {
+ for (String policyTopology : topologyList) {
+ if (FilenameUtils.wildcardMatch(topology, policyTopology)) {
+ topologyMatched = true;
+ LOG.debug("Policy topologyList matches requested topology");
+ break; // break out of topologyList check
+ }
+ }
+ }
+ if (!topologyMatched) {
+ LOG.debug("Policy not applicable: polocy topologyList does not match requested topology") ;
+ continue; // jump to next policy
+ } else {
+ LOG.debug("Policy topologyList matches requested topology");
+ }
+
+ boolean serviceMatched = false;
+
+ List<String> serviceList = policy.getServiceList();
+ if (serviceList == null || serviceList.isEmpty()) {
+ LOG.debug("Policy not applicable: serviceList is empty") ;
+ continue; // jump to next policy
+ }
+
+ if (serviceList.contains("*") || serviceList.contains(service)) {
+ serviceMatched = true;
+ LOG.debug("Policy serviceList matches requested service");
+ }
+
+ if (!serviceMatched) {
+ for (String policyService : serviceList) {
+ if (FilenameUtils.wildcardMatch(service, policyService)) {
+ serviceMatched = true;
+ LOG.debug("Policy serviceList matches requested service");
+ break; // break out of serviceList check
+ }
+ }
+ }
+ if (!serviceMatched) {
+ LOG.debug("Policy not applicable: policy serviceList does not match requested service") ;
+ continue; // jump to next policy
+ } else {
+ LOG.debug("Policy serviceList matches requested service");
+ }
+ auditEnabled = true;;
+ break; // break out of policyList check
+ }
+ return auditEnabled;
+ }
+
+ public PolicyContainer getPolicyContainer() {
+ return policyContainer;
+ }
+
+
+ synchronized void setPolicyContainer(PolicyContainer aPolicyContainer) {
+
+ for(Policy p : aPolicyContainer.getAcl()) {
+ for(RolePermission rp : p.getPermissions()) {
+ // lowercase accesType value stings
+ List<String> rpaccess = rp.getAccess() ;
+ if (rpaccess != null && rpaccess.size() > 0) {
+ List<String> temp = new ArrayList<String>() ;
+ for(String s : rpaccess) {
+ temp.add(s.toLowerCase()) ;
+ }
+ rp.setAccess(temp);
+ }
+ }
+ }
+
+ this.policyContainer = aPolicyContainer ;
+ this.cachedAuditFlag.clear();
+ }
+
+
+ private boolean ipMatches(String policyIp, String requestIp) {
+ if (policyIp == null) {
+ return false;
+ }
+ policyIp = policyIp.trim();
+ if (policyIp.isEmpty()) {
+ return false;
+ }
+ boolean ipMatched = false;
+ boolean wildEnd = false;
+ if (policyIp.contains(".")) {
+ while (policyIp.endsWith(".*")) {
+ wildEnd = true;
+ policyIp = policyIp.substring(0, policyIp.lastIndexOf(".*"));
+ }
+ if (wildEnd) {
+ policyIp = policyIp + ".";
+ }
+ } else if (policyIp.contains(":")) {
+ while (policyIp.endsWith(":*")) {
+ wildEnd = true;
+ policyIp = policyIp.substring(0, policyIp.lastIndexOf(":*"));
+ }
+ if (wildEnd) {
+ policyIp = policyIp + ":";
+ }
+ }
+ if (wildEnd && requestIp.toLowerCase().startsWith(policyIp.toLowerCase())) {
+ ipMatched = true;
+ } else if (policyIp.equalsIgnoreCase(requestIp)) {
+ ipMatched = true;
+ }
+ return ipMatched;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/knox/deploy/RangerPDPKnoxDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/knox/deploy/RangerPDPKnoxDeploymentContributor.java b/agents-impl/src/main/java/org/apache/ranger/pdp/knox/deploy/RangerPDPKnoxDeploymentContributor.java
new file mode 100644
index 0000000..a70224f
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/knox/deploy/RangerPDPKnoxDeploymentContributor.java
@@ -0,0 +1,73 @@
+/**
+ * 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.pdp.knox.deploy;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.hadoop.gateway.deploy.DeploymentContext;
+import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributorBase;
+import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
+import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
+import org.apache.hadoop.gateway.topology.Provider;
+import org.apache.hadoop.gateway.topology.Service;
+
+public class RangerPDPKnoxDeploymentContributor extends ProviderDeploymentContributorBase {
+
+ private static final String FILTER_CLASSNAME = "org.apache.ranger.pdp.knox.filter.RangerPDPKnoxFilter";
+
+ @Override
+ public String getRole() {
+ return "authorization";
+ }
+
+ @Override
+ public String getName() {
+ return "XASecurePDPKnox";
+ }
+
+ @Override
+ public void initializeContribution(DeploymentContext context) {
+ super.initializeContribution(context);
+ }
+
+ @Override
+ public void contributeProvider( DeploymentContext context, Provider provider ) {
+ }
+
+ @Override
+ public void contributeFilter( DeploymentContext context, Provider provider, Service service,
+ ResourceDescriptor resource, List<FilterParamDescriptor> params ) {
+ if (params == null) {
+ params = new ArrayList<FilterParamDescriptor>();
+ }
+ // add resource role to params so that we can determine the acls to enforce at runtime
+ params.add( resource.createFilterParam().name( "resource.role" ).value(resource.role() ) );
+
+ // blindly add all the provider params as filter init params
+ // this will include any {resource.role}-ACLS parameters to be enforced - such as NAMENODE-ACLS
+ Map<String, String> providerParams = provider.getParams();
+ for(Entry<String, String> entry : providerParams.entrySet()) {
+ params.add( resource.createFilterParam().name( entry.getKey().toLowerCase() ).value( entry.getValue() ) );
+ }
+
+ resource.addFilter().name( getName() ).role( getRole() ).impl( FILTER_CLASSNAME ).params( params );
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/knox/filter/RangerPDPKnoxFilter.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/knox/filter/RangerPDPKnoxFilter.java b/agents-impl/src/main/java/org/apache/ranger/pdp/knox/filter/RangerPDPKnoxFilter.java
new file mode 100644
index 0000000..7eb498e
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/knox/filter/RangerPDPKnoxFilter.java
@@ -0,0 +1,214 @@
+/**
+ * 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.pdp.knox.filter;
+
+import java.io.IOException;
+import java.security.AccessController;
+import java.security.Principal;
+import java.util.HashSet;
+import java.util.Set;
+
+import javax.security.auth.Subject;
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.gateway.filter.AbstractGatewayFilter;
+import org.apache.hadoop.gateway.security.GroupPrincipal;
+import org.apache.hadoop.gateway.security.ImpersonatedPrincipal;
+import org.apache.hadoop.gateway.security.PrimaryPrincipal;
+import org.apache.ranger.audit.model.EnumRepositoryType;
+import org.apache.ranger.audit.model.KnoxAuditEvent;
+import org.apache.ranger.audit.provider.AuditProvider;
+import org.apache.ranger.audit.provider.AuditProviderFactory;
+import org.apache.ranger.authorization.hadoop.config.RangerConfiguration;
+import org.apache.ranger.authorization.hadoop.constants.RangerHadoopConstants;
+import org.apache.ranger.authorization.knox.KnoxAccessVerifier;
+import org.apache.ranger.authorization.knox.KnoxAccessVerifierFactory;
+import org.apache.ranger.authorization.utils.StringUtil;
+
+public class RangerPDPKnoxFilter implements Filter {
+
+ private static final Log LOG = LogFactory.getLog(RangerPDPKnoxFilter.class);
+ private static final String ACL_ENFORCER = "xasecure-acl";
+ private static final String PERM_ALLOW = "allow";
+ private String resourceRole = null;
+ private KnoxAccessVerifier knoxAccessVerifier;
+
+
+ AuditProvider auditProvider = AuditProviderFactory.getAuditProvider();
+ private final String REPOSITORY_NAME = RangerConfiguration.getInstance().get(RangerHadoopConstants.AUDITLOG_REPOSITORY_NAME_PROP);
+
+ static {
+ RangerConfiguration.getInstance().initAudit(AuditProviderFactory.ApplicationType.Knox);
+ }
+
+ @Override
+ public void init(FilterConfig filterConfig) throws ServletException {
+ resourceRole = getInitParameter(filterConfig, "resource.role");
+ knoxAccessVerifier = KnoxAccessVerifierFactory.getInstance();
+ }
+
+ private String getInitParameter(FilterConfig filterConfig, String paramName) {
+ return filterConfig.getInitParameter(paramName.toLowerCase());
+ }
+
+ public void destroy() {
+ }
+
+ public void doFilter(ServletRequest request, ServletResponse response,
+ FilterChain chain) throws IOException, ServletException {
+
+ String sourceUrl = (String) request
+ .getAttribute(AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME);
+ String topologyName = getTopologyName(sourceUrl);
+ String serviceName = getServiceName();
+
+ Subject subject = Subject.getSubject(AccessController.getContext());
+
+ Principal primaryPrincipal = (Principal) subject.getPrincipals(
+ PrimaryPrincipal.class).toArray()[0];
+ String primaryUser = primaryPrincipal.getName();
+
+ String impersonatedUser = null;
+ Object[] impersonations = subject.getPrincipals(
+ ImpersonatedPrincipal.class).toArray();
+ if (impersonations != null && impersonations.length > 0) {
+ impersonatedUser = ((Principal) impersonations[0]).getName();
+ }
+
+ String user = (impersonatedUser != null) ? impersonatedUser
+ : primaryUser;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Checking access primaryUser: " + primaryUser + ", impersonatedUser: "
+ + impersonatedUser + ", effectiveUser: " + user);
+ }
+
+ Object[] groupObjects = subject.getPrincipals(GroupPrincipal.class)
+ .toArray();
+ Set<String> groups = new HashSet<String>();
+ for (Object obj : groupObjects) {
+ groups.add(((Principal) obj).getName());
+ }
+
+ String clientIp = request.getRemoteAddr();
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Checking access primaryUser: " + primaryUser + ", impersonatedUser: "
+ + impersonatedUser + ", effectiveUser: " + user +
+ ", groups: " + groups + ", clientIp: " + clientIp);
+ }
+ boolean accessAllowed = knoxAccessVerifier.isAccessAllowed(
+ topologyName, serviceName, PERM_ALLOW, user, groups, clientIp);
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Access allowed: " + accessAllowed);
+ }
+ if (accessAllowed) {
+ chain.doFilter(request, response);
+ if (knoxAccessVerifier.isAuditEnabled(topologyName, serviceName)) {
+ LOG.debug("Audit is enabled");
+ logAuditEvent(user, clientIp, topologyName, serviceName,
+ "allow", true);
+ } else {
+ LOG.debug("Audit is not enabled");
+ }
+ } else {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Access is denied");
+ }
+ if (knoxAccessVerifier.isAuditEnabled(topologyName, serviceName)) {
+ LOG.debug("Audit is enabled");
+ logAuditEvent(user, clientIp, topologyName, serviceName,
+ "allow", false);
+ } else {
+ LOG.debug("Audit is not enabled");
+ }
+ sendForbidden((HttpServletResponse) response);
+ }
+ }
+
+ private void sendForbidden(HttpServletResponse res) {
+ sendErrorCode(res, 403);
+ }
+
+ private void sendErrorCode(HttpServletResponse res, int code) {
+ try {
+ res.sendError(code);
+ } catch (IOException e) {
+ LOG.error("Error while redireting:", e);
+ }
+ }
+
+ private String getTopologyName(String requestUrl) {
+ if (requestUrl == null) {
+ return null;
+ }
+ String url = requestUrl.trim();
+ String[] tokens = url.split("/");
+ if (tokens.length > 2) {
+ return tokens[2];
+ } else {
+ return null;
+ }
+ }
+
+ private String getServiceName() {
+ return resourceRole;
+ }
+
+ private void logAuditEvent(String userName, String clientIp,
+ String topology, String service,
+ String accessType, boolean accessGranted) {
+
+ KnoxAuditEvent auditEvent = new KnoxAuditEvent();
+
+ auditEvent.setUser(userName == null ?
+ RangerHadoopConstants.AUDITLOG_EMPTY_STRING : userName);
+ auditEvent.setResourcePath("/" + topology + "/" + service);
+ auditEvent.setResourceType("service");
+ auditEvent.setAccessType(accessType);
+ auditEvent.setClientIP(clientIp);
+ auditEvent.setEventTime(StringUtil.getUTCDate());
+ auditEvent.setAccessResult((short) (accessGranted ? 1 : 0));
+ auditEvent.setResultReason(null);
+ auditEvent.setRepositoryType(EnumRepositoryType.KNOX);
+ auditEvent.setRepositoryName(REPOSITORY_NAME);
+ auditEvent.setAclEnforcer(ACL_ENFORCER);
+
+ try {
+ LOG.debug("logEvent [" + auditEvent + "] - START");
+
+ AuditProvider ap = AuditProviderFactory.getAuditProvider();
+ ap.log(auditEvent);
+
+ LOG.debug("logEvent [" + auditEvent + "] - END");
+ } catch (Throwable t) {
+ LOG.error("ERROR logEvent [" + auditEvent + "]", t);
+ }
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/model/Policy.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/model/Policy.java b/agents-impl/src/main/java/org/apache/ranger/pdp/model/Policy.java
new file mode 100644
index 0000000..46ca26b
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/model/Policy.java
@@ -0,0 +1,326 @@
+/*
+ * 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.pdp.model;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.ranger.pdp.config.gson.ExcludeSerialization;
+
+import com.google.gson.annotations.SerializedName;
+
+public class Policy {
+
+ public static final String RESOURCE_SPLITER = "," ;
+ public static final String POLICY_ENABLED_STATUS = "Enabled" ;
+ public static final String SELECTION_TYPE_INCLUSIVE = "Inclusion" ;
+ public static final String SELECTION_TYPE_EXCLUSIVE = "Exclusion" ;
+
+ //
+ // Only for HDFS policies
+ //
+ private String resource ;
+ @SerializedName("isRecursive")
+ private int recursiveInd;
+
+ // Only for Knox Policies
+ //
+
+ @SerializedName("topology_name")
+ private String topologies ;
+
+ @SerializedName("service_name")
+ private String services ;
+
+
+ //
+ // Only for Hive Policies
+ //
+
+ @SerializedName("database_name")
+ private String databases ;
+
+ @SerializedName("table_name")
+ private String tables ;
+
+ @SerializedName("udf_name")
+ private String udfs ;
+
+ @SerializedName("column_name")
+ private String columns ;
+
+ @SerializedName("column_families")
+ private String columnfamilies ;
+
+ //
+ // Neede for all Policies
+ //
+ @SerializedName("permission")
+ private List<RolePermission> permissions ;
+
+ @SerializedName("audit")
+ private int auditInd ;
+
+ @SerializedName("encrypt")
+ private int encryptInd ;
+
+ @SerializedName("policyStatus")
+ private String policyStatus;
+
+ @SerializedName("tablePolicyType")
+ private String tableSelectionType ;
+
+ @SerializedName("columnPolicyType")
+ private String columnSelectionType ;
+
+ // Derived fields for PolicyAnalysis
+ @ExcludeSerialization
+ private List<ResourcePath> resourceList ;
+ @ExcludeSerialization
+ private List<String> databaseList ;
+ @ExcludeSerialization
+ private List<String> tableList ;
+ @ExcludeSerialization
+ private List<String> udfList ;
+ @ExcludeSerialization
+ private List<String> columnList ;
+ @ExcludeSerialization
+ private List<String> columnFamilyList ;
+ @ExcludeSerialization
+ private List<String> topologyList ;
+ @ExcludeSerialization
+ private List<String> serviceList ;
+
+ public Policy() {
+ permissions = new ArrayList<RolePermission>() ;
+ }
+
+
+ public String getResource() {
+ return resource;
+ }
+
+ public void setResource(String resource) {
+ this.resource = resource;
+ }
+
+ public String getDatabases() {
+ return databases;
+ }
+
+ public void setDatabases(String databases) {
+ this.databases = databases;
+ }
+
+ public String getTables() {
+ return tables;
+ }
+
+ public void setTables(String tables) {
+ this.tables = tables;
+ }
+
+ public String gettopologies() {
+ return topologies;
+ }
+
+ public void setTopologies(String topologies) {
+ this.topologies = topologies;
+ }
+
+ public String getServices() {
+ return services;
+ }
+
+ public void setServices(String services) {
+ this.services = services;
+ }
+ public String getUdfs() {
+ return udfs;
+ }
+
+ public void setUdfs(String udfs) {
+ this.udfs = udfs;
+ }
+
+
+ public String getColumns() {
+ return columns;
+ }
+ public void setColumns(String columns) {
+ this.columns = columns;
+ }
+ public String getColumnfamilies() {
+ return columnfamilies;
+ }
+ public void setColumnfamilies(String columnfamilies) {
+ this.columnfamilies = columnfamilies;
+ }
+
+ public List<RolePermission> getPermissions() {
+ return permissions;
+ }
+ public void setPermissions(List<RolePermission> permissions) {
+ this.permissions = permissions;
+ }
+
+ public int getRecursiveInd() {
+ return recursiveInd;
+ }
+ public void setRecursiveInd(int recursiveInd) {
+ this.recursiveInd = recursiveInd;
+ }
+
+ public int getAuditInd() {
+ return auditInd;
+ }
+
+
+ public void setAuditInd(int auditInd) {
+ this.auditInd = auditInd;
+ }
+
+
+ public int getEncryptInd() {
+ return encryptInd;
+ }
+
+
+ public void setEncryptInd(int encryptInd) {
+ this.encryptInd = encryptInd;
+ }
+
+ public String getPolicyStatus() {
+ return policyStatus;
+ }
+
+
+ public void setPolicyStatus(String policyStatus) {
+ this.policyStatus = policyStatus;
+ }
+
+ public String getTableSelectionType() {
+ return tableSelectionType;
+ }
+
+
+ public void setTableSelectionType(String tableSelectionType) {
+ this.tableSelectionType = tableSelectionType;
+ }
+
+
+ public String getColumnSelectionType() {
+ return columnSelectionType;
+ }
+
+
+ public void setColumnSelectionType(String columnSelectionType) {
+ this.columnSelectionType = columnSelectionType;
+ }
+
+ public boolean isTableSelectionExcluded() {
+ return (this.tableSelectionType != null && SELECTION_TYPE_EXCLUSIVE.equalsIgnoreCase(this.tableSelectionType)) ;
+ }
+
+ public boolean isColumnSelectionExcluded() {
+ return (this.columnSelectionType != null && SELECTION_TYPE_EXCLUSIVE.equalsIgnoreCase(this.columnSelectionType)) ;
+ }
+
+
+ // An older version of policy manager would show policyStatus as NULL (considered that as Enabled)
+ public boolean isEnabled() {
+ return (this.policyStatus == null || POLICY_ENABLED_STATUS.equalsIgnoreCase(this.policyStatus)) ;
+ }
+
+ public List<ResourcePath> getResourceList() {
+ if (this.resourceList == null) {
+ this.resourceList = getResourceList(resource) ;
+ }
+ return this.resourceList;
+ }
+ public List<String> getDatabaseList() {
+ if (this.databaseList == null) {
+ this.databaseList = getList(this.databases) ;
+ }
+ return this.databaseList;
+ }
+ public List<String> getTableList() {
+ if (this.tableList == null) {
+ this.tableList = getList(this.tables) ;
+ }
+ return this.tableList;
+ }
+ public List<String> getColumnList() {
+ if (this.columnList == null) {
+ this.columnList = getList(this.columns) ;
+ }
+ return this.columnList;
+ }
+ public List<String> getColumnFamilyList() {
+ if (this.columnFamilyList == null) {
+ this.columnFamilyList = getList(this.columnfamilies) ;
+ }
+ return this.columnFamilyList;
+ }
+ public List<String> getUDFList() {
+ if (this.udfList == null && this.udfList != null) {
+ this.udfList = getList(this.udfs) ;
+ }
+ return this.udfList;
+ }
+
+ public List<String> getTopologyList() {
+ if (this.topologyList == null) {
+ this.topologyList = getList(this.topologies) ;
+ }
+ return this.topologyList;
+ }
+
+ public List<String> getServiceList() {
+ if (this.serviceList == null) {
+ this.serviceList = getList(this.services) ;
+ }
+ return this.serviceList;
+ }
+
+
+ private List<String> getList(String resource) {
+ List<String> ret = new ArrayList<String>() ;
+ if (resource == null || resource.trim().isEmpty()) {
+ resource = "*" ;
+ }
+ for(String r : resource.split(RESOURCE_SPLITER)) {
+ ret.add(r) ;
+ }
+
+ return ret;
+ }
+
+ private List<ResourcePath> getResourceList(String resource) {
+ List<ResourcePath> ret = new ArrayList<ResourcePath>() ;
+ if (resource != null && ! resource.isEmpty()) {
+ for(String path : resource.split(RESOURCE_SPLITER)) {
+ ret.add(new ResourcePath(path)) ;
+ }
+ }
+ return ret ;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/model/PolicyContainer.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/model/PolicyContainer.java b/agents-impl/src/main/java/org/apache/ranger/pdp/model/PolicyContainer.java
new file mode 100644
index 0000000..3674102
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/model/PolicyContainer.java
@@ -0,0 +1,55 @@
+/*
+ * 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.pdp.model;
+
+import java.util.List;
+
+import com.google.gson.annotations.SerializedName;
+
+public class PolicyContainer {
+
+ @SerializedName("repository_name")
+ private String repositoryName ;
+
+ @SerializedName("last_updated")
+ private long lastUpdatedTimeInEpoc ;
+
+ @SerializedName("acl")
+ private List<Policy> acl;
+
+ public String getRepositoryName() {
+ return repositoryName;
+ }
+ public void setRepositoryName(String repositoryName) {
+ this.repositoryName = repositoryName;
+ }
+ public long getLastUpdatedTimeInEpoc() {
+ return lastUpdatedTimeInEpoc;
+ }
+ public void setLastUpdatedTimeInEpoc(long lastUpdatedTimeInEpoc) {
+ this.lastUpdatedTimeInEpoc = lastUpdatedTimeInEpoc;
+ }
+ public List<Policy> getAcl() {
+ return acl;
+ }
+ public void setAcl(List<Policy> acl) {
+ this.acl = acl;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/model/ResourcePath.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/model/ResourcePath.java b/agents-impl/src/main/java/org/apache/ranger/pdp/model/ResourcePath.java
new file mode 100644
index 0000000..fa32ed8
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/model/ResourcePath.java
@@ -0,0 +1,43 @@
+/*
+ * 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.pdp.model;
+
+public class ResourcePath {
+
+ String path ;
+ boolean wildcardPath ;
+
+ public ResourcePath(String path) {
+ this.path = path ;
+ if (this.path.contains("*") || this.path.contains("?")) {
+ this.wildcardPath = true ;
+ }
+ }
+
+ public String getPath() {
+ return path;
+ }
+
+ public boolean isWildcardPath() {
+ return wildcardPath;
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/model/RolePermission.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/model/RolePermission.java b/agents-impl/src/main/java/org/apache/ranger/pdp/model/RolePermission.java
new file mode 100644
index 0000000..accee6c
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/model/RolePermission.java
@@ -0,0 +1,71 @@
+/*
+ * 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.pdp.model;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class RolePermission {
+
+ private List<String> users ;
+ private List<String> groups ;
+ private List<String> access ;
+ private List<String> ipAddress ;
+
+ public RolePermission() {
+ users = new ArrayList<String>() ;
+ groups = new ArrayList<String>() ;
+ access = new ArrayList<String>() ;
+ }
+
+
+ public List<String> getUsers() {
+ return users;
+ }
+
+ public void setUsers(List<String> users) {
+ this.users = users;
+ }
+
+ public List<String> getGroups() {
+ return groups;
+ }
+
+ public void setGroups(List<String> groups) {
+ this.groups = groups;
+ }
+
+ public List<String> getAccess() {
+ return this.access;
+ }
+
+ public List<String> getIpAddress() {
+ return this.ipAddress;
+ }
+
+ public void setIpAddress(List<String> ipAddress) {
+ this.ipAddress = ipAddress ;
+ }
+
+ public void setAccess(List<String> access) {
+ this.access = access ;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/storm/RangerAuthorizer.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/storm/RangerAuthorizer.java b/agents-impl/src/main/java/org/apache/ranger/pdp/storm/RangerAuthorizer.java
new file mode 100644
index 0000000..f7d3b0f
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/storm/RangerAuthorizer.java
@@ -0,0 +1,61 @@
+/*
+ * 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.pdp.storm;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.authorization.storm.RangerStormAccessVerifier;
+
+public class RangerAuthorizer implements RangerStormAccessVerifier {
+
+ private static final Log LOG = LogFactory.getLog(RangerAuthorizer.class) ;
+
+ private static URLBasedAuthDB authDB = URLBasedAuthDB.getInstance() ;
+
+
+ @Override
+ public boolean isAccessAllowed(String aUserName, String[] aGroupName, String aOperationName, String aTopologyName) {
+ boolean ret = false ;
+
+ if (authDB != null) {
+ ret = authDB.isAccessAllowed(aUserName, aGroupName, aOperationName, aTopologyName) ;
+ }
+ else {
+ LOG.error("Unable to find a URLBasedAuthDB for authorization - Found null");
+ }
+
+ return ret ;
+ }
+
+ @Override
+ public boolean isAudited(String aTopologyName) {
+ boolean ret = false ;
+
+ if (authDB != null) {
+ ret = authDB.isAudited(aTopologyName) ;
+ }
+ else {
+ LOG.error("Unable to find a URLBasedAuthDB for authorization - Found null");
+ }
+
+ return ret ;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/storm/StormAuthRule.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/storm/StormAuthRule.java b/agents-impl/src/main/java/org/apache/ranger/pdp/storm/StormAuthRule.java
new file mode 100644
index 0000000..f655839
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/storm/StormAuthRule.java
@@ -0,0 +1,136 @@
+/*
+ * 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.pdp.storm;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.io.FilenameUtils;
+import org.apache.ranger.authorization.utils.StringUtil;
+
+public class StormAuthRule {
+ private String topologyName ;
+ private List<String> accessTypeList ;
+ private List<String> groupList ;
+ private List<String> userList;
+ private boolean auditEnabled ;
+
+
+ public StormAuthRule(String topologyName, List<String> accessTypeList,
+ List<String> userList, List<String> groupList, boolean auditEnabled) {
+ super();
+ this.topologyName = topologyName;
+ this.accessTypeList = accessTypeList;
+ if (this.accessTypeList == null) {
+ this.accessTypeList = new ArrayList<String>();
+ }
+ this.userList = userList;
+ if (this.userList == null) {
+ this.userList = new ArrayList<String>();
+ }
+
+ this.groupList = groupList;
+ if (this.groupList == null) {
+ this.groupList = new ArrayList<String>();
+ }
+
+ this.auditEnabled = auditEnabled ;
+ }
+
+ public String getTopologyName() {
+ return topologyName;
+ }
+ public void setTopologyName(String topologyName) {
+ this.topologyName = topologyName;
+ }
+ public List<String> getAccessTypeList() {
+ return accessTypeList;
+ }
+ public void setAccessTypeList(List<String> accessTypeList) {
+ this.accessTypeList = accessTypeList;
+ }
+ public List<String> getGroupList() {
+ return groupList;
+ }
+ public void setGroupList(List<String> groupList) {
+ this.groupList = groupList;
+ }
+ public List<String> getUserList() {
+ return userList;
+ }
+ public void setUserList(List<String> userList) {
+ this.userList = userList;
+ }
+
+ public boolean isMatchedTopology(String aTopologyName) {
+
+ boolean ret = false ;
+
+ if (aTopologyName == null || aTopologyName.length() == 0) {
+ ret = "*".equals(this.topologyName) ;
+ }
+ else {
+ ret = (aTopologyName.equals(this.topologyName) || FilenameUtils.wildcardMatch(aTopologyName,this.topologyName)) ;
+ }
+ return ret ;
+ }
+
+ public boolean isOperationAllowed(String aOperationName) {
+ return this.accessTypeList.contains(aOperationName);
+ }
+
+ private static final String PUBLIC_GROUP_NAME = "public" ;
+
+ public boolean isUserAllowed(String aUserName, String[] aGroupList) {
+
+ boolean accessAllowed = false ;
+
+ if ( this.userList.contains(aUserName) ) {
+ accessAllowed = true ;
+ }
+ else if (this.groupList.contains(PUBLIC_GROUP_NAME)) {
+ accessAllowed = true ;
+ }
+ else if (aGroupList != null ) {
+ for(String userGroup : aGroupList ) {
+ if (this.groupList.contains(userGroup) ) {
+ accessAllowed = true ;
+ break ;
+ }
+ }
+ }
+
+ return accessAllowed ;
+ }
+
+ public boolean getAuditEnabled() {
+ return this.auditEnabled ;
+ }
+
+ @Override
+ public String toString() {
+ return "StormAuthRule: { topologyName: [" + topologyName + "]," +
+ "userList: [" + StringUtil.toString(userList) + "]" +
+ "groupList: [" + StringUtil.toString(groupList) + "]" +
+ "accessTypeList: [" + StringUtil.toString(accessTypeList) + "]" +
+ "auditEnabled: [" + auditEnabled + "] }";
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/storm/URLBasedAuthDB.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/storm/URLBasedAuthDB.java b/agents-impl/src/main/java/org/apache/ranger/pdp/storm/URLBasedAuthDB.java
new file mode 100644
index 0000000..1977fb2
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/storm/URLBasedAuthDB.java
@@ -0,0 +1,176 @@
+/*
+ * 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.pdp.storm;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.ranger.authorization.hadoop.config.RangerConfiguration;
+import org.apache.ranger.authorization.storm.RangerStormAccessVerifier;
+import org.apache.ranger.pdp.config.PolicyChangeListener;
+import org.apache.ranger.pdp.config.PolicyRefresher;
+import org.apache.ranger.pdp.constants.RangerConstants;
+import org.apache.ranger.pdp.model.Policy;
+import org.apache.ranger.pdp.model.PolicyContainer;
+import org.apache.ranger.pdp.model.RolePermission;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+public class URLBasedAuthDB implements PolicyChangeListener, RangerStormAccessVerifier {
+
+ private static final Logger LOG = LoggerFactory.getLogger(URLBasedAuthDB.class) ;
+
+ private static URLBasedAuthDB me = null;
+
+ private PolicyRefresher refresher = null ;
+
+ private PolicyContainer policyContainer = null;
+
+ private List<StormAuthRule> stormAuthDB = null ;
+
+ public static URLBasedAuthDB getInstance() {
+ if (me == null) {
+ synchronized (URLBasedAuthDB.class) {
+ URLBasedAuthDB temp = me;
+ if (temp == null) {
+ me = new URLBasedAuthDB();
+ me.init() ;
+ }
+ }
+ }
+ return me;
+ }
+
+ private URLBasedAuthDB() {
+
+ String url = RangerConfiguration.getInstance().get(RangerConstants.RANGER_STORM_POLICYMGR_URL_PROP);
+
+ long refreshInMilli = RangerConfiguration.getInstance().getLong(
+ RangerConstants.RANGER_STORM_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_PROP ,
+ RangerConstants.RANGER_STORM_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_DEFAULT);
+
+ String lastStoredFileName = RangerConfiguration.getInstance().get(RangerConstants.RANGER_STORM_LAST_SAVED_POLICY_FILE_PROP) ;
+
+ String sslConfigFileName = RangerConfiguration.getInstance().get(RangerConstants.RANGER_STORM_POLICYMGR_SSL_CONFIG_FILE_PROP) ;
+
+ refresher = new PolicyRefresher(url, refreshInMilli,sslConfigFileName,lastStoredFileName) ;
+
+ String saveAsFileName = RangerConfiguration.getInstance().get(RangerConstants.RANGER_STORM_POLICYMGR_URL_SAVE_FILE_PROP) ;
+ if (saveAsFileName != null) {
+ refresher.setSaveAsFileName(saveAsFileName) ;
+ }
+
+ if (lastStoredFileName != null) {
+ refresher.setLastStoredFileName(lastStoredFileName);
+ }
+ }
+
+
+ private void init() {
+ refresher.setPolicyChangeListener(this);
+ }
+
+
+ @Override
+ public void OnPolicyChange(PolicyContainer aPolicyContainer) {
+ setPolicyContainer(aPolicyContainer);
+ }
+
+
+ public PolicyContainer getPolicyContainer() {
+ return policyContainer;
+ }
+
+
+
+ public synchronized void setPolicyContainer(PolicyContainer aPolicyContainer) {
+
+ if (aPolicyContainer != null) {
+
+ List<StormAuthRule> tempStormAuthDB = new ArrayList<StormAuthRule>() ;
+
+ for(Policy p : aPolicyContainer.getAcl()) {
+
+ if (! p.isEnabled()) {
+ continue;
+ }
+
+ for (String topologyName : p.getTopologyList()) {
+
+ List<RolePermission> rpList = p.getPermissions() ;
+
+ for(RolePermission rp : rpList) {
+ StormAuthRule rule = new StormAuthRule(topologyName, rp.getAccess() , rp.getUsers(), rp.getGroups(), (p.getAuditInd() == 1)) ;
+ tempStormAuthDB.add(rule) ;
+ }
+ }
+ }
+
+ this.stormAuthDB = tempStormAuthDB ;
+
+ this.policyContainer = aPolicyContainer ;
+ }
+ }
+
+ @Override
+ public boolean isAccessAllowed(String aUserName, String[] aGroupName, String aOperationName, String aTopologyName) {
+
+ boolean accessAllowed = false ;
+
+ List<StormAuthRule> tempStormAuthDB = this.stormAuthDB ;
+
+ if (tempStormAuthDB != null) {
+ for(StormAuthRule rule : tempStormAuthDB) {
+ if (rule.isMatchedTopology(aTopologyName)) {
+ if (rule.isOperationAllowed(aOperationName)) {
+ if (rule.isUserAllowed(aUserName, aGroupName)) {
+ accessAllowed = true ;
+ break ;
+ }
+ }
+ }
+ }
+ }
+
+ return accessAllowed ;
+ }
+
+ @Override
+ public boolean isAudited(String aTopologyName) {
+ boolean auditEnabled = false ;
+
+ List<StormAuthRule> tempStormAuthDB = stormAuthDB ;
+
+ if (tempStormAuthDB != null) {
+ for(StormAuthRule rule : tempStormAuthDB) {
+ if (rule.isMatchedTopology(aTopologyName)) {
+ auditEnabled = rule.getAuditEnabled() ;
+ if (auditEnabled) {
+ break ;
+ }
+ }
+ }
+ }
+
+ return auditEnabled ;
+ }
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/org/apache/ranger/pdp/utils/RangerUtils.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/org/apache/ranger/pdp/utils/RangerUtils.java b/agents-impl/src/main/java/org/apache/ranger/pdp/utils/RangerUtils.java
new file mode 100644
index 0000000..27e7dee
--- /dev/null
+++ b/agents-impl/src/main/java/org/apache/ranger/pdp/utils/RangerUtils.java
@@ -0,0 +1,49 @@
+/*
+ * 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.pdp.utils;
+
+import java.io.File;
+import java.net.URL;
+
+public class RangerUtils {
+
+ public static String getFilePathFromClassPath(String aFileName) {
+ String pathName = null;
+
+ File lf = new File(aFileName) ;
+
+ if (lf.exists()) {
+ pathName = lf.getAbsolutePath();
+ }
+ else {
+ URL lurl = RangerUtils.class.getResource(aFileName);
+ if (lurl == null) {
+ if (!aFileName.startsWith("/")) {
+ lurl = RangerUtils.class.getResource("/" + aFileName);
+ }
+ }
+ if (lurl != null) {
+ pathName = lurl.getFile();
+ }
+ }
+ return pathName;
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor b/agents-impl/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
index 44483f0..6db0bdc 100644
--- a/agents-impl/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
+++ b/agents-impl/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
@@ -15,4 +15,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
##########################################################################
-com.xasecure.pdp.knox.deploy.XASecurePDPKnoxDeploymentContributor
+org.apache.ranger.pdp.knox.deploy.RangerPDPKnoxDeploymentContributor
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/test/java/com/xasecure/pdp/hdfs/PolicyCacheStoreTest.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/test/java/com/xasecure/pdp/hdfs/PolicyCacheStoreTest.java b/agents-impl/src/test/java/com/xasecure/pdp/hdfs/PolicyCacheStoreTest.java
deleted file mode 100644
index 2b1b508..0000000
--- a/agents-impl/src/test/java/com/xasecure/pdp/hdfs/PolicyCacheStoreTest.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * 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 com.xasecure.pdp.hdfs;
-
-import java.io.BufferedReader;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.junit.Before;
-import org.junit.After;
-import org.junit.Test;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.xasecure.pdp.config.ConfigWatcher;
-import com.xasecure.pdp.config.PolicyRefresher;
-import com.xasecure.pdp.model.Policy;
-import com.xasecure.pdp.model.PolicyContainer;
-import com.xasecure.pdp.model.RolePermission;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
-
-public class PolicyCacheStoreTest {
- URLBasedAuthDB authDB = null;
- ConfigWatcher watcherDaemon = null;
- PolicyRefresher pr = null;
- PolicyContainer policyContainer=null;
- String url=null;
- String sslConfigFileName=null;
- String lastStoredFileName=null;
- Long refreshInterval =0L;
- private static final Log LOG = LogFactory.getLog(PolicyCacheStoreTest.class);
- @Before
- public void setup(){
- authDB = URLBasedAuthDB.getInstance();
-
- }
-
- @After
- public void teardown(){
- authDB = null;
- PolicyRefresher pr = null;
- }
-
- @Test
- public void testHdfsPolicyCacheStore(){
- //Check if the policy cache gets created when agent get created;
- url="dummyurl";
- refreshInterval=10L;
- sslConfigFileName = "dummyConfigFileName.xml";
- lastStoredFileName = System.getProperty("user.home") +"/"+ "haooopPolicyCache.json";
- policyContainer = buildPolicyContainer(
- "/demo/data",
- 1,
- asList("allow"),
- asList("guest"),
- asList("sales"),
- null, // ipAddress
- true, // policyEnabled
- true); // auditEnabled
- authDB.OnPolicyChange(policyContainer);
- pr = spy(new PolicyRefresher(url,refreshInterval,sslConfigFileName,lastStoredFileName));
- pr.setPolicyContainer(policyContainer);
- pr.setPolicyChangeListener(authDB);
- PolicyContainer newPr = readPolicyCache(lastStoredFileName);
- assertEquals(policyToString(policyContainer),policyToString(newPr));
- }
-
- private static PolicyContainer buildPolicyContainer(String resource,
- int recursiveInd, List<String> accessTypes, List<String> users,
- List<String> groups, List<String> ipAddresses,
- boolean policyEnabled, boolean auditEnabled) {
-
- PolicyContainer policyContainer = new PolicyContainer();
- policyContainer.setRepositoryName("hadoopdev");
-
- List<Policy> policies = new ArrayList<Policy>();
-
- Policy policy = new Policy();
- policy.setResource(resource);
- policy.setRecursiveInd(recursiveInd);
- policy.setPolicyStatus(policyEnabled ? "Enabled" : "NotEnabled");
- policy.setAuditInd(auditEnabled ? 1 : 0);
-
- List<RolePermission> rolePermissions = new ArrayList<RolePermission>();
-
- RolePermission rolePermission = new RolePermission();
-
- rolePermissions.add(rolePermission);
- rolePermission.setAccess(accessTypes);
- rolePermission.setUsers(users);
- rolePermission.setGroups(groups);
- rolePermission.setIpAddress(ipAddresses);
-
- policy.setPermissions(rolePermissions);
-
- policies.add(policy);
-
- policyContainer.setAcl(policies);
-
- return policyContainer;
- }
-
- private static Set<String> asSet(String... a) {
- Set<String> vals = new HashSet<String>();
- for (String s : a) {
- vals.add(s);
- }
- return vals;
- }
-
- private static List<String> asList(String... a) {
- List<String> vals = new ArrayList<String>();
- for (String s : a) {
- vals.add(s);
- }
- return vals;
- }
-
-
- private PolicyContainer readPolicyCache(String lastStoreFileName) {
- BufferedReader jsonString = null;
- try {
- jsonString = new BufferedReader(new FileReader(lastStoredFileName));
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- Gson gson = new GsonBuilder().create();
- PolicyContainer newPolicyContainer = gson.fromJson(jsonString, PolicyContainer.class);
- return newPolicyContainer;
- }
-
- private String policyToString(PolicyContainer pc) {
- Gson gson = new GsonBuilder().create() ;
- String policyAsJson = gson.toJson(policyContainer) ;
- return policyAsJson;
- }
-
-
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/test/java/com/xasecure/pdp/hdfs/URLBasedAuthDBTest.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/test/java/com/xasecure/pdp/hdfs/URLBasedAuthDBTest.java b/agents-impl/src/test/java/com/xasecure/pdp/hdfs/URLBasedAuthDBTest.java
deleted file mode 100644
index 4a19d98..0000000
--- a/agents-impl/src/test/java/com/xasecure/pdp/hdfs/URLBasedAuthDBTest.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * 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 com.xasecure.pdp.hdfs;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.junit.Test;
-
-import com.xasecure.pdp.model.Policy;
-import com.xasecure.pdp.model.PolicyContainer;
-import com.xasecure.pdp.model.ResourcePath;
-
-public class URLBasedAuthDBTest {
-
- @Test
- public void testIsAuditLogEnabledByACL_emptyPolicyContainer() {
-
- // audit can't be enabled if authdb isn't initialized
- assertFalse(mAuthDB.isAuditLogEnabledByACL("blah"));
-
- // or if the policy container in is null!
- URLBasedAuthDB spy = spy(mAuthDB);
- when(spy.getPolicyContainer()).thenReturn(null);
- assertFalse(mAuthDB.isAuditLogEnabledByACL("blah"));
-
- // of if policy container is empty, i.e. has no policies!
- List<Policy> policies = new ArrayList<Policy>();
- PolicyContainer policyContainer = mock(PolicyContainer.class);
- when(policyContainer.getAcl()).thenReturn(policies);
- when(spy.getPolicyContainer()).thenReturn(policyContainer);
- assertFalse(mAuthDB.isAuditLogEnabledByACL("blah"));
-
- // or if all policies are empty, i.e. no acls!
- Policy aPolicy = mock(Policy.class);
- when(aPolicy.getResourceList()).thenReturn(new ArrayList<ResourcePath>());
- policies.add(aPolicy);
- when(policyContainer.getAcl()).thenReturn(policies);
- when(spy.getPolicyContainer()).thenReturn(policyContainer);
- assertFalse(spy.isAuditLogEnabledByACL("blah"));
- }
-
- private final URLBasedAuthDB mAuthDB = URLBasedAuthDB.getInstance();
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/test/java/com/xasecure/pdp/hdfs/URLBasedAuthDB_IsAuditLogEnabledByACL_PTest.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/test/java/com/xasecure/pdp/hdfs/URLBasedAuthDB_IsAuditLogEnabledByACL_PTest.java b/agents-impl/src/test/java/com/xasecure/pdp/hdfs/URLBasedAuthDB_IsAuditLogEnabledByACL_PTest.java
deleted file mode 100644
index 02c81f5..0000000
--- a/agents-impl/src/test/java/com/xasecure/pdp/hdfs/URLBasedAuthDB_IsAuditLogEnabledByACL_PTest.java
+++ /dev/null
@@ -1,340 +0,0 @@
-/*
- * 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 com.xasecure.pdp.hdfs;
-
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertThat;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
-
-import com.xasecure.pdp.model.Policy;
-import com.xasecure.pdp.model.PolicyContainer;
-import com.xasecure.pdp.model.ResourcePath;
-
-@RunWith(Parameterized.class)
-public class URLBasedAuthDB_IsAuditLogEnabledByACL_PTest {
-
- static class PolicyIs {
- static final boolean wildcard = true;
- static final boolean audited = true;
- static final boolean recursive = true;
-
- static final boolean notWildcard = false;
- static final boolean notAudited = false;
- static final boolean notRecursive = false;
- }
-
- static final class PolicyPath {
- static final String path1 = "aPath";
- static final String path1Child1 = PolicyPath.path1 + "/" + "child1";
- static final String path1Child2 = PolicyPath.path1 + "/" + "child2";
-
- static final String path2 = "anotherPath";
- }
- static final class TestPath {
- static final String path1 = PolicyPath.path1;
- static final String beginsWithPath1 = PolicyPath.path1 + "_";
- static final String path1Child1 = PolicyPath.path1Child1;
- static final String path1Child2 = PolicyPath.path1Child2;
- static final String path1GrandChild1 = String.format("%s/%s/%s", path1, path1Child1, "grandChild1");
- static final String path1GrandChild2 = String.format("%s/%s/%s", path1, path1Child1, "grandChild2");
-
- static final String path2 = PolicyPath.path2;
- static final String beginsWithPath2 = PolicyPath.path2 + "_";
- static final String path2Child1 = PolicyPath.path2 + "/" + "child1";
- static final String path2Child2 = PolicyPath.path2 + "/" + "child2";
- }
-
- static class ExpectedResult {
- static final class AuditEnabled {
- static final boolean yes = true;
- static final boolean no = false;
- }
- }
-
- static class TestDataIndex {
- static final int ExpectedResult = 6;
- static final int Audited = 3;
- public static final int TestName = 0;
- public static final int wildCard = 2;
- }
-
-
- /**
- * ASSUMPTION: set of tests passed as such that they require wildcard flag to be set for them to return audit enabled.
- * So turn wildcard flag of them off to assert that they no-longer work. Of course, those that don't work even with wildcard
- * should also continue to not work when wildcard is turned off!
- */
- private static List<Object[]> turnWildcardOffForTestsThatRequireWildcard(List<Object[]> tests) {
-
- // in the worse case we would generate one test for each existing test
- List<Object[]> newTests = new ArrayList<Object[]>(tests.size());
- for (Object[] aTest: tests) {
- boolean isPolicyWildcard = (Boolean) aTest[TestDataIndex.wildCard];
- if (isPolicyWildcard == PolicyIs.wildcard) {
- Object[] newTest = Arrays.copyOf(aTest, aTest.length);
- // Change the policy of this test so that Audit is disabled at policy level and accordingly change the expected result
- newTest[TestDataIndex.wildCard] = PolicyIs.notWildcard;
- newTest[TestDataIndex.ExpectedResult] = ExpectedResult.AuditEnabled.no;
- // for debugging purposes alter the test description, too
- String testName = (String) newTest[TestDataIndex.TestName];
- newTest[TestDataIndex.TestName] = "[Wildcard-ed base test with wildcard flag turned off] " + testName;
- newTests.add(newTest);
- }
- }
- return newTests;
- }
-
- /**
- * wildcard - policy flag says wildcard by the policy path itself does not have any wildcards worth expanding.
- * This should work exactly the same as if wildcard was turned off!
- */
- private static List<Object[]> turnWildcardOnForNonWildcardTests(List<Object[]> tests) {
-
- // in the worse case we would generate one test for each existing test
- List<Object[]> newTests = new ArrayList<Object[]>(tests.size());
- /*
- * If a test currently does not have wildcard set on it, then expectation is changing wildcard flag
- * true shouldn't change the result. ASSUMPTION here, of course, is that "base tests" don't use any
- * wild-card characters in their resource paths that would make an otherwise disabled audit to return enabled.
- */
- for (Object[] aTest: tests) {
- boolean isPolicyWildcard = (Boolean) aTest[TestDataIndex.wildCard];
- if (isPolicyWildcard == PolicyIs.notWildcard) {
- Object[] newTest = Arrays.copyOf(aTest, aTest.length);
- // Change the policy of this test so that Audit is disabled at policy level and accordingly change the expected result
- newTest[TestDataIndex.wildCard] = PolicyIs.wildcard;
- // for debugging purposes alter the test description, too
- String testName = (String) newTest[TestDataIndex.TestName];
- newTest[TestDataIndex.TestName] = "[Base test with wildcard enabled] " + testName;
- newTests.add(newTest);
- }
- }
- return newTests;
- }
-
- /**
- * Disabled audit on every test that expects result to be yes to ensure that no matter what answer should be false if policy says that audit is disabled!
- */
- private static List<Object[]> disableAuditForBaseTests(List<Object[]> tests) {
-
- List<Object[]> newTests = new ArrayList<Object[]>(tests.size());
-
- for (Object[] aTest : tests) {
- boolean expectedResult = (Boolean) aTest[TestDataIndex.ExpectedResult];
- boolean isPolicyAuditEnabled = (Boolean) aTest[TestDataIndex.Audited];
-
- if (expectedResult == ExpectedResult.AuditEnabled.yes
- && isPolicyAuditEnabled == PolicyIs.audited) {
- Object[] newTest = Arrays.copyOf(aTest, aTest.length);
- // Change the policy of this test so that Audit is disabled at policy level and accordingly change the expected result
- newTest[TestDataIndex.Audited] = PolicyIs.notAudited;
- newTest[TestDataIndex.ExpectedResult] = ExpectedResult.AuditEnabled.no;
- // for debugging purposes alter the test description, too
- String testName = (String) newTest[TestDataIndex.TestName];
- newTest[TestDataIndex.TestName] = "[Base tests with audit disabled] " + testName;
- newTests.add(newTest);
- }
- }
-
- return newTests;
- }
-
- @Parameters
- public static Collection<Object[]> data() {
- Object[][] baseTestData = new Object[][] {
-
- // no-recursive paths - return true if paths match
- {"policypath(path1) == testpath(path1) => yes",
- PolicyPath.path1, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.notRecursive, TestPath.path1, ExpectedResult.AuditEnabled.yes},
- {"policypath(path2) == testpath(path2) => yes",
- PolicyPath.path2, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.notRecursive, TestPath.path2, ExpectedResult.AuditEnabled.yes},
-
- // no-recursive paths - return false if paths don't match!
- {"policypath(path1) != testPath(path2) => no",
- PolicyPath.path1, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.notRecursive, TestPath.path2, ExpectedResult.AuditEnabled.no},
- {"policypath(path2) != testPath(path1) => no",
- PolicyPath.path2, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.notRecursive, TestPath.path1, ExpectedResult.AuditEnabled.no},
-
- // recursive path policy - should work at least as well as non-recursive, i.e. match when same and not otherwise!
- {"recursive, policypath(path1) == testpath(path1)",
- PolicyPath.path1, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path1, ExpectedResult.AuditEnabled.yes},
- {"recursive, policypath(path2) == testpath(path2)",
- PolicyPath.path2, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path2, ExpectedResult.AuditEnabled.yes},
- {"recursive, policypath(path1) == testpath(path2)",
- PolicyPath.path1, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path2, ExpectedResult.AuditEnabled.no},
- {"recursive, policypath(path1) == testpath(path2)",
- PolicyPath.path2, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path1, ExpectedResult.AuditEnabled.no},
-
- // recursive path policy - should match children
- {"recursive, policypath(path1) == testpath(path1/child1)",
- PolicyPath.path1, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path1Child1, ExpectedResult.AuditEnabled.yes},
- {"recursive, policypath(path1) == testpath(path1/child2)",
- PolicyPath.path1, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path1Child2, ExpectedResult.AuditEnabled.yes},
- {"recursive, policypath(path1) == testpath(path1/child1)",
- PolicyPath.path2, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path2Child1, ExpectedResult.AuditEnabled.yes},
- {"recursive, policypath(path1) == testpath(path1/child2)",
- PolicyPath.path2, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path2Child2, ExpectedResult.AuditEnabled.yes},
-
- // recursive path policy - should match grand children, too!
- {"recursive, policypath(path1) == testpath(path1/child1/grandChild1)",
- PolicyPath.path1, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path1GrandChild1, ExpectedResult.AuditEnabled.yes},
- {"recursive, policypath(path1) == testpath(path1/child1/grandChild2)",
- PolicyPath.path1, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path1GrandChild2, ExpectedResult.AuditEnabled.yes},
-
- // recursive path policy - shouldn't match child in some other directory
- {"recursive, policypath(path1) == testpath(path1/child1)",
- PolicyPath.path1, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path2Child1, ExpectedResult.AuditEnabled.no},
- {"recursive, policypath(path1) == testpath(path1/child2)",
- PolicyPath.path1, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path2Child2, ExpectedResult.AuditEnabled.no},
- {"recursive, policypath(path1) == testpath(path1/child1)",
- PolicyPath.path2, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path1Child1, ExpectedResult.AuditEnabled.no},
- {"recursive, policypath(path1) == testpath(path1/child2)",
- PolicyPath.path2, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path1Child2, ExpectedResult.AuditEnabled.no},
-
- };
-
- Object[][] wildCardTestData = new Object[][] {
- // Pattern contains exact substring
- {"Wildcard, Pattern contains substring of tested path - 1",
- "aPath*", PolicyIs.wildcard, PolicyIs.audited, PolicyIs.recursive, "aPath", ExpectedResult.AuditEnabled.yes},
- {"Wildcard, Pattern contains substring of tested path - 2",
- "*aPath", PolicyIs.wildcard, PolicyIs.audited, PolicyIs.recursive, "aPath", ExpectedResult.AuditEnabled.yes},
- {"Wildcard, Pattern contains substring of tested path - 3",
- "aPa*th", PolicyIs.wildcard, PolicyIs.audited, PolicyIs.recursive, "aPath", ExpectedResult.AuditEnabled.yes},
- {"Wildcard, Pattern contains substring of tested path - 4",
- "aP*at*h", PolicyIs.wildcard, PolicyIs.audited, PolicyIs.recursive, "aPath", ExpectedResult.AuditEnabled.yes},
-
- // Pattern should match
- {"Wildcard, Pattern should match - 1",
- "aPath*", PolicyIs.wildcard, PolicyIs.audited, PolicyIs.recursive, "aPath_", ExpectedResult.AuditEnabled.yes},
- {"Wildcard, Pattern should match - 2",
- "aPath*", PolicyIs.wildcard, PolicyIs.audited, PolicyIs.recursive, "aPath_longSuffix", ExpectedResult.AuditEnabled.yes},
- {"Wildcard, Pattern should match - 3",
- "*aPath", PolicyIs.wildcard, PolicyIs.audited, PolicyIs.recursive, "_aPath", ExpectedResult.AuditEnabled.yes},
- {"Wildcard, Pattern should match - 4",
- "*aPath", PolicyIs.wildcard, PolicyIs.audited, PolicyIs.recursive, "longPrefix_aPath", ExpectedResult.AuditEnabled.yes},
- {"Wildcard, Pattern should match - 5",
- "*aPath", PolicyIs.wildcard, PolicyIs.audited, PolicyIs.recursive, "_aPath", ExpectedResult.AuditEnabled.yes},
- {"Wildcard, Pattern should match - 6",
- "*aPath", PolicyIs.wildcard, PolicyIs.audited, PolicyIs.recursive, "longPrefix_aPath", ExpectedResult.AuditEnabled.yes},
- {"Wildcard, Pattern should match - 5",
- "a*Path", PolicyIs.wildcard, PolicyIs.audited, PolicyIs.recursive, "a___Path", ExpectedResult.AuditEnabled.yes},
- {"Wildcard, Pattern should match - 6",
- "a*Path", PolicyIs.wildcard, PolicyIs.audited, PolicyIs.recursive, "aMiddlePath", ExpectedResult.AuditEnabled.yes},
- };
-
- // in the worst case all tests have a corresponding audit disabled test
- List<Object[]> baseTests = Arrays.asList(baseTestData);
- List<Object[]> result = new ArrayList<Object[]>(baseTests);
-
- // answer is false no matter what if policy is set to not audit
- List<Object[]> additionalTests = disableAuditForBaseTests(baseTests);
- result.addAll(additionalTests);
-
- // turning wildcard flag on when policy path itself does not have wildcard characters in it shouldn't change the result!
- additionalTests = turnWildcardOnForNonWildcardTests(baseTests);
- result.addAll(additionalTests);
-
- List<Object[]> wildcardBaseTests = Arrays.asList(wildCardTestData);
- result.addAll(wildcardBaseTests);
-
- additionalTests = turnWildcardOffForTestsThatRequireWildcard(wildcardBaseTests);
- result.addAll(additionalTests);
- return result;
- }
-
- public URLBasedAuthDB_IsAuditLogEnabledByACL_PTest(String testName, String policyPath, boolean wildCard, boolean audited, boolean recursive, String testPath, boolean expectedResult) {
- _testName = testName;
- _policyPath = policyPath;
- _policyPathWildcard = wildCard;
- _policyAudited = audited;
- _policyRecursive = recursive;
- _testPath = testPath;
- _expectedResult = expectedResult;
- }
-
- private final String _testName;
- private final String _policyPath;
- private final boolean _policyPathWildcard;
- private final boolean _policyAudited;
- private final boolean _policyRecursive;
- private final String _testPath;
- private final boolean _expectedResult;
-
- @Test
- public void testIsAuditLogEnabledByACL() {
-
- if (LOG.isDebugEnabled()) {
- LOG.debug(String.format("Test: %sPolicy Path: %s, isWildcard: %b, isAudited: %b, isRecursive: %b, TestPath: %s",
- _testName, _policyPath, _policyPathWildcard, _policyAudited, _policyRecursive, _testPath));
- }
-
- // A policy can have several paths, so let's first stuff our path into a collection
- ResourcePath path = mock(ResourcePath.class);
- when(path.getPath()).thenReturn(_policyPath);
- when(path.isWildcardPath()).thenReturn(_policyPathWildcard);
- List<ResourcePath> resourcePaths = new ArrayList<ResourcePath>();
- resourcePaths.add(path);
-
- // wire it into the policy and set other aspects of the policy
- Policy aPolicy = mock(Policy.class);
- when(aPolicy.getResourceList()).thenReturn(resourcePaths);
-
- int recursiveIndicator = _policyRecursive ? 1 : 0;
- when(aPolicy.getRecursiveInd()).thenReturn(recursiveIndicator);
-
- int auditedIndicator = _policyAudited ? 1 : 0;
- when(aPolicy.getAuditInd()).thenReturn(auditedIndicator);
-
- // a container can have several policies to first we stuff our policy into a container
- List<Policy> policies = new ArrayList<Policy>();
- policies.add(aPolicy);
- // now wire the policy into the container
- PolicyContainer policyContainer = mock(PolicyContainer.class);
- when(policyContainer.getAcl()).thenReturn(policies);
-
- // finally wire the policy container into the authdb
- URLBasedAuthDB spy = spy(mAuthDB);
- when(spy.getPolicyContainer()).thenReturn(policyContainer);
-
- // assert the result
- boolean result = spy.isAuditLogEnabledByACL(_testPath);
- assertThat(_testName, result, is(_expectedResult));
- if (LOG.isDebugEnabled()) {
- LOG.debug(String.format(", Expected Result (Audit enabled?): %b Result: %b\n", _expectedResult, result));
- }
- }
-
- private final URLBasedAuthDB mAuthDB = URLBasedAuthDB.getInstance();
- private static final Log LOG = LogFactory.getLog(URLBasedAuthDB_IsAuditLogEnabledByACL_PTest.class) ;
-}
[03/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/view/VList.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/view/VList.java b/security-admin/src/main/java/org/apache/ranger/common/view/VList.java
new file mode 100644
index 0000000..177e7fd
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/view/VList.java
@@ -0,0 +1,189 @@
+/*
+ * 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.view;
+
+
+import java.util.List;
+
+import javax.xml.bind.annotation.*;
+
+@XmlRootElement
+public abstract class VList extends ViewBaseBean implements
+ java.io.Serializable {
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * Start index for the result
+ */
+ protected int startIndex;
+ /**
+ * Page size used for the result
+ */
+ protected int pageSize;
+ /**
+ * Total records in the database for the given search conditions
+ */
+ protected long totalCount;
+ /**
+ * Number of rows returned for the search condition
+ */
+ protected int resultSize;
+ /**
+ * Sort type. Either desc or asc
+ */
+ protected String sortType;
+ /**
+ * Comma seperated list of the fields for sorting
+ */
+ protected String sortBy;
+
+ protected long queryTimeMS = System.currentTimeMillis();
+
+ /**
+ * Default constructor. This will set all the attributes to default value.
+ */
+ public VList() {
+ }
+
+ /**
+ * Initialize with existing list
+ *
+ * @param size
+ */
+ public VList(@SuppressWarnings("rawtypes") List objectList) {
+ int size = 0;
+ if (objectList != null) {
+ size = objectList.size();
+ }
+
+ startIndex = 0;
+ pageSize = size;
+ totalCount = size;
+ resultSize = size;
+ sortType = null;
+ sortBy = null;
+ }
+
+ abstract public int getListSize();
+
+ abstract public List<?> getList();
+
+ /**
+ * This method sets the value to the member attribute <b>startIndex</b>. You
+ * cannot set null to the attribute.
+ *
+ * @param startIndex
+ * Value to set member attribute <b>startIndex</b>
+ */
+ public void setStartIndex(int startIndex) {
+ this.startIndex = startIndex;
+ }
+
+
+ /**
+ * This method sets the value to the member attribute <b>pageSize</b>. You
+ * cannot set null to the attribute.
+ *
+ * @param pageSize
+ * Value to set member attribute <b>pageSize</b>
+ */
+ public void setPageSize(int pageSize) {
+ this.pageSize = pageSize;
+ }
+
+
+ /**
+ * This method sets the value to the member attribute <b>totalCount</b>. You
+ * cannot set null to the attribute.
+ *
+ * @param totalCount
+ * Value to set member attribute <b>totalCount</b>
+ */
+ public void setTotalCount(long totalCount) {
+ this.totalCount = totalCount;
+ }
+
+
+
+ /**
+ * This method sets the value to the member attribute <b>resultSize</b>. You
+ * cannot set null to the attribute.
+ *
+ * @param resultSize
+ * Value to set member attribute <b>resultSize</b>
+ */
+ public void setResultSize(int resultSize) {
+ this.resultSize = resultSize;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>resultSize</b>
+ *
+ * @return int - value of member attribute <b>resultSize</b>.
+ */
+ public int getResultSize() {
+ return getListSize();
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>sortType</b>. You
+ * cannot set null to the attribute.
+ *
+ * @param sortType
+ * Value to set member attribute <b>sortType</b>
+ */
+ public void setSortType(String sortType) {
+ this.sortType = sortType;
+ }
+
+
+
+ /**
+ * This method sets the value to the member attribute <b>sortBy</b>. You
+ * cannot set null to the attribute.
+ *
+ * @param sortBy
+ * Value to set member attribute <b>sortBy</b>
+ */
+ public void setSortBy(String sortBy) {
+ this.sortBy = sortBy;
+ }
+
+
+
+
+
+
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString() {
+ return "VList [startIndex=" + startIndex + ", pageSize="
+ + pageSize + ", totalCount=" + totalCount
+ + ", resultSize=" + resultSize + ", sortType="
+ + sortType + ", sortBy=" + sortBy + ", queryTimeMS="
+ + queryTimeMS + "]";
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/view/VTrxLogAttr.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/view/VTrxLogAttr.java b/security-admin/src/main/java/org/apache/ranger/common/view/VTrxLogAttr.java
new file mode 100644
index 0000000..2974e7d
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/view/VTrxLogAttr.java
@@ -0,0 +1,83 @@
+/*
+ * 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.view;
+
+import java.io.Serializable;
+
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.apache.ranger.common.AppConstants;
+import org.apache.ranger.common.XACommonEnums;
+import org.apache.ranger.common.view.ViewBaseBean;
+
+@XmlRootElement
+public class VTrxLogAttr extends ViewBaseBean implements Serializable{
+ private static final long serialVersionUID = 1L;
+
+ protected String attribName;
+ protected String attribUserFriendlyName;
+ protected boolean isEnum;
+
+ public VTrxLogAttr(){}
+
+ public VTrxLogAttr(String attribName, String attribUserFriendlyName,
+ boolean isEnum) {
+ super();
+ this.attribName = attribName;
+ this.attribUserFriendlyName = attribUserFriendlyName;
+ this.isEnum = isEnum;
+ }
+
+
+
+
+ /**
+ * @return the attribUserFriendlyName
+ */
+ public String getAttribUserFriendlyName() {
+ return attribUserFriendlyName;
+ }
+
+
+ /**
+ * @return the isEnum
+ */
+ public boolean isEnum() {
+ return isEnum;
+ }
+
+
+
+ @Override
+ public int getMyClassType( ) {
+ return AppConstants.CLASS_TYPE_XA_TRANSACTION_LOG_ATTRIBUTE;
+ }
+
+ @Override
+ public String toString(){
+ String str = "VTrxLogAttr={";
+ str += super.toString();
+ str += "attribName={" + attribName + "} ";
+ str += "attribUserFriendlyName={" + attribUserFriendlyName + "} ";
+ str += "isEnum={" + isEnum + "} ";
+ str += "}";
+ return str;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/common/view/ViewBaseBean.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/view/ViewBaseBean.java b/security-admin/src/main/java/org/apache/ranger/common/view/ViewBaseBean.java
new file mode 100644
index 0000000..b820120
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/common/view/ViewBaseBean.java
@@ -0,0 +1,56 @@
+/*
+ * 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.view;
+
+import javax.xml.bind.annotation.XmlTransient;
+
+import org.apache.ranger.common.XACommonEnums;
+import org.apache.ranger.entity.XXDBBase;
+import org.codehaus.jackson.annotate.JsonIgnore;
+
+public class ViewBaseBean implements java.io.Serializable {
+ private static final long serialVersionUID = 1L;
+
+ @JsonIgnore
+ private XXDBBase mObj = null;
+
+ /**
+ * @return the gjObj
+ */
+ @XmlTransient
+ @JsonIgnore
+ public XXDBBase getMObj() {
+ return mObj;
+ }
+
+ /**
+ * @param gjObj
+ * the gjObj to set
+ */
+ public void setMObj(XXDBBase gjObj) {
+ this.mObj = gjObj;
+ }
+
+ @XmlTransient
+ @JsonIgnore
+ public int getMyClassType() {
+ return XACommonEnums.CLASS_TYPE_NONE;
+ }
+}
\ 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/credentialapi/CredentialReader.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/credentialapi/CredentialReader.java b/security-admin/src/main/java/org/apache/ranger/credentialapi/CredentialReader.java
new file mode 100644
index 0000000..920c12d
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/credentialapi/CredentialReader.java
@@ -0,0 +1,87 @@
+/*
+ * 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.credentialapi;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.security.alias.CredentialProvider;
+import org.apache.hadoop.security.alias.CredentialProviderFactory;
+import org.apache.hadoop.security.alias.JavaKeyStoreProvider;
+
+public class CredentialReader {
+
+ public static String getDecryptedString(String CrendentialProviderPath,String alias) {
+ String credential=null;
+ try{
+ if(CrendentialProviderPath==null || alias==null){
+ return null;
+ }
+ char[] pass = null;
+ Configuration conf = new Configuration();
+ String crendentialProviderPrefix=JavaKeyStoreProvider.SCHEME_NAME + "://file";
+ crendentialProviderPrefix=crendentialProviderPrefix.toLowerCase();
+ CrendentialProviderPath=CrendentialProviderPath.trim();
+ alias=alias.trim();
+ if(CrendentialProviderPath.toLowerCase().startsWith(crendentialProviderPrefix)){
+ conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
+ //UserProvider.SCHEME_NAME + ":///," +
+ CrendentialProviderPath);
+ }else{
+ if(CrendentialProviderPath.startsWith("/")){
+ conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
+ //UserProvider.SCHEME_NAME + ":///," +
+ JavaKeyStoreProvider.SCHEME_NAME + "://file" + CrendentialProviderPath);
+ }else{
+ conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
+ //UserProvider.SCHEME_NAME + ":///," +
+ JavaKeyStoreProvider.SCHEME_NAME + "://file/" + CrendentialProviderPath);
+ }
+ }
+ List<CredentialProvider> providers = CredentialProviderFactory.getProviders(conf);
+ List<String> aliasesList=new ArrayList<String>();
+ CredentialProvider.CredentialEntry credEntry=null;
+ for(CredentialProvider provider: providers) {
+ //System.out.println("Credential Provider :" + provider);
+ aliasesList=provider.getAliases();
+ if(aliasesList!=null && aliasesList.contains(alias.toLowerCase())){
+ credEntry=null;
+ credEntry= provider.getCredentialEntry(alias);
+ pass = credEntry.getCredential();
+ if(pass!=null && pass.length>0){
+ credential=String.valueOf(pass);
+ break;
+ }
+ }
+ }
+ }catch(Exception ex){
+ ex.printStackTrace();
+ credential=null;
+ }
+ return credential;
+ }
+
+ /*
+ public static void main(String args[]) throws Exception{
+ String keystoreFile =new String("/tmp/mykey3.jceks");
+ String password=CredentialReader.getDecryptedString(keystoreFile, "mykey3");
+ System.out.println(password);
+ }*/
+}
\ 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/db/XADaoManager.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XADaoManager.java b/security-admin/src/main/java/org/apache/ranger/db/XADaoManager.java
new file mode 100644
index 0000000..64f2148
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/db/XADaoManager.java
@@ -0,0 +1,77 @@
+/*
+ * 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.db;
+
+
+
+import javax.persistence.*;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.common.*;
+import org.apache.ranger.common.db.BaseDao;
+import org.springframework.stereotype.Component;
+import org.springframework.beans.factory.annotation.Autowired;
+
+@Component
+public class XADaoManager extends XADaoManagerBase {
+ final static Logger logger = Logger.getLogger(XADaoManager.class);
+
+ @PersistenceContext(unitName = "defaultPU")
+ private EntityManager em;
+
+ @PersistenceContext(unitName = "loggingPU")
+ private EntityManager loggingEM;
+
+ @Autowired
+ StringUtil stringUtil;
+
+ @Override
+ public EntityManager getEntityManager() {
+ return em;
+ }
+
+ public EntityManager getEntityManager(String persistenceContextUnit) {
+ logger.error("XADaoManager.getEntityManager(" + persistenceContextUnit + ")");
+ if (persistenceContextUnit.equalsIgnoreCase("loggingPU")) {
+ return loggingEM;
+ }
+ return getEntityManager();
+ }
+
+
+ /**
+ * @return the stringUtil
+ */
+ public StringUtil getStringUtil() {
+ return stringUtil;
+ }
+
+ /*
+ * (non-Javadoc)
+ */
+ @Override
+ public BaseDao<?> getDaoForClassType(int classType) {
+ if (classType == XAConstants.CLASS_TYPE_NONE) {
+ return null;
+ }
+ return super.getDaoForClassType(classType);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/db/XADaoManagerBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XADaoManagerBase.java b/security-admin/src/main/java/org/apache/ranger/db/XADaoManagerBase.java
new file mode 100644
index 0000000..e908447
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/db/XADaoManagerBase.java
@@ -0,0 +1,216 @@
+/*
+ * 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.db;
+
+/**
+ *
+ */
+
+import javax.persistence.*;
+
+import java.util.*;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.common.*;
+import org.apache.ranger.common.db.*;
+import org.apache.ranger.entity.*;
+import org.springframework.stereotype.Component;
+import org.springframework.beans.factory.annotation.Autowired;
+
+
+public abstract class XADaoManagerBase {
+ final static Logger logger = Logger.getLogger(XADaoManagerBase.class);
+
+ @Autowired
+ protected RESTErrorUtil restErrorUtil;
+ abstract public EntityManager getEntityManager();
+
+ public XADaoManagerBase() {
+ }
+
+ public BaseDao<?> getDaoForClassType(int classType) {
+ if (classType == AppConstants.CLASS_TYPE_AUTH_SESS) {
+ return getXXAuthSession();
+ }
+ if (classType == AppConstants.CLASS_TYPE_USER_PROFILE) {
+ return getXXPortalUser();
+ }
+ if (classType == AppConstants.CLASS_TYPE_XA_ASSET) {
+ return getXXAsset();
+ }
+ if (classType == AppConstants.CLASS_TYPE_XA_RESOURCE) {
+ return getXXResource();
+ }
+ if (classType == AppConstants.CLASS_TYPE_XA_CRED_STORE) {
+ return getXXCredentialStore();
+ }
+ if (classType == AppConstants.CLASS_TYPE_XA_GROUP) {
+ return getXXGroup();
+ }
+ if (classType == AppConstants.CLASS_TYPE_XA_USER) {
+ return getXXUser();
+ }
+ if (classType == AppConstants.CLASS_TYPE_XA_GROUP_USER) {
+ return getXXGroupUser();
+ }
+ if (classType == AppConstants.CLASS_TYPE_XA_GROUP_GROUP) {
+ return getXXGroupGroup();
+ }
+ if (classType == AppConstants.CLASS_TYPE_XA_PERM_MAP) {
+ return getXXPermMap();
+ }
+ if (classType == AppConstants.CLASS_TYPE_XA_AUDIT_MAP) {
+ return getXXAuditMap();
+ }
+ if (classType == AppConstants.CLASS_TYPE_XA_POLICY_EXPORT_AUDIT) {
+ return getXXPolicyExportAudit();
+ }
+ if (classType == AppConstants.CLASS_TYPE_TRX_LOG) {
+ return getXXTrxLog();
+ }
+ if (classType == AppConstants.CLASS_TYPE_XA_ACCESS_AUDIT) {
+ return getXXAccessAudit();
+ }
+
+ logger.error("No DaoManager found for classType=" + classType, new Throwable());
+ return null;
+ }
+
+ public BaseDao<?> getDaoForClassName(String className) {
+ if (className.equals("XXDBBase")) {
+ return getXXDBBase();
+ }
+ if (className.equals("XXAuthSession")) {
+ return getXXAuthSession();
+ }
+ if (className.equals("XXPortalUser")) {
+ return getXXPortalUser();
+ }
+ if (className.equals("XXPortalUserRole")) {
+ return getXXPortalUserRole();
+ }
+ if (className.equals("XXAsset")) {
+ return getXXAsset();
+ }
+ if (className.equals("XXResource")) {
+ return getXXResource();
+ }
+ if (className.equals("XXCredentialStore")) {
+ return getXXCredentialStore();
+ }
+ if (className.equals("XXGroup")) {
+ return getXXGroup();
+ }
+ if (className.equals("XXUser")) {
+ return getXXUser();
+ }
+ if (className.equals("XXGroupUser")) {
+ return getXXGroupUser();
+ }
+ if (className.equals("XXGroupGroup")) {
+ return getXXGroupGroup();
+ }
+ if (className.equals("XXPermMap")) {
+ return getXXPermMap();
+ }
+ if (className.equals("XXAuditMap")) {
+ return getXXAuditMap();
+ }
+ if (className.equals("XXPolicyExportAudit")) {
+ return getXXPolicyExportAudit();
+ }
+ if (className.equals("XXTrxLog")) {
+ return getXXTrxLog();
+ }
+ if (className.equals("XXAccessAudit")) {
+ return getXXAccessAudit();
+ }
+
+ logger.error("No DaoManager found for className=" + className, new Throwable());
+ return null;
+ }
+
+ public XXDBBaseDao getXXDBBase() {
+ return new XXDBBaseDao(this);
+ }
+
+ public XXAuthSessionDao getXXAuthSession() {
+ return new XXAuthSessionDao(this);
+ }
+
+ public XXPortalUserDao getXXPortalUser() {
+ return new XXPortalUserDao(this);
+ }
+
+ public XXPortalUserRoleDao getXXPortalUserRole() {
+ return new XXPortalUserRoleDao(this);
+ }
+
+ public XXAssetDao getXXAsset() {
+ return new XXAssetDao(this);
+ }
+
+ public XXResourceDao getXXResource() {
+ return new XXResourceDao(this);
+ }
+
+ public XXCredentialStoreDao getXXCredentialStore() {
+ return new XXCredentialStoreDao(this);
+ }
+
+ public XXGroupDao getXXGroup() {
+ return new XXGroupDao(this);
+ }
+
+ public XXUserDao getXXUser() {
+ return new XXUserDao(this);
+ }
+
+ public XXGroupUserDao getXXGroupUser() {
+ return new XXGroupUserDao(this);
+ }
+
+ public XXGroupGroupDao getXXGroupGroup() {
+ return new XXGroupGroupDao(this);
+ }
+
+ public XXPermMapDao getXXPermMap() {
+ return new XXPermMapDao(this);
+ }
+
+ public XXAuditMapDao getXXAuditMap() {
+ return new XXAuditMapDao(this);
+ }
+
+ public XXPolicyExportAuditDao getXXPolicyExportAudit() {
+ return new XXPolicyExportAuditDao(this);
+ }
+
+ public XXTrxLogDao getXXTrxLog() {
+ return new XXTrxLogDao(this);
+ }
+
+ public XXAccessAuditDao getXXAccessAudit() {
+ return new XXAccessAuditDao(this);
+ }
+
+
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/db/XXAccessAuditDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXAccessAuditDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXAccessAuditDao.java
new file mode 100644
index 0000000..614cea9
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXAccessAuditDao.java
@@ -0,0 +1,32 @@
+/*
+ * 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.db;
+
+import org.apache.ranger.common.*;
+import org.apache.ranger.common.db.*;
+import org.apache.ranger.entity.*;
+
+public class XXAccessAuditDao extends BaseDao<XXAccessAudit> {
+
+ public XXAccessAuditDao( XADaoManagerBase daoManager ) {
+ super(daoManager, "loggingPU");
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/db/XXAssetDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXAssetDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXAssetDao.java
new file mode 100644
index 0000000..08a1d2a
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXAssetDao.java
@@ -0,0 +1,54 @@
+/*
+ * 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.db;
+
+import javax.persistence.NoResultException;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.common.XACommonEnums;
+import org.apache.ranger.common.db.*;
+import org.apache.ranger.entity.XXAsset;
+
+public class XXAssetDao extends BaseDao<XXAsset> {
+ static final Logger logger = Logger.getLogger(XXAssetDao.class);
+
+ public XXAssetDao( XADaoManagerBase daoManager ) {
+ super(daoManager);
+ }
+
+ public XXAsset findByAssetName(String name){
+ if (daoManager.getStringUtil().isEmpty(name)) {
+ logger.debug("name is empty");
+ return null;
+ }
+ try {
+ return getEntityManager()
+ .createNamedQuery("XXAsset.findByAssetName", XXAsset.class)
+ .setParameter("name", name.trim())
+ .setParameter("status",XACommonEnums.STATUS_DELETED)
+ .getSingleResult();
+ } catch (NoResultException e) {
+ // ignore
+ }
+ return null;
+ }
+
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/db/XXAuditMapDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXAuditMapDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXAuditMapDao.java
new file mode 100644
index 0000000..2b1a95f
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXAuditMapDao.java
@@ -0,0 +1,57 @@
+/*
+ * 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.db;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.persistence.NoResultException;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.common.*;
+import org.apache.ranger.common.db.*;
+import org.apache.ranger.entity.*;
+
+public class XXAuditMapDao extends BaseDao<XXAuditMap> {
+ static final Logger logger = Logger.getLogger(XXAssetDao.class);
+
+ public XXAuditMapDao( XADaoManagerBase daoManager ) {
+ super(daoManager);
+ }
+
+ public List<XXAuditMap> findByResourceId(Long resourceId) {
+ if (resourceId != null) {
+ try {
+ return getEntityManager()
+ .createNamedQuery("XXAuditMap.findByResourceId", XXAuditMap.class)
+ .setParameter("resourceId", resourceId)
+ .getResultList();
+ } catch (NoResultException e) {
+ logger.debug(e.getMessage());
+ }
+ } else {
+ logger.debug("ResourceId not provided.");
+ return new ArrayList<XXAuditMap>();
+ }
+ return new ArrayList<XXAuditMap>();
+ }
+
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/db/XXAuthSessionDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXAuthSessionDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXAuthSessionDao.java
new file mode 100644
index 0000000..4e592f4
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXAuthSessionDao.java
@@ -0,0 +1,53 @@
+/*
+ * 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.db;
+
+import java.util.List;
+
+import javax.persistence.NoResultException;
+
+import org.apache.ranger.common.db.BaseDao;
+import org.apache.ranger.entity.XXAuthSession;
+
+public class XXAuthSessionDao extends BaseDao<XXAuthSession> {
+
+ public XXAuthSessionDao( XADaoManagerBase daoManager ) {
+ super(daoManager);
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<Object[]> getUserLoggedIn(){
+ return getEntityManager()
+ .createNamedQuery("XXAuthSession.getUserLoggedIn")
+ .getResultList();
+ }
+
+ public XXAuthSession getAuthSessionBySessionId(String sessionId){
+ try{
+ return (XXAuthSession) getEntityManager()
+ .createNamedQuery("XXAuthSession.getAuthSessionBySessionId")
+ .setParameter("sessionId", sessionId)
+ .getSingleResult();
+ } catch(NoResultException ignoreNoResultFound) {
+ return null;
+ }
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/db/XXCredentialStoreDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXCredentialStoreDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXCredentialStoreDao.java
new file mode 100644
index 0000000..1ed278e
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXCredentialStoreDao.java
@@ -0,0 +1,32 @@
+/*
+ * 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.db;
+
+import org.apache.ranger.common.*;
+import org.apache.ranger.common.db.*;
+import org.apache.ranger.entity.*;
+
+public class XXCredentialStoreDao extends BaseDao<XXCredentialStore> {
+
+ public XXCredentialStoreDao( XADaoManagerBase daoManager ) {
+ super(daoManager);
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/db/XXDBBaseDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXDBBaseDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXDBBaseDao.java
new file mode 100644
index 0000000..3913f3d
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXDBBaseDao.java
@@ -0,0 +1,31 @@
+/*
+ * 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.db;
+
+import org.apache.ranger.common.db.BaseDao;
+import org.apache.ranger.entity.*;
+
+public class XXDBBaseDao extends BaseDao<XXDBBase> {
+
+ public XXDBBaseDao( XADaoManagerBase daoManager ) {
+ super(daoManager);
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/db/XXGroupDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXGroupDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXGroupDao.java
new file mode 100644
index 0000000..e0b7735
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXGroupDao.java
@@ -0,0 +1,73 @@
+/*
+ * 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.db;
+
+
+import java.util.ArrayList;
+import java.util.List;
+
+
+
+
+import org.apache.ranger.common.*;
+import org.apache.ranger.common.db.*;
+import org.apache.ranger.entity.*;
+
+public class XXGroupDao extends BaseDao<XXGroup> {
+
+ public XXGroupDao(XADaoManagerBase daoManager) {
+ super(daoManager);
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<XXGroup> findByUserId(Long userId) {
+ if (userId == null) {
+ return new ArrayList<XXGroup>();
+ }
+
+ List<XXGroup> groupList = (List<XXGroup>) getEntityManager()
+ .createNamedQuery("XXGroup.findByUserId")
+ .setParameter("userId", userId).getResultList();
+
+ if (groupList == null) {
+ groupList = new ArrayList<XXGroup>();
+ }
+
+ return groupList;
+ }
+
+ @SuppressWarnings("unchecked")
+ public XXGroup findByGroupName(String groupName) {
+ if (groupName == null) {
+ return null;
+ }
+ try {
+
+ return (XXGroup) getEntityManager()
+ .createNamedQuery("XXGroup.findByGroupName")
+ .setParameter("name", groupName)
+ .getSingleResult();
+ } catch (Exception e) {
+
+ }
+ return null;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/db/XXGroupGroupDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXGroupGroupDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXGroupGroupDao.java
new file mode 100644
index 0000000..5b831a2
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXGroupGroupDao.java
@@ -0,0 +1,32 @@
+/*
+ * 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.db;
+
+import org.apache.ranger.common.*;
+import org.apache.ranger.common.db.*;
+import org.apache.ranger.entity.*;
+
+public class XXGroupGroupDao extends BaseDao<XXGroupGroup> {
+
+ public XXGroupGroupDao( XADaoManagerBase daoManager ) {
+ super(daoManager);
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/db/XXGroupUserDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXGroupUserDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXGroupUserDao.java
new file mode 100644
index 0000000..8b27c7f
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXGroupUserDao.java
@@ -0,0 +1,64 @@
+/*
+ * 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.db;
+
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.persistence.NoResultException;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.common.*;
+import org.apache.ranger.common.db.*;
+import org.apache.ranger.entity.*;
+
+public class XXGroupUserDao extends BaseDao<XXGroupUser> {
+ static final Logger logger = Logger.getLogger(XXGroupUserDao.class);
+
+ public XXGroupUserDao(XADaoManagerBase daoManager) {
+ super(daoManager);
+ }
+
+ public void deleteByGroupIdAndUserId(Long groupId, Long userId) {
+ getEntityManager()
+ .createNamedQuery("XXGroupUser.deleteByGroupIdAndUserId")
+ .setParameter("userId", userId)
+ .setParameter("parentGroupId", groupId).executeUpdate();
+
+ }
+
+ public List<XXGroupUser> findByUserId(Long userId) {
+ if (userId != null) {
+ try {
+ return getEntityManager()
+ .createNamedQuery("XXGroupUser.findByUserId", XXGroupUser.class)
+ .setParameter("userId", userId)
+ .getResultList();
+ } catch (NoResultException e) {
+ logger.debug(e.getMessage());
+ }
+ } else {
+ logger.debug("ResourceId not provided.");
+ return new ArrayList<XXGroupUser>();
+ }
+ return null;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/db/XXPermMapDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPermMapDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPermMapDao.java
new file mode 100644
index 0000000..659b9be
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXPermMapDao.java
@@ -0,0 +1,56 @@
+/*
+ * 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.db;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.persistence.NoResultException;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.common.*;
+import org.apache.ranger.common.db.*;
+import org.apache.ranger.entity.*;
+
+public class XXPermMapDao extends BaseDao<XXPermMap> {
+ static final Logger logger = Logger.getLogger(XXResourceDao.class);
+
+ public XXPermMapDao( XADaoManagerBase daoManager ) {
+ super(daoManager);
+ }
+
+ public List<XXPermMap> findByResourceId(Long resourceId) {
+ if (resourceId != null) {
+ try {
+ return getEntityManager()
+ .createNamedQuery("XXPermMap.findByResourceId", XXPermMap.class)
+ .setParameter("resourceId", resourceId)
+ .getResultList();
+ } catch (NoResultException e) {
+ logger.debug(e.getMessage());
+ }
+ } else {
+ logger.debug("ResourceId not provided.");
+ return new ArrayList<XXPermMap>();
+ }
+ return null;
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/db/XXPolicyExportAuditDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyExportAuditDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyExportAuditDao.java
new file mode 100644
index 0000000..9ac89b7
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyExportAuditDao.java
@@ -0,0 +1,32 @@
+/*
+ * 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.db;
+
+import org.apache.ranger.common.*;
+import org.apache.ranger.common.db.*;
+import org.apache.ranger.entity.*;
+
+public class XXPolicyExportAuditDao extends BaseDao<XXPolicyExportAudit> {
+
+ public XXPolicyExportAuditDao( XADaoManagerBase daoManager ) {
+ super(daoManager);
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/db/XXPortalUserDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPortalUserDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPortalUserDao.java
new file mode 100644
index 0000000..ac11431
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXPortalUserDao.java
@@ -0,0 +1,79 @@
+/*
+ * 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.db;
+
+
+import java.util.List;
+
+import org.apache.ranger.common.db.*;
+import org.apache.ranger.entity.XXPortalUser;
+
+public class XXPortalUserDao extends BaseDao<XXPortalUser> {
+
+ public XXPortalUserDao(XADaoManagerBase daoManager) {
+ super(daoManager);
+ }
+
+ public XXPortalUser findByLoginId(String loginId) {
+ if (daoManager.getStringUtil().isEmpty(loginId)) {
+ return null;
+ }
+
+ @SuppressWarnings("rawtypes")
+ List resultList = getEntityManager()
+ .createNamedQuery("XXPortalUser.findByLoginId")
+ .setParameter("loginId", loginId).getResultList();
+ if (resultList.size() != 0) {
+ return (XXPortalUser) resultList.get(0);
+ }
+ return null;
+ }
+
+ public XXPortalUser findByEmailAddress(String emailAddress) {
+ if (daoManager.getStringUtil().isEmpty(emailAddress)) {
+ return null;
+ }
+
+ @SuppressWarnings("rawtypes")
+ List resultList = getEntityManager()
+ .createNamedQuery("XXPortalUser.findByEmailAddress")
+ .setParameter("emailAddress", emailAddress)
+ .getResultList();
+ if (resultList.size() != 0) {
+ return (XXPortalUser) resultList.get(0);
+ }
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<XXPortalUser> findByRole(String userRole) {
+ return getEntityManager().createNamedQuery("XXPortalUser.findByRole")
+ .setParameter("userRole", userRole.toUpperCase())
+ .getResultList();
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<Object[]> getUserAddedReport(){
+ return getEntityManager()
+ .createNamedQuery("XXPortalUser.getUserAddedReport")
+ .getResultList();
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/db/XXPortalUserRoleDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPortalUserRoleDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPortalUserRoleDao.java
new file mode 100644
index 0000000..cf41d59
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXPortalUserRoleDao.java
@@ -0,0 +1,59 @@
+/*
+ * 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.db;
+
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.persistence.NoResultException;
+
+import org.apache.ranger.common.db.*;
+import org.apache.ranger.entity.XXPortalUserRole;
+
+public class XXPortalUserRoleDao extends BaseDao<XXPortalUserRole> {
+
+ public XXPortalUserRoleDao(XADaoManagerBase daoManager) {
+ super(daoManager);
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<XXPortalUserRole> findByUserId(Long userId) {
+ if (userId == null) {
+ return new ArrayList<XXPortalUserRole>();
+ }
+ return getEntityManager().createNamedQuery("XXPortalUserRole.findByUserId")
+ .setParameter("userId", userId).getResultList();
+ }
+
+ public XXPortalUserRole findByRoleUserId(Long userId, String role) {
+ if(userId == null || role == null || role.isEmpty()){
+ return null;
+ }
+ try{
+ return (XXPortalUserRole)getEntityManager().createNamedQuery("XXPortalUserRole.findByRoleUserId")
+ .setParameter("userId", userId)
+ .setParameter("userRole", role).getSingleResult();
+ } catch(NoResultException e){
+ //doNothing;
+ }
+ return null;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/db/XXResourceDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXResourceDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXResourceDao.java
new file mode 100644
index 0000000..0aa3f75
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXResourceDao.java
@@ -0,0 +1,273 @@
+/*
+ * 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.db;
+
+
+import java.util.Date;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.persistence.NoResultException;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.common.db.*;
+import org.apache.ranger.entity.XXResource;
+
+public class XXResourceDao extends BaseDao<XXResource> {
+ static final Logger logger = Logger.getLogger(XXResourceDao.class);
+
+ public XXResourceDao(XADaoManagerBase daoManager) {
+ super(daoManager);
+ }
+
+ public XXResource findByResourceName(String name) {
+ if (daoManager.getStringUtil().isEmpty(name)) {
+ logger.debug("name is empty");
+ return null;
+ }
+ try {
+ return getEntityManager()
+ .createNamedQuery("XXResource.findByResourceName",
+ XXResource.class).setParameter("name", name.trim())
+ .getSingleResult();
+ } catch (NoResultException e) {
+ // ignore
+ }
+ return null;
+ }
+
+ public List<XXResource> findUpdatedResourcesByAssetId(
+ Long assetId, Date lastUpdated) {
+ if (assetId != null) {
+ try {
+ return getEntityManager()
+ .createNamedQuery("XXResource.findUpdatedResourcesByAssetId",
+ XXResource.class)
+ .setParameter("assetId", assetId)
+ .setParameter("lastUpdated", lastUpdated)
+ .getResultList();
+ } catch (NoResultException e) {
+ logger.debug(e.getMessage());
+ }
+ } else {
+ logger.debug("AssetId not provided.");
+ return new ArrayList<XXResource>();
+ }
+ return null;
+ }
+
+ public List<XXResource> findByAssetId(Long assetId) {
+ List<XXResource> xResourceList = null;
+ if (assetId != null) {
+ try {
+ xResourceList = getEntityManager()
+ .createNamedQuery("XXResource.findByAssetId", XXResource.class)
+ .setParameter("assetId", assetId)
+ .getResultList();
+ } catch (NoResultException e) {
+ // ignore
+ logger.debug(e.getMessage());
+ }
+ if(xResourceList == null) {
+ xResourceList = new ArrayList<XXResource>();
+ }
+ } else {
+ logger.debug("AssetId not provided.");
+ xResourceList = new ArrayList<XXResource>();
+ }
+ return xResourceList;
+ }
+
+ public List<XXResource> findByAssetType(Integer assetType) {
+ List<XXResource> xResourceList = null;
+ if (assetType != null) {
+ try {
+ xResourceList = getEntityManager()
+ .createNamedQuery("XXResource.findByAssetType", XXResource.class)
+ .setParameter("assetType", assetType)
+ .getResultList();
+ } catch (NoResultException e) {
+ // ignore
+ logger.debug(e.getMessage());
+ }
+ if(xResourceList == null) {
+ xResourceList = new ArrayList<XXResource>();
+ }
+ } else {
+ logger.debug("AssetType not provided.");
+ xResourceList = new ArrayList<XXResource>();
+ }
+ return xResourceList;
+ }
+
+ public Timestamp getMaxUpdateTimeForAssetName(String assetName) {
+ if (assetName == null) {
+ return null;
+ }
+ try {
+ Date date=(Date)getEntityManager()
+ .createNamedQuery("XXResource.getMaxUpdateTimeForAssetName")
+ .setParameter("assetName", assetName)
+ .getSingleResult();
+ if(date!=null){
+ Timestamp timestamp=new Timestamp(date.getTime());
+ return timestamp;
+ }else{
+ return null;
+ }
+ } catch (NoResultException e) {
+ // ignore
+ }
+ return null;
+ }
+
+ public List<XXResource> findUpdatedResourcesByAssetName(
+ String assetName, Date lastUpdated) {
+ if (assetName != null) {
+ try {
+ return getEntityManager()
+ .createNamedQuery(
+ "XXResource.findUpdatedResourcesByAssetName",
+ XXResource.class)
+ .setParameter("assetName", assetName)
+ .setParameter("lastUpdated", lastUpdated)
+ .getResultList();
+ } catch (NoResultException e) {
+ logger.debug(e.getMessage());
+ }
+ } else {
+ logger.debug("Asset name not provided.");
+ return new ArrayList<XXResource>();
+ }
+ return null;
+ }
+
+ public List<XXResource> findByResourceNameAndAssetIdAndRecursiveFlag(
+ String name,Long assetId,int isRecursive ) {
+ if (daoManager.getStringUtil().isEmpty(name)) {
+ logger.debug("name is empty");
+ return null;
+ }
+ if (assetId==null) {
+ logger.debug("assetId is null");
+ return null;
+ }
+ try {
+ String resourceName = name.trim();
+ resourceName = "%"+resourceName+"%";
+ return getEntityManager()
+ .createNamedQuery(
+ "XXResource.findByResourceNameAndAssetIdAndRecursiveFlag",
+ XXResource.class).setParameter("name", resourceName)
+ .setParameter("assetId", assetId)
+ .setParameter("isRecursive", isRecursive)
+ .getResultList();
+ } catch (NoResultException e) {
+ // ignore
+ }
+ return null;
+ }
+
+ public List<XXResource> findByResourceNameAndAssetIdAndResourceType(String name,Long assetId,int resourceType) {
+ if (daoManager.getStringUtil().isEmpty(name)) {
+ logger.debug("name is empty");
+ return null;
+ }
+ if (assetId==null) {
+ logger.debug("assetId is null");
+ return null;
+ }
+ try {
+ String resourceName = name.trim();
+ resourceName = "%"+resourceName+"%";
+ return getEntityManager()
+ .createNamedQuery(
+ "XXResource.findByResourceNameAndAssetIdAndResourceType",
+ XXResource.class).setParameter("name", resourceName)
+ .setParameter("assetId", assetId)
+ .setParameter("resourceType", resourceType)
+ .getResultList();
+ } catch (NoResultException e) {
+ // ignore
+ }
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<XXResource> findByAssetIdAndResourceTypes(Long assetId,
+ List<Integer> resourceType) {
+ if (assetId == null) {
+ logger.debug("assetId is null");
+ return null;
+ }
+ try {
+ StringBuffer query = new StringBuffer(
+ "SELECT obj FROM XXResource obj WHERE obj.assetId="
+ + assetId);
+ String whereClause = makeWhereCaluseForResourceType(resourceType);
+ if (!whereClause.trim().isEmpty()) {
+ query.append(" and ( " + whereClause + " )");
+ }
+ return getEntityManager().createQuery(query.toString())
+ .getResultList();
+ } catch (NoResultException e) {
+ // ignore
+ }
+ return null;
+ }
+
+ private String makeWhereCaluseForResourceType(List<Integer> resourceTypes) {
+ StringBuffer whereClause = new StringBuffer();
+ if (resourceTypes != null && resourceTypes.size() != 0) {
+
+ for (int i = 0; i < resourceTypes.size() - 1; i++) {
+ whereClause.append("obj.resourceType=" + resourceTypes.get(i)
+ + " OR ");
+ }
+ whereClause.append("obj.resourceType="
+ + resourceTypes.get(resourceTypes.size() - 1));
+ }
+ return whereClause.toString();
+ }
+
+ public List<XXResource> findByAssetIdAndResourceStatus(Long assetId, int resourceStatus) {
+ List<XXResource> xResourceList = null;
+ if (assetId != null) {
+ try {
+ xResourceList = getEntityManager()
+ .createNamedQuery("XXResource.findByAssetIdAndResourceStatus", XXResource.class)
+ .setParameter("assetId", assetId)
+ .setParameter("resourceStatus", resourceStatus)
+ .getResultList();
+ } catch (NoResultException e) {
+ // ignore
+ logger.debug(e.getMessage());
+ }
+ if(xResourceList == null) {
+ xResourceList = new ArrayList<XXResource>();
+ }
+ } else {
+ logger.debug("AssetId not provided.");
+ xResourceList = new ArrayList<XXResource>();
+ }
+ return xResourceList;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/db/XXTrxLogDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXTrxLogDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXTrxLogDao.java
new file mode 100644
index 0000000..e5729fa
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXTrxLogDao.java
@@ -0,0 +1,56 @@
+/*
+ * 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.db;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.persistence.NoResultException;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.common.db.*;
+import org.apache.ranger.entity.XXTrxLog;
+
+public class XXTrxLogDao extends BaseDao<XXTrxLog> {
+ private static Logger logger = Logger.getLogger(XXTrxLogDao.class);
+
+ public XXTrxLogDao( XADaoManagerBase daoManager ) {
+ super(daoManager);
+ }
+
+ public List<XXTrxLog> findByTransactionId(String transactionId){
+ if(transactionId == null){
+ return null;
+ }
+
+ List<XXTrxLog> xTrxLogList = new ArrayList<XXTrxLog>();
+ try {
+ xTrxLogList = getEntityManager()
+ .createNamedQuery("XXTrxLog.findByTrxId", XXTrxLog.class)
+ .setParameter("transactionId", transactionId)
+ .getResultList();
+ } catch (NoResultException e) {
+ logger.debug(e.getMessage());
+ }
+
+ return xTrxLogList;
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/db/XXUserDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXUserDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXUserDao.java
new file mode 100644
index 0000000..4d2cec4
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXUserDao.java
@@ -0,0 +1,51 @@
+/*
+ * 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.db;
+
+
+import javax.persistence.NoResultException;
+
+import org.apache.log4j.Logger;
+import org.apache.ranger.common.db.*;
+import org.apache.ranger.entity.XXUser;
+
+public class XXUserDao extends BaseDao<XXUser> {
+ static final Logger logger = Logger.getLogger(XXResourceDao.class);
+
+ public XXUserDao(XADaoManagerBase daoManager) {
+ super(daoManager);
+ }
+
+ public XXUser findByUserName(String name) {
+ if (daoManager.getStringUtil().isEmpty(name)) {
+ logger.debug("name is empty");
+ return null;
+ }
+ try {
+ return getEntityManager()
+ .createNamedQuery("XXUser.findByUserName", XXUser.class)
+ .setParameter("name", name.trim())
+ .getSingleResult();
+ } catch (NoResultException e) {
+ // ignore
+ }
+ return null;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/entity/XXAccessAudit.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXAccessAudit.java b/security-admin/src/main/java/org/apache/ranger/entity/XXAccessAudit.java
new file mode 100644
index 0000000..1e8f6e7
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/entity/XXAccessAudit.java
@@ -0,0 +1,653 @@
+/*
+ * 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.entity;
+
+/**
+ * Access Audit
+ *
+ */
+
+import java.util.*;
+
+import javax.persistence.*;
+import javax.xml.bind.annotation.*;
+
+import org.apache.ranger.common.*;
+import org.apache.ranger.entity.*;
+
+
+@Entity
+@Table(name="xa_access_audit")
+@XmlRootElement
+public class XXAccessAudit extends XXDBBase implements java.io.Serializable {
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @SequenceGenerator(name="XA_ACCESS_AUDIT_SEQ",sequenceName="XA_ACCESS_AUDIT_SEQ",allocationSize=1)
+ @GeneratedValue(strategy=GenerationType.AUTO,generator="XA_ACCESS_AUDIT_SEQ")
+ @Column(name="ID")
+ protected Long id;
+
+ @Override
+ public void setId(Long id) {
+ this.id=id;
+ }
+ @Override
+ public Long getId() {
+ return id;
+ }
+ /**
+ * Repository Type
+ * <ul>
+ * <li>This attribute is of type enum CommonEnums::AssetType
+ * </ul>
+ *
+ */
+ @Column(name="AUDIT_TYPE" , nullable=false )
+ protected int auditType = AppConstants.ASSET_UNKNOWN;
+
+ /**
+ * Access Result
+ * <ul>
+ * <li>This attribute is of type enum CommonEnums::AccessResult
+ * </ul>
+ *
+ */
+ @Column(name="ACCESS_RESULT" )
+ protected int accessResult = XAConstants.ACCESS_RESULT_DENIED;
+
+ /**
+ * Access Type
+ * <ul>
+ * <li>The maximum length for this attribute is <b>255</b>.
+ * </ul>
+ *
+ */
+ @Column(name="ACCESS_TYPE" , length=255)
+ protected String accessType;
+
+ /**
+ * Acl Enforcer
+ * <ul>
+ * <li>The maximum length for this attribute is <b>255</b>.
+ * </ul>
+ *
+ */
+ @Column(name="ACL_ENFORCER" , length=255)
+ protected String aclEnforcer;
+
+ /**
+ * Agent Id
+ * <ul>
+ * <li>The maximum length for this attribute is <b>255</b>.
+ * </ul>
+ *
+ */
+ @Column(name="AGENT_ID" , length=255)
+ protected String agentId;
+
+ /**
+ * Client Ip
+ * <ul>
+ * <li>The maximum length for this attribute is <b>255</b>.
+ * </ul>
+ *
+ */
+ @Column(name="CLIENT_IP" , length=255)
+ protected String clientIP;
+
+ /**
+ * Client Type
+ * <ul>
+ * <li>The maximum length for this attribute is <b>255</b>.
+ * </ul>
+ *
+ */
+ @Column(name="CLIENT_TYPE" , length=255)
+ protected String clientType;
+
+ /**
+ * Policy Id
+ * <ul>
+ * </ul>
+ *
+ */
+ @Column(name="POLICY_ID" )
+ protected long policyId;
+
+ /**
+ * Repository Name
+ * <ul>
+ * <li>The maximum length for this attribute is <b>255</b>.
+ * </ul>
+ *
+ */
+ @Column(name="REPO_NAME" , length=255)
+ protected String repoName;
+
+ /**
+ * Repository Type
+ * <ul>
+ * </ul>
+ *
+ */
+ @Column(name="REPO_TYPE" )
+ protected int repoType;
+
+ /**
+ * Reason of result
+ * <ul>
+ * <li>The maximum length for this attribute is <b>255</b>.
+ * </ul>
+ *
+ */
+ @Column(name="RESULT_REASON" , length=255)
+ protected String resultReason;
+
+ /**
+ * Session Id
+ * <ul>
+ * <li>The maximum length for this attribute is <b>255</b>.
+ * </ul>
+ *
+ */
+ @Column(name="SESSION_ID" , length=255)
+ protected String sessionId;
+
+ /**
+ * Event Time
+ * <ul>
+ * </ul>
+ *
+ */
+ @Temporal(TemporalType.TIMESTAMP)
+ @Column(name="EVENT_TIME" )
+ protected Date eventTime = DateUtil.getUTCDate();
+
+ /**
+ * Requesting User
+ * <ul>
+ * <li>The maximum length for this attribute is <b>255</b>.
+ * </ul>
+ *
+ */
+ @Column(name="REQUEST_USER" , length=255)
+ protected String requestUser;
+
+ /**
+ * Action
+ * <ul>
+ * <li>The maximum length for this attribute is <b>2000</b>.
+ * </ul>
+ *
+ */
+ @Column(name="ACTION" , length=2000)
+ protected String action;
+
+ /**
+ * Requesting Data
+ * <ul>
+ * <li>The maximum length for this attribute is <b>2000</b>.
+ * </ul>
+ *
+ */
+ @Column(name="REQUEST_DATA" , length=2000)
+ protected String requestData;
+
+ /**
+ * Resource Path
+ * <ul>
+ * <li>The maximum length for this attribute is <b>2000</b>.
+ * </ul>
+ *
+ */
+ @Column(name="RESOURCE_PATH" , length=2000)
+ protected String resourcePath;
+
+ /**
+ * Resource Type
+ * <ul>
+ * <li>The maximum length for this attribute is <b>255</b>.
+ * </ul>
+ *
+ */
+ @Column(name="RESOURCE_TYPE" , length=255)
+ protected String resourceType;
+
+ /**
+ * Default constructor. This will set all the attributes to default value.
+ */
+ public XXAccessAudit ( ) {
+ auditType = AppConstants.ASSET_UNKNOWN;
+ accessResult = XAConstants.ACCESS_RESULT_DENIED;
+ }
+
+ @Override
+ public int getMyClassType( ) {
+ return AppConstants.CLASS_TYPE_XA_ACCESS_AUDIT;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>auditType</b>.
+ * You cannot set null to the attribute.
+ * @param auditType Value to set member attribute <b>auditType</b>
+ */
+ public void setAuditType( int auditType ) {
+ this.auditType = auditType;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>auditType</b>
+ * @return int - value of member attribute <b>auditType</b>.
+ */
+ public int getAuditType( ) {
+ return this.auditType;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>accessResult</b>.
+ * You cannot set null to the attribute.
+ * @param accessResult Value to set member attribute <b>accessResult</b>
+ */
+ public void setAccessResult( int accessResult ) {
+ this.accessResult = accessResult;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>accessResult</b>
+ * @return int - value of member attribute <b>accessResult</b>.
+ */
+ public int getAccessResult( ) {
+ return this.accessResult;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>accessType</b>.
+ * You cannot set null to the attribute.
+ * @param accessType Value to set member attribute <b>accessType</b>
+ */
+ public void setAccessType( String accessType ) {
+ this.accessType = accessType;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>accessType</b>
+ * @return String - value of member attribute <b>accessType</b>.
+ */
+ public String getAccessType( ) {
+ return this.accessType;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>aclEnforcer</b>.
+ * You cannot set null to the attribute.
+ * @param aclEnforcer Value to set member attribute <b>aclEnforcer</b>
+ */
+ public void setAclEnforcer( String aclEnforcer ) {
+ this.aclEnforcer = aclEnforcer;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>aclEnforcer</b>
+ * @return String - value of member attribute <b>aclEnforcer</b>.
+ */
+ public String getAclEnforcer( ) {
+ return this.aclEnforcer;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>agentId</b>.
+ * You cannot set null to the attribute.
+ * @param agentId Value to set member attribute <b>agentId</b>
+ */
+ public void setAgentId( String agentId ) {
+ this.agentId = agentId;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>agentId</b>
+ * @return String - value of member attribute <b>agentId</b>.
+ */
+ public String getAgentId( ) {
+ return this.agentId;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>clientIP</b>.
+ * You cannot set null to the attribute.
+ * @param clientIP Value to set member attribute <b>clientIP</b>
+ */
+ public void setClientIP( String clientIP ) {
+ this.clientIP = clientIP;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>clientIP</b>
+ * @return String - value of member attribute <b>clientIP</b>.
+ */
+ public String getClientIP( ) {
+ return this.clientIP;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>clientType</b>.
+ * You cannot set null to the attribute.
+ * @param clientType Value to set member attribute <b>clientType</b>
+ */
+ public void setClientType( String clientType ) {
+ this.clientType = clientType;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>clientType</b>
+ * @return String - value of member attribute <b>clientType</b>.
+ */
+ public String getClientType( ) {
+ return this.clientType;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>policyId</b>.
+ * You cannot set null to the attribute.
+ * @param policyId Value to set member attribute <b>policyId</b>
+ */
+ public void setPolicyId( long policyId ) {
+ this.policyId = policyId;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>policyId</b>
+ * @return long - value of member attribute <b>policyId</b>.
+ */
+ public long getPolicyId( ) {
+ return this.policyId;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>repoName</b>.
+ * You cannot set null to the attribute.
+ * @param repoName Value to set member attribute <b>repoName</b>
+ */
+ public void setRepoName( String repoName ) {
+ this.repoName = repoName;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>repoName</b>
+ * @return String - value of member attribute <b>repoName</b>.
+ */
+ public String getRepoName( ) {
+ return this.repoName;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>repoType</b>.
+ * You cannot set null to the attribute.
+ * @param repoType Value to set member attribute <b>repoType</b>
+ */
+ public void setRepoType( int repoType ) {
+ this.repoType = repoType;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>repoType</b>
+ * @return int - value of member attribute <b>repoType</b>.
+ */
+ public int getRepoType( ) {
+ return this.repoType;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>resultReason</b>.
+ * You cannot set null to the attribute.
+ * @param resultReason Value to set member attribute <b>resultReason</b>
+ */
+ public void setResultReason( String resultReason ) {
+ this.resultReason = resultReason;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>resultReason</b>
+ * @return String - value of member attribute <b>resultReason</b>.
+ */
+ public String getResultReason( ) {
+ return this.resultReason;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>sessionId</b>.
+ * You cannot set null to the attribute.
+ * @param sessionId Value to set member attribute <b>sessionId</b>
+ */
+ public void setSessionId( String sessionId ) {
+ this.sessionId = sessionId;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>sessionId</b>
+ * @return String - value of member attribute <b>sessionId</b>.
+ */
+ public String getSessionId( ) {
+ return this.sessionId;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>eventTime</b>.
+ * You cannot set null to the attribute.
+ * @param eventTime Value to set member attribute <b>eventTime</b>
+ */
+ public void setEventTime( Date eventTime ) {
+ this.eventTime = eventTime;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>eventTime</b>
+ * @return Date - value of member attribute <b>eventTime</b>.
+ */
+ public Date getEventTime( ) {
+ return this.eventTime;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>requestUser</b>.
+ * You cannot set null to the attribute.
+ * @param requestUser Value to set member attribute <b>requestUser</b>
+ */
+ public void setRequestUser( String requestUser ) {
+ this.requestUser = requestUser;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>requestUser</b>
+ * @return String - value of member attribute <b>requestUser</b>.
+ */
+ public String getRequestUser( ) {
+ return this.requestUser;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>action</b>.
+ * You cannot set null to the attribute.
+ * @param action Value to set member attribute <b>action</b>
+ */
+ public void setAction( String action ) {
+ this.action = action;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>action</b>
+ * @return String - value of member attribute <b>action</b>.
+ */
+ public String getAction( ) {
+ return this.action;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>requestData</b>.
+ * You cannot set null to the attribute.
+ * @param requestData Value to set member attribute <b>requestData</b>
+ */
+ public void setRequestData( String requestData ) {
+ this.requestData = requestData;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>requestData</b>
+ * @return String - value of member attribute <b>requestData</b>.
+ */
+ public String getRequestData( ) {
+ return this.requestData;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>resourcePath</b>.
+ * You cannot set null to the attribute.
+ * @param resourcePath Value to set member attribute <b>resourcePath</b>
+ */
+ public void setResourcePath( String resourcePath ) {
+ this.resourcePath = resourcePath;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>resourcePath</b>
+ * @return String - value of member attribute <b>resourcePath</b>.
+ */
+ public String getResourcePath( ) {
+ return this.resourcePath;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>resourceType</b>.
+ * You cannot set null to the attribute.
+ * @param resourceType Value to set member attribute <b>resourceType</b>
+ */
+ public void setResourceType( String resourceType ) {
+ this.resourceType = resourceType;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>resourceType</b>
+ * @return String - value of member attribute <b>resourceType</b>.
+ */
+ public String getResourceType( ) {
+ return this.resourceType;
+ }
+
+ /**
+ * This return the bean content in string format
+ * @return formatedStr
+ */
+ @Override
+ public String toString( ) {
+ String str = "XXAccessAudit={";
+ str += super.toString();
+ str += "auditType={" + auditType + "} ";
+ str += "accessResult={" + accessResult + "} ";
+ str += "accessType={" + accessType + "} ";
+ str += "aclEnforcer={" + aclEnforcer + "} ";
+ str += "agentId={" + agentId + "} ";
+ str += "clientIP={" + clientIP + "} ";
+ str += "clientType={" + clientType + "} ";
+ str += "policyId={" + policyId + "} ";
+ str += "repoName={" + repoName + "} ";
+ str += "repoType={" + repoType + "} ";
+ str += "resultReason={" + resultReason + "} ";
+ str += "sessionId={" + sessionId + "} ";
+ str += "eventTime={" + eventTime + "} ";
+ str += "requestUser={" + requestUser + "} ";
+ str += "action={" + action + "} ";
+ str += "requestData={" + requestData + "} ";
+ str += "resourcePath={" + resourcePath + "} ";
+ str += "resourceType={" + resourceType + "} ";
+ str += "}";
+ return str;
+ }
+
+ /**
+ * Checks for all attributes except referenced db objects
+ * @return true if all attributes match
+ */
+ @Override
+ public boolean equals( Object obj) {
+ if ( !super.equals(obj) ) {
+ return false;
+ }
+ XXAccessAudit other = (XXAccessAudit) obj;
+ if( this.auditType != other.auditType ) return false;
+ if( this.accessResult != other.accessResult ) return false;
+ if ((this.accessType == null && other.accessType != null) || (this.accessType != null && !this.accessType.equals(other.accessType))) {
+ return false;
+ }
+ if ((this.aclEnforcer == null && other.aclEnforcer != null) || (this.aclEnforcer != null && !this.aclEnforcer.equals(other.aclEnforcer))) {
+ return false;
+ }
+ if ((this.agentId == null && other.agentId != null) || (this.agentId != null && !this.agentId.equals(other.agentId))) {
+ return false;
+ }
+ if ((this.clientIP == null && other.clientIP != null) || (this.clientIP != null && !this.clientIP.equals(other.clientIP))) {
+ return false;
+ }
+ if ((this.clientType == null && other.clientType != null) || (this.clientType != null && !this.clientType.equals(other.clientType))) {
+ return false;
+ }
+ if( this.policyId != other.policyId ) return false;
+ if ((this.repoName == null && other.repoName != null) || (this.repoName != null && !this.repoName.equals(other.repoName))) {
+ return false;
+ }
+ if( this.repoType != other.repoType ) return false;
+ if ((this.resultReason == null && other.resultReason != null) || (this.resultReason != null && !this.resultReason.equals(other.resultReason))) {
+ return false;
+ }
+ if ((this.sessionId == null && other.sessionId != null) || (this.sessionId != null && !this.sessionId.equals(other.sessionId))) {
+ return false;
+ }
+ if ((this.eventTime == null && other.eventTime != null) || (this.eventTime != null && !this.eventTime.equals(other.eventTime))) {
+ return false;
+ }
+ if ((this.requestUser == null && other.requestUser != null) || (this.requestUser != null && !this.requestUser.equals(other.requestUser))) {
+ return false;
+ }
+ if ((this.action == null && other.action != null) || (this.action != null && !this.action.equals(other.action))) {
+ return false;
+ }
+ if ((this.requestData == null && other.requestData != null) || (this.requestData != null && !this.requestData.equals(other.requestData))) {
+ return false;
+ }
+ if ((this.resourcePath == null && other.resourcePath != null) || (this.resourcePath != null && !this.resourcePath.equals(other.resourcePath))) {
+ return false;
+ }
+ if ((this.resourceType == null && other.resourceType != null) || (this.resourceType != null && !this.resourceType.equals(other.resourceType))) {
+ return false;
+ }
+ return true;
+ }
+ public static String getEnumName(String fieldName ) {
+ if( fieldName.equals("auditType") ) {
+ return "CommonEnums.AssetType";
+ }
+ if( fieldName.equals("accessResult") ) {
+ return "CommonEnums.AccessResult";
+ }
+ //Later TODO
+ //return super.getEnumName(fieldName);
+ return null;
+ }
+
+}
[37/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-installer/src/main/java/com/xasecure/utils/install/XmlConfigChanger.java
----------------------------------------------------------------------
diff --git a/agents-installer/src/main/java/com/xasecure/utils/install/XmlConfigChanger.java b/agents-installer/src/main/java/com/xasecure/utils/install/XmlConfigChanger.java
deleted file mode 100644
index 946ef4f..0000000
--- a/agents-installer/src/main/java/com/xasecure/utils/install/XmlConfigChanger.java
+++ /dev/null
@@ -1,494 +0,0 @@
-/*
- * 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 com.xasecure.utils.install;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileReader;
-import java.io.IOException;
-import java.util.Properties;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-
-import org.apache.commons.cli.BasicParser;
-import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.CommandLineParser;
-import org.apache.commons.cli.HelpFormatter;
-import org.apache.commons.cli.Option;
-import org.apache.commons.cli.OptionBuilder;
-import org.apache.commons.cli.Options;
-import org.apache.commons.cli.ParseException;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.SAXException;
-
-public class XmlConfigChanger {
-
- private static final String EMPTY_TOKEN = "%EMPTY%" ;
- private static final String EMPTY_TOKEN_VALUE = "" ;
-
- public static final String ROOT_NODE_NAME = "configuration" ;
- public static final String NAME_NODE_NAME = "name" ;
- public static final String PROPERTY_NODE_NAME = "property" ;
- public static final String VALUE_NODE_NAME = "value" ;
-
- private File inpFile ;
- private File outFile ;
- private File confFile ;
- private File propFile ;
-
- private Document doc ;
-
-
-
- public static void main(String[] args) {
- XmlConfigChanger xmlConfigChanger = new XmlConfigChanger() ;
- xmlConfigChanger.parseConfig(args);
- try {
- xmlConfigChanger.run();
- }
- catch(Throwable t) {
- System.err.println("*************************************************************************") ;
- System.err.println("******* ERROR: unable to process xml configuration changes due to error:" + t.getMessage()) ;
- t.printStackTrace();
- System.err.println("*************************************************************************") ;
- System.exit(1);
- }
- }
-
-
-
-
- @SuppressWarnings("static-access")
- public void parseConfig(String[] args) {
-
-
- Options options = new Options();
-
- Option inputOption = OptionBuilder.hasArgs(1).isRequired().withLongOpt("input").withDescription("Input xml file name").create('i');
- options.addOption(inputOption);
-
- Option outputOption = OptionBuilder.hasArgs(1).isRequired().withLongOpt("output").withDescription("Output xml file name").create('o');
- options.addOption(outputOption);
-
- Option configOption = OptionBuilder.hasArgs(1).isRequired().withLongOpt("config").withDescription("Config file name").create('c');
- options.addOption(configOption);
-
- Option installPropOption = OptionBuilder.hasArgs(1).isRequired(false).withLongOpt("installprop").withDescription("install.properties").create('p');
- options.addOption(installPropOption);
-
- CommandLineParser parser = new BasicParser();
- CommandLine cmd = null ;
- try {
- cmd = parser.parse(options, args);
- } catch (ParseException e) {
- String header = "ERROR: " + e ;
- HelpFormatter helpFormatter = new HelpFormatter();
- helpFormatter.printHelp("java " + XmlConfigChanger.class.getName(), header, options, null, true);
- System.exit(1);
- }
-
- String inputFileName = cmd.getOptionValue('i') ;
- this.inpFile = new File(inputFileName) ;
- if (! this.inpFile.canRead()) {
- String header = "ERROR: Input file [" + this.inpFile.getAbsolutePath() + "] can not be read.";
- HelpFormatter helpFormatter = new HelpFormatter();
- helpFormatter.printHelp("java " + XmlConfigChanger.class.getName(), header, options, null, true);
- System.exit(1);
- }
-
- String outputFileName = cmd.getOptionValue('o') ;
- this.outFile = new File(outputFileName) ;
- if (this.outFile.exists()) {
- String header = "ERROR: Output file [" + this.outFile.getAbsolutePath() + "] already exists. Specify a filepath for creating new output file for the input [" + this.inpFile.getAbsolutePath() + "]";
- HelpFormatter helpFormatter = new HelpFormatter();
- helpFormatter.printHelp("java " + XmlConfigChanger.class.getName(), header, options, null, true);
- System.exit(1);
- }
-
- String configFileName = cmd.getOptionValue('c') ;
- this.confFile = new File(configFileName) ;
- if (! this.confFile.canRead()) {
- String header = "ERROR: Config file [" + this.confFile.getAbsolutePath() + "] can not be read.";
- HelpFormatter helpFormatter = new HelpFormatter();
- helpFormatter.printHelp("java " + XmlConfigChanger.class.getName(), header, options, null, true);
- System.exit(1);
- }
-
- String installPropFileName = (cmd.hasOption('p') ? cmd.getOptionValue('p') : null ) ;
- if (installPropFileName != null) {
- this.propFile = new File(installPropFileName) ;
- if (! this.propFile.canRead()) {
- String header = "ERROR: Install Property file [" + this.propFile.getAbsolutePath() + "] can not be read.";
- HelpFormatter helpFormatter = new HelpFormatter();
- helpFormatter.printHelp("java " + XmlConfigChanger.class.getName(), header, options, null, true);
- System.exit(1);
- }
- }
-
- }
-
-
-
-
- public void run() throws ParserConfigurationException, SAXException, IOException, TransformerException {
-
-
- loadInstallProperties() ;
-
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance() ;
- DocumentBuilder builder = factory.newDocumentBuilder() ;
- doc = builder.parse(inpFile) ;
-
- BufferedReader reader = null ;
- try {
- reader = new BufferedReader(new FileReader(confFile)) ;
-
- String line = null ;
-
- @SuppressWarnings("unused")
- int lineNo = 0 ;
-
- while ((line = reader.readLine()) != null) {
-
- lineNo++ ;
-
- line = line.trim() ;
-
- if (line.isEmpty() )
- continue ;
- if (line.startsWith("#")) {
- continue ;
- }
-
- if (line.contains("#")) {
- int len = line.indexOf("#") ;
- line = line.substring(0,len) ;
- }
-
- String[] tokens = line.split("\\s+") ;
-
- String propName = tokens[0] ;
-
- String propValue = null ;
-
- try {
- propValue = replaceProp(tokens[1],installProperties) ;
- } catch (ValidationException e) {
- // throw new RuntimeException("Unable to replace tokens in the line: \n[" + line + "]\n in file [" + confFile.getAbsolutePath() + "] line number:[" + lineNo + "]" ) ;
- throw new RuntimeException(e) ;
- }
-
-
-
- String actionType = tokens[2] ;
- String options = (tokens.length > 3 ? tokens[3] : null) ;
- boolean createIfNotExists = (options != null && options.contains("create-if-not-exists")) ;
-
-
- if ("add".equals(actionType)) {
- addProperty(propName, propValue);
- }
- else if ("mod".equals(actionType)) {
- modProperty(propName, propValue,createIfNotExists);
- }
- else if ("del".equals(actionType)) {
- delProperty(propName);
- }
- else if ("append".equals(actionType)) {
- String curVal = getProperty(propName) ;
- if (curVal == null) {
- if (createIfNotExists) {
- addProperty(propName, propValue);
- }
- }
- else {
- String appendDelimitor = (tokens.length > 4 ? tokens[4] : " ") ;
- if (! curVal.contains(propValue)) {
- String newVal = null ;
- if (curVal.length() == 0) {
- newVal = propValue ;
- }
- else {
- newVal = curVal + appendDelimitor + propValue ;
- }
- modProperty(propName, newVal,createIfNotExists) ;
- }
- }
- }
- else if ("delval".equals(actionType)) {
- String curVal = getProperty(propName) ;
- if (curVal != null) {
- String appendDelimitor = (tokens.length > 4 ? tokens[4] : " ") ;
- if (curVal.contains(propValue)) {
- String[] valTokens = curVal.split(appendDelimitor) ;
- StringBuilder sb = new StringBuilder() ;
- for(String v : valTokens) {
- if (! v.equals(propValue)) {
- if (sb.length() > 0) {
- sb.append(appendDelimitor) ;
- }
- sb.append(v);
- }
- }
- String newVal = sb.toString() ;
- modProperty(propName, newVal,createIfNotExists) ;
- }
- }
- }
- else {
- throw new RuntimeException("Unknown Command Found: [" + actionType + "], Supported Types: add modify del append") ;
- }
-
- }
-
- TransformerFactory tfactory = TransformerFactory.newInstance() ;
- Transformer transformer = tfactory.newTransformer() ;
- transformer.setOutputProperty(OutputKeys.INDENT, "yes");
- transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
-
- DOMSource source = new DOMSource(doc) ;
- FileOutputStream out = new FileOutputStream(outFile) ;
- StreamResult result = new StreamResult(out) ;
- transformer.transform(source, result);
- out.close();
-
- }
- finally {
- if (reader != null) {
- reader.close();
- }
- }
-
- }
-
-
- private void addProperty(String propName, String val) {
- NodeList nl = doc.getElementsByTagName(ROOT_NODE_NAME) ;
- Node rootConfig = nl.item(0) ;
- rootConfig.appendChild(createNewElement(propName,val)) ;
- }
-
- private void modProperty(String propName, String val, boolean createIfNotExists) {
- Node node = findProperty(propName) ;
- if (node != null) {
- NodeList cnl = node.getChildNodes() ;
- for (int j = 0 ; j < cnl.getLength() ; j++) {
- String nodeName = cnl.item(j).getNodeName() ;
- if (nodeName.equals(VALUE_NODE_NAME)) {
- if (cnl.item(j).hasChildNodes()) {
- cnl.item(j).getChildNodes().item(0).setNodeValue(val);
- }
- else {
- Node propValueNode = cnl.item(j) ;
- Node txtNode = doc.createTextNode(val) ;
- propValueNode.appendChild(txtNode) ;
- txtNode.setNodeValue(val);
- }
- return ;
- }
- }
- }
- if (createIfNotExists) {
- addProperty(propName, val);
- }
- }
-
- private String getProperty(String propName) {
- String ret = null;
- try {
- Node node = findProperty(propName) ;
- if (node != null) {
- NodeList cnl = node.getChildNodes() ;
- for (int j = 0 ; j < cnl.getLength() ; j++) {
- String nodeName = cnl.item(j).getNodeName() ;
- if (nodeName.equals(VALUE_NODE_NAME)) {
- Node valueNode = null ;
- if (cnl.item(j).hasChildNodes()) {
- valueNode = cnl.item(j).getChildNodes().item(0) ;
- }
- if (valueNode == null) { // Value Node is defined with
- ret = "" ;
- }
- else {
- ret = valueNode.getNodeValue() ;
- }
- break ;
- }
- }
- }
- }
- catch(Throwable t) {
- throw new RuntimeException("getProperty(" + propName + ") failed.", t) ;
- }
- return ret ;
- }
-
-
- private void delProperty(String propName) {
- Node node = findProperty(propName) ;
- if (node != null) {
- node.getParentNode().removeChild(node) ;
- }
- }
-
-
- private Node findProperty(String propName) {
- Node ret = null;
- try {
- NodeList nl = doc.getElementsByTagName(PROPERTY_NODE_NAME) ;
-
- for(int i = 0 ; i < nl.getLength() ; i++) {
- NodeList cnl = nl.item(i).getChildNodes();
- boolean found = false ;
- for (int j = 0 ; j < cnl.getLength() ; j++) {
- String nodeName = cnl.item(j).getNodeName() ;
- if (nodeName.equals(NAME_NODE_NAME)) {
- String pName = cnl.item(j).getChildNodes().item(0).getNodeValue() ;
- found = pName.equals(propName) ;
- if (found)
- break ;
- }
- }
- if (found) {
- ret = nl.item(i) ;
- break;
- }
- }
- }
- catch(Throwable t) {
- throw new RuntimeException("findProperty(" + propName + ") failed.", t) ;
- }
- return ret ;
- }
-
-
- private Element createNewElement(String propName, String val) {
- Element ret = null ;
-
- try {
- if (doc != null) {
- ret = doc.createElement(PROPERTY_NODE_NAME) ;
- Node propNameNode = doc.createElement(NAME_NODE_NAME) ;
- Node txtNode = doc.createTextNode(propName) ;
- propNameNode.appendChild(txtNode) ;
- propNameNode.setNodeValue(propName);
- ret.appendChild(propNameNode);
-
- Node propValueNode = doc.createElement(VALUE_NODE_NAME) ;
- txtNode = doc.createTextNode(val) ;
- propValueNode.appendChild(txtNode) ;
- propValueNode.setNodeValue(propName);
- ret.appendChild(propValueNode);
- }
- }
- catch(Throwable t) {
- throw new RuntimeException("createNewElement(" + propName + ") with value [" + val + "] failed.", t) ;
- }
-
-
- return ret ;
- }
-
-
- Properties installProperties = new Properties() ;
-
- private void loadInstallProperties() throws IOException {
- if (propFile != null) {
- FileInputStream in = new FileInputStream(propFile) ;
- installProperties.load(in);
- }
- // To support environment variable, we will add all environment variables to the Properties
- installProperties.putAll(System.getenv());
- }
-
-
- private String replaceProp(String propValue, Properties prop) throws ValidationException {
-
- StringBuilder tokensb = new StringBuilder() ;
- StringBuilder retsb = new StringBuilder() ;
- boolean isToken = false ;
-
- for(char c : propValue.toCharArray()) {
- if (c == '%') {
- if (isToken) {
- String token = tokensb.toString();
- String tokenValue = (token.length() == 0 ? "%" : prop.getProperty(token) ) ;
- if (tokenValue == null || tokenValue.trim().isEmpty()) {
- throw new ValidationException("ERROR: configuration token [" + token + "] is not defined in the file: [" + (propFile != null ? propFile.getAbsolutePath() : "{no install.properties file specified using -p option}") + "]") ;
- }
- else {
- if (EMPTY_TOKEN.equals(tokenValue)) {
- retsb.append(EMPTY_TOKEN_VALUE) ;
- }
- else {
- retsb.append(tokenValue) ;
- }
- }
- isToken = false;
- }
- else {
- isToken = true ;
- tokensb.setLength(0);
- }
- }
- else if (isToken) {
- tokensb.append(String.valueOf(c)) ;
- }
- else {
- retsb.append(String.valueOf(c)) ;
- }
- }
-
- if (isToken) {
- throw new ValidationException("ERROR: configuration has a token defined without end-token [" + propValue + "] in the file: [" + (propFile != null ? propFile.getAbsolutePath() : "{no install.properties file specified using -p option}") + "]") ;
- }
-
- return retsb.toString();
- }
-
-
- @SuppressWarnings("serial")
- class ValidationException extends Exception {
-
- public ValidationException(String msg) {
- super(msg);
- }
-
- public ValidationException(Throwable cause) {
- super(cause);
- }
-
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-installer/src/main/java/org/apache/ranger/utils/install/PasswordGenerator.java
----------------------------------------------------------------------
diff --git a/agents-installer/src/main/java/org/apache/ranger/utils/install/PasswordGenerator.java b/agents-installer/src/main/java/org/apache/ranger/utils/install/PasswordGenerator.java
new file mode 100644
index 0000000..3632c1a
--- /dev/null
+++ b/agents-installer/src/main/java/org/apache/ranger/utils/install/PasswordGenerator.java
@@ -0,0 +1,141 @@
+/*
+ * 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.utils.install;
+
+import java.util.ArrayList;
+import java.util.Random;
+
+public class PasswordGenerator {
+
+
+ private int minimumPasswordLength = 8 ;
+
+ private int maximumPasswordLength = 12 ;
+
+ private boolean isExpectedNumberic = true ;
+
+ private boolean isExpectedBothCase = true ;
+
+ private static final ArrayList<Character> alphaLetters = new ArrayList<Character>() ;
+
+ private static final ArrayList<Character> alphaUpperLetters = new ArrayList<Character>() ;
+
+ private static final ArrayList<Character> numericLetters = new ArrayList<Character>() ;
+
+
+ static {
+ for(int x = 'a' ; x <= 'z' ; x++) {
+ char v = (char)x ;
+ alphaLetters.add(Character.toLowerCase(v)) ;
+ alphaUpperLetters.add(Character.toUpperCase(v)) ;
+ }
+ for(int i = 0 ; i < 10 ; i++) {
+ numericLetters.add(Character.forDigit(i,10)) ;
+ }
+ }
+
+
+
+ public static void main(String[] args) {
+ PasswordGenerator pg = new PasswordGenerator() ;
+ System.out.println(pg.generatorPassword()) ;
+ }
+
+
+ private int getPasswordLength() {
+ int ret = 0;
+
+ if (minimumPasswordLength == maximumPasswordLength) {
+ ret = minimumPasswordLength ;
+ }
+ else {
+
+ int diff = Math.abs(maximumPasswordLength - minimumPasswordLength) + 1 ;
+ ret = minimumPasswordLength + new Random().nextInt(diff) ;
+ }
+ return (ret) ;
+ }
+
+
+ public String generatorPassword() {
+
+ String password = null ;
+
+ ArrayList<Character> all = new ArrayList<Character>() ;
+
+ all.addAll(alphaLetters) ;
+ all.addAll(alphaUpperLetters) ;
+ all.addAll(numericLetters) ;
+
+ int len = getPasswordLength() ;
+
+ Random random = new Random() ;
+
+ int setSz = all.size();
+
+ do
+ {
+ StringBuilder sb = new StringBuilder();
+
+ for(int i = 0 ; i < len ; i++) {
+ int index = random.nextInt(setSz) ;
+ Character c = all.get(index) ;
+ while ((i == 0) && Character.isDigit(c)) {
+ index = random.nextInt(setSz) ;
+ c = all.get(index) ;
+ }
+ sb.append(all.get(index)) ;
+ }
+ password = sb.toString() ;
+ } while (! isValidPassword(password)) ;
+
+
+ return password ;
+
+ }
+
+ private boolean isValidPassword(String pass) {
+ boolean ret = true ;
+
+ if (isExpectedNumberic || isExpectedBothCase) {
+ boolean lowerCaseFound = false ;
+ boolean digitFound = false ;
+ boolean upperCaseFound = false ;
+ for(char c : pass.toCharArray()) {
+ if (!digitFound && Character.isDigit(c)) {
+ digitFound = true ;
+ }
+ else if (!lowerCaseFound && Character.isLowerCase(c)) {
+ lowerCaseFound = true ;
+ }
+ else if (!upperCaseFound && Character.isUpperCase(c) ) {
+ upperCaseFound = true ;
+ }
+ }
+
+ if (isExpectedNumberic && !digitFound) {
+ ret = false ;
+ }
+
+ if (isExpectedBothCase && (!lowerCaseFound || !upperCaseFound)) {
+ ret = false ;
+ }
+ }
+
+ return ret ;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-installer/src/main/java/org/apache/ranger/utils/install/XmlConfigChanger.java
----------------------------------------------------------------------
diff --git a/agents-installer/src/main/java/org/apache/ranger/utils/install/XmlConfigChanger.java b/agents-installer/src/main/java/org/apache/ranger/utils/install/XmlConfigChanger.java
new file mode 100644
index 0000000..9c5fb6f
--- /dev/null
+++ b/agents-installer/src/main/java/org/apache/ranger/utils/install/XmlConfigChanger.java
@@ -0,0 +1,494 @@
+/*
+ * 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.utils.install;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.Properties;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+
+import org.apache.commons.cli.BasicParser;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.OptionBuilder;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.SAXException;
+
+public class XmlConfigChanger {
+
+ private static final String EMPTY_TOKEN = "%EMPTY%" ;
+ private static final String EMPTY_TOKEN_VALUE = "" ;
+
+ public static final String ROOT_NODE_NAME = "configuration" ;
+ public static final String NAME_NODE_NAME = "name" ;
+ public static final String PROPERTY_NODE_NAME = "property" ;
+ public static final String VALUE_NODE_NAME = "value" ;
+
+ private File inpFile ;
+ private File outFile ;
+ private File confFile ;
+ private File propFile ;
+
+ private Document doc ;
+
+
+
+ public static void main(String[] args) {
+ XmlConfigChanger xmlConfigChanger = new XmlConfigChanger() ;
+ xmlConfigChanger.parseConfig(args);
+ try {
+ xmlConfigChanger.run();
+ }
+ catch(Throwable t) {
+ System.err.println("*************************************************************************") ;
+ System.err.println("******* ERROR: unable to process xml configuration changes due to error:" + t.getMessage()) ;
+ t.printStackTrace();
+ System.err.println("*************************************************************************") ;
+ System.exit(1);
+ }
+ }
+
+
+
+
+ @SuppressWarnings("static-access")
+ public void parseConfig(String[] args) {
+
+
+ Options options = new Options();
+
+ Option inputOption = OptionBuilder.hasArgs(1).isRequired().withLongOpt("input").withDescription("Input xml file name").create('i');
+ options.addOption(inputOption);
+
+ Option outputOption = OptionBuilder.hasArgs(1).isRequired().withLongOpt("output").withDescription("Output xml file name").create('o');
+ options.addOption(outputOption);
+
+ Option configOption = OptionBuilder.hasArgs(1).isRequired().withLongOpt("config").withDescription("Config file name").create('c');
+ options.addOption(configOption);
+
+ Option installPropOption = OptionBuilder.hasArgs(1).isRequired(false).withLongOpt("installprop").withDescription("install.properties").create('p');
+ options.addOption(installPropOption);
+
+ CommandLineParser parser = new BasicParser();
+ CommandLine cmd = null ;
+ try {
+ cmd = parser.parse(options, args);
+ } catch (ParseException e) {
+ String header = "ERROR: " + e ;
+ HelpFormatter helpFormatter = new HelpFormatter();
+ helpFormatter.printHelp("java " + XmlConfigChanger.class.getName(), header, options, null, true);
+ System.exit(1);
+ }
+
+ String inputFileName = cmd.getOptionValue('i') ;
+ this.inpFile = new File(inputFileName) ;
+ if (! this.inpFile.canRead()) {
+ String header = "ERROR: Input file [" + this.inpFile.getAbsolutePath() + "] can not be read.";
+ HelpFormatter helpFormatter = new HelpFormatter();
+ helpFormatter.printHelp("java " + XmlConfigChanger.class.getName(), header, options, null, true);
+ System.exit(1);
+ }
+
+ String outputFileName = cmd.getOptionValue('o') ;
+ this.outFile = new File(outputFileName) ;
+ if (this.outFile.exists()) {
+ String header = "ERROR: Output file [" + this.outFile.getAbsolutePath() + "] already exists. Specify a filepath for creating new output file for the input [" + this.inpFile.getAbsolutePath() + "]";
+ HelpFormatter helpFormatter = new HelpFormatter();
+ helpFormatter.printHelp("java " + XmlConfigChanger.class.getName(), header, options, null, true);
+ System.exit(1);
+ }
+
+ String configFileName = cmd.getOptionValue('c') ;
+ this.confFile = new File(configFileName) ;
+ if (! this.confFile.canRead()) {
+ String header = "ERROR: Config file [" + this.confFile.getAbsolutePath() + "] can not be read.";
+ HelpFormatter helpFormatter = new HelpFormatter();
+ helpFormatter.printHelp("java " + XmlConfigChanger.class.getName(), header, options, null, true);
+ System.exit(1);
+ }
+
+ String installPropFileName = (cmd.hasOption('p') ? cmd.getOptionValue('p') : null ) ;
+ if (installPropFileName != null) {
+ this.propFile = new File(installPropFileName) ;
+ if (! this.propFile.canRead()) {
+ String header = "ERROR: Install Property file [" + this.propFile.getAbsolutePath() + "] can not be read.";
+ HelpFormatter helpFormatter = new HelpFormatter();
+ helpFormatter.printHelp("java " + XmlConfigChanger.class.getName(), header, options, null, true);
+ System.exit(1);
+ }
+ }
+
+ }
+
+
+
+
+ public void run() throws ParserConfigurationException, SAXException, IOException, TransformerException {
+
+
+ loadInstallProperties() ;
+
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance() ;
+ DocumentBuilder builder = factory.newDocumentBuilder() ;
+ doc = builder.parse(inpFile) ;
+
+ BufferedReader reader = null ;
+ try {
+ reader = new BufferedReader(new FileReader(confFile)) ;
+
+ String line = null ;
+
+ @SuppressWarnings("unused")
+ int lineNo = 0 ;
+
+ while ((line = reader.readLine()) != null) {
+
+ lineNo++ ;
+
+ line = line.trim() ;
+
+ if (line.isEmpty() )
+ continue ;
+ if (line.startsWith("#")) {
+ continue ;
+ }
+
+ if (line.contains("#")) {
+ int len = line.indexOf("#") ;
+ line = line.substring(0,len) ;
+ }
+
+ String[] tokens = line.split("\\s+") ;
+
+ String propName = tokens[0] ;
+
+ String propValue = null ;
+
+ try {
+ propValue = replaceProp(tokens[1],installProperties) ;
+ } catch (ValidationException e) {
+ // throw new RuntimeException("Unable to replace tokens in the line: \n[" + line + "]\n in file [" + confFile.getAbsolutePath() + "] line number:[" + lineNo + "]" ) ;
+ throw new RuntimeException(e) ;
+ }
+
+
+
+ String actionType = tokens[2] ;
+ String options = (tokens.length > 3 ? tokens[3] : null) ;
+ boolean createIfNotExists = (options != null && options.contains("create-if-not-exists")) ;
+
+
+ if ("add".equals(actionType)) {
+ addProperty(propName, propValue);
+ }
+ else if ("mod".equals(actionType)) {
+ modProperty(propName, propValue,createIfNotExists);
+ }
+ else if ("del".equals(actionType)) {
+ delProperty(propName);
+ }
+ else if ("append".equals(actionType)) {
+ String curVal = getProperty(propName) ;
+ if (curVal == null) {
+ if (createIfNotExists) {
+ addProperty(propName, propValue);
+ }
+ }
+ else {
+ String appendDelimitor = (tokens.length > 4 ? tokens[4] : " ") ;
+ if (! curVal.contains(propValue)) {
+ String newVal = null ;
+ if (curVal.length() == 0) {
+ newVal = propValue ;
+ }
+ else {
+ newVal = curVal + appendDelimitor + propValue ;
+ }
+ modProperty(propName, newVal,createIfNotExists) ;
+ }
+ }
+ }
+ else if ("delval".equals(actionType)) {
+ String curVal = getProperty(propName) ;
+ if (curVal != null) {
+ String appendDelimitor = (tokens.length > 4 ? tokens[4] : " ") ;
+ if (curVal.contains(propValue)) {
+ String[] valTokens = curVal.split(appendDelimitor) ;
+ StringBuilder sb = new StringBuilder() ;
+ for(String v : valTokens) {
+ if (! v.equals(propValue)) {
+ if (sb.length() > 0) {
+ sb.append(appendDelimitor) ;
+ }
+ sb.append(v);
+ }
+ }
+ String newVal = sb.toString() ;
+ modProperty(propName, newVal,createIfNotExists) ;
+ }
+ }
+ }
+ else {
+ throw new RuntimeException("Unknown Command Found: [" + actionType + "], Supported Types: add modify del append") ;
+ }
+
+ }
+
+ TransformerFactory tfactory = TransformerFactory.newInstance() ;
+ Transformer transformer = tfactory.newTransformer() ;
+ transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+ transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
+
+ DOMSource source = new DOMSource(doc) ;
+ FileOutputStream out = new FileOutputStream(outFile) ;
+ StreamResult result = new StreamResult(out) ;
+ transformer.transform(source, result);
+ out.close();
+
+ }
+ finally {
+ if (reader != null) {
+ reader.close();
+ }
+ }
+
+ }
+
+
+ private void addProperty(String propName, String val) {
+ NodeList nl = doc.getElementsByTagName(ROOT_NODE_NAME) ;
+ Node rootConfig = nl.item(0) ;
+ rootConfig.appendChild(createNewElement(propName,val)) ;
+ }
+
+ private void modProperty(String propName, String val, boolean createIfNotExists) {
+ Node node = findProperty(propName) ;
+ if (node != null) {
+ NodeList cnl = node.getChildNodes() ;
+ for (int j = 0 ; j < cnl.getLength() ; j++) {
+ String nodeName = cnl.item(j).getNodeName() ;
+ if (nodeName.equals(VALUE_NODE_NAME)) {
+ if (cnl.item(j).hasChildNodes()) {
+ cnl.item(j).getChildNodes().item(0).setNodeValue(val);
+ }
+ else {
+ Node propValueNode = cnl.item(j) ;
+ Node txtNode = doc.createTextNode(val) ;
+ propValueNode.appendChild(txtNode) ;
+ txtNode.setNodeValue(val);
+ }
+ return ;
+ }
+ }
+ }
+ if (createIfNotExists) {
+ addProperty(propName, val);
+ }
+ }
+
+ private String getProperty(String propName) {
+ String ret = null;
+ try {
+ Node node = findProperty(propName) ;
+ if (node != null) {
+ NodeList cnl = node.getChildNodes() ;
+ for (int j = 0 ; j < cnl.getLength() ; j++) {
+ String nodeName = cnl.item(j).getNodeName() ;
+ if (nodeName.equals(VALUE_NODE_NAME)) {
+ Node valueNode = null ;
+ if (cnl.item(j).hasChildNodes()) {
+ valueNode = cnl.item(j).getChildNodes().item(0) ;
+ }
+ if (valueNode == null) { // Value Node is defined with
+ ret = "" ;
+ }
+ else {
+ ret = valueNode.getNodeValue() ;
+ }
+ break ;
+ }
+ }
+ }
+ }
+ catch(Throwable t) {
+ throw new RuntimeException("getProperty(" + propName + ") failed.", t) ;
+ }
+ return ret ;
+ }
+
+
+ private void delProperty(String propName) {
+ Node node = findProperty(propName) ;
+ if (node != null) {
+ node.getParentNode().removeChild(node) ;
+ }
+ }
+
+
+ private Node findProperty(String propName) {
+ Node ret = null;
+ try {
+ NodeList nl = doc.getElementsByTagName(PROPERTY_NODE_NAME) ;
+
+ for(int i = 0 ; i < nl.getLength() ; i++) {
+ NodeList cnl = nl.item(i).getChildNodes();
+ boolean found = false ;
+ for (int j = 0 ; j < cnl.getLength() ; j++) {
+ String nodeName = cnl.item(j).getNodeName() ;
+ if (nodeName.equals(NAME_NODE_NAME)) {
+ String pName = cnl.item(j).getChildNodes().item(0).getNodeValue() ;
+ found = pName.equals(propName) ;
+ if (found)
+ break ;
+ }
+ }
+ if (found) {
+ ret = nl.item(i) ;
+ break;
+ }
+ }
+ }
+ catch(Throwable t) {
+ throw new RuntimeException("findProperty(" + propName + ") failed.", t) ;
+ }
+ return ret ;
+ }
+
+
+ private Element createNewElement(String propName, String val) {
+ Element ret = null ;
+
+ try {
+ if (doc != null) {
+ ret = doc.createElement(PROPERTY_NODE_NAME) ;
+ Node propNameNode = doc.createElement(NAME_NODE_NAME) ;
+ Node txtNode = doc.createTextNode(propName) ;
+ propNameNode.appendChild(txtNode) ;
+ propNameNode.setNodeValue(propName);
+ ret.appendChild(propNameNode);
+
+ Node propValueNode = doc.createElement(VALUE_NODE_NAME) ;
+ txtNode = doc.createTextNode(val) ;
+ propValueNode.appendChild(txtNode) ;
+ propValueNode.setNodeValue(propName);
+ ret.appendChild(propValueNode);
+ }
+ }
+ catch(Throwable t) {
+ throw new RuntimeException("createNewElement(" + propName + ") with value [" + val + "] failed.", t) ;
+ }
+
+
+ return ret ;
+ }
+
+
+ Properties installProperties = new Properties() ;
+
+ private void loadInstallProperties() throws IOException {
+ if (propFile != null) {
+ FileInputStream in = new FileInputStream(propFile) ;
+ installProperties.load(in);
+ }
+ // To support environment variable, we will add all environment variables to the Properties
+ installProperties.putAll(System.getenv());
+ }
+
+
+ private String replaceProp(String propValue, Properties prop) throws ValidationException {
+
+ StringBuilder tokensb = new StringBuilder() ;
+ StringBuilder retsb = new StringBuilder() ;
+ boolean isToken = false ;
+
+ for(char c : propValue.toCharArray()) {
+ if (c == '%') {
+ if (isToken) {
+ String token = tokensb.toString();
+ String tokenValue = (token.length() == 0 ? "%" : prop.getProperty(token) ) ;
+ if (tokenValue == null || tokenValue.trim().isEmpty()) {
+ throw new ValidationException("ERROR: configuration token [" + token + "] is not defined in the file: [" + (propFile != null ? propFile.getAbsolutePath() : "{no install.properties file specified using -p option}") + "]") ;
+ }
+ else {
+ if (EMPTY_TOKEN.equals(tokenValue)) {
+ retsb.append(EMPTY_TOKEN_VALUE) ;
+ }
+ else {
+ retsb.append(tokenValue) ;
+ }
+ }
+ isToken = false;
+ }
+ else {
+ isToken = true ;
+ tokensb.setLength(0);
+ }
+ }
+ else if (isToken) {
+ tokensb.append(String.valueOf(c)) ;
+ }
+ else {
+ retsb.append(String.valueOf(c)) ;
+ }
+ }
+
+ if (isToken) {
+ throw new ValidationException("ERROR: configuration has a token defined without end-token [" + propValue + "] in the file: [" + (propFile != null ? propFile.getAbsolutePath() : "{no install.properties file specified using -p option}") + "]") ;
+ }
+
+ return retsb.toString();
+ }
+
+
+ @SuppressWarnings("serial")
+ class ValidationException extends Exception {
+
+ public ValidationException(String msg) {
+ super(msg);
+ }
+
+ public ValidationException(Throwable cause) {
+ super(cause);
+ }
+
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/credentialbuilder/.gitignore
----------------------------------------------------------------------
diff --git a/credentialbuilder/.gitignore b/credentialbuilder/.gitignore
index 0f63015..de3a426 100644
--- a/credentialbuilder/.gitignore
+++ b/credentialbuilder/.gitignore
@@ -1,2 +1,3 @@
/target/
/bin/
+/bin/
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/credentialbuilder/src/main/java/com/hortonworks/credentialapi/CredentialReader.java
----------------------------------------------------------------------
diff --git a/credentialbuilder/src/main/java/com/hortonworks/credentialapi/CredentialReader.java b/credentialbuilder/src/main/java/com/hortonworks/credentialapi/CredentialReader.java
deleted file mode 100644
index f0627ae..0000000
--- a/credentialbuilder/src/main/java/com/hortonworks/credentialapi/CredentialReader.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * 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 com.hortonworks.credentialapi;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.security.alias.CredentialProvider;
-import org.apache.hadoop.security.alias.CredentialProviderFactory;
-import org.apache.hadoop.security.alias.JavaKeyStoreProvider;
-
-public class CredentialReader {
-
- public static String getDecryptedString(String CrendentialProviderPath,String alias) {
- String credential=null;
- try{
- if(CrendentialProviderPath==null || alias==null){
- return null;
- }
- char[] pass = null;
- Configuration conf = new Configuration();
- String crendentialProviderPrefix=JavaKeyStoreProvider.SCHEME_NAME + "://file";
- crendentialProviderPrefix=crendentialProviderPrefix.toLowerCase();
- CrendentialProviderPath=CrendentialProviderPath.trim();
- alias=alias.trim();
- if(CrendentialProviderPath.toLowerCase().startsWith(crendentialProviderPrefix)){
- conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
- //UserProvider.SCHEME_NAME + ":///," +
- CrendentialProviderPath);
- }else{
- if(CrendentialProviderPath.startsWith("/")){
- conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
- //UserProvider.SCHEME_NAME + ":///," +
- JavaKeyStoreProvider.SCHEME_NAME + "://file" + CrendentialProviderPath);
- }else{
- conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
- //UserProvider.SCHEME_NAME + ":///," +
- JavaKeyStoreProvider.SCHEME_NAME + "://file/" + CrendentialProviderPath);
- }
- }
- List<CredentialProvider> providers = CredentialProviderFactory.getProviders(conf);
- List<String> aliasesList=new ArrayList<String>();
- CredentialProvider.CredentialEntry credEntry=null;
- for(CredentialProvider provider: providers) {
- //System.out.println("Credential Provider :" + provider);
- aliasesList=provider.getAliases();
- if(aliasesList!=null && aliasesList.contains(alias.toLowerCase())){
- credEntry=null;
- credEntry= provider.getCredentialEntry(alias);
- pass = credEntry.getCredential();
- if(pass!=null && pass.length>0){
- credential=String.valueOf(pass);
- break;
- }
- }
- }
- }catch(Exception ex){
- ex.printStackTrace();
- credential=null;
- }
- return credential;
- }
-
- /*
- public static void main(String args[]) throws Exception{
- String keystoreFile =new String("/tmp/mykey3.jceks");
- String password=CredentialReader.getDecryptedString(keystoreFile, "mykey3");
- System.out.println(password);
- }*/
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/credentialbuilder/src/main/java/com/hortonworks/credentialapi/buildks.java
----------------------------------------------------------------------
diff --git a/credentialbuilder/src/main/java/com/hortonworks/credentialapi/buildks.java b/credentialbuilder/src/main/java/com/hortonworks/credentialapi/buildks.java
deleted file mode 100644
index 717fba2..0000000
--- a/credentialbuilder/src/main/java/com/hortonworks/credentialapi/buildks.java
+++ /dev/null
@@ -1,433 +0,0 @@
-/*
- * 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 com.hortonworks.credentialapi;
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.security.alias.CredentialShell;
-import org.apache.hadoop.util.GenericOptionsParser;
-
-public class buildks {
- public static void main(String[] args) {
- buildks buildksOBJ=new buildks();
- String command=null;
- try{
- if(args!=null && args.length>=3){
- command=args[0];
- if(command!=null && !command.trim().isEmpty()){
- if(command.equalsIgnoreCase("create")){
- buildksOBJ.createCredential(args);
- }else if(command.equalsIgnoreCase("list")){
- buildksOBJ.listCredential(args);
- }else if(command.equalsIgnoreCase("get")){
- String credential=buildksOBJ.getCredential(args);
- if(credential!=null){
- System.out.println(credential);
- System.exit(0);
- }else{
- System.exit(1);
- }
- }else{
- System.out.println(command +" is not supported in current version of CredentialBuilder API.");
- System.exit(1);
- }
- }
- }else{
- System.out.println("Invalid Command line argument.");
- System.exit(1);
- }
- }catch(Exception ex){
- ex.printStackTrace();
- System.exit(1);
- }
- }
-
- public int createCredential(String args[]){
- int returnCode=-1;
- String command=null;
- String alias=null;
- String valueOption=null;
- String credential=null;
- String providerOption=null;
- String providerPath=null;
- String tempCredential=null;
- try{
- if(args!=null && args.length==6)
- {
- command=args[0];
- alias=args[1];
- valueOption=args[2];
- credential=args[3];
- providerOption=args[4];
- providerPath=args[5];
- if(!isValidCreateCommand(command,alias,valueOption,credential,providerOption,providerPath)){
- return returnCode;
- }
- tempCredential=CredentialReader.getDecryptedString(providerPath, alias);
- }else{
- return returnCode;
- }
-
- if(tempCredential==null){
- returnCode=createKeyStore(args);
- }else{
- try{
- System.out.println("Alias already exist!! will try to delete first.");
- String argsDelete[]=new String[4];
- argsDelete[0]="delete";
- argsDelete[1]=alias;
- argsDelete[2]=providerOption;
- argsDelete[3]=providerPath;
- returnCode=deleteCredential(argsDelete);
- if(returnCode==0){
- returnCode=createKeyStore(args);
- }
- }catch(Exception ex){
- returnCode=-1;
- }
- }
- }catch(Exception ex){
- ex.printStackTrace();
- }
- return returnCode;
- }
-
- public int createKeyStore(String args[]){
- int returnCode=-1;
- try{
- String command=null;
- String alias=null;
- String valueOption=null;
- String credential=null;
- String providerOption=null;
- String providerPath=null;
- if(args!=null && args.length==6)
- {
- command=args[0];
- alias=args[1];
- valueOption=args[2];
- credential=args[3];
- providerOption=args[4];
- providerPath=args[5];
- if(!isValidCreateCommand(command,alias,valueOption,credential,providerOption,providerPath)){
- return returnCode;
- }
- displayCommand(args);
- }else{
- return returnCode;
- }
-
- CredentialShell cs = new CredentialShell();
- Configuration conf = new Configuration();
- //parse argument
- GenericOptionsParser parser = new GenericOptionsParser(conf, args);
- //set the configuration back, so that Tool can configure itself
- cs.setConf(conf);
- //get valid and remaining argument
- String[] toolArgs = parser.getRemainingArgs();
- //execute command in CredentialShell
- // int i = 0 ;
- // for(String s : toolArgs) {
- // System.out.println("TooArgs [" + i + "] = [" + s + "]") ;
- // i++ ;
- // }
- returnCode= cs.run(toolArgs);
- //if response code is zero then success else failure
- //System.out.println("Response Code:"+returnCode);
- }catch(IOException ex){
- ex.printStackTrace();
- } catch(Exception ex){
- ex.printStackTrace();
- }
- return returnCode;
- }
- public int createCredentialFromUserInput(){
- int returnCode=-1;
- try{
- String[] args=null;
- String command=null;
- String alias=null;
- String valueOption=null;
- String credential=null;
- String providerOption=null;
- String providerPath=null;
- //below code can ask user to input if command line input fails
- System.out.println("Enter Alias Name:");
- BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
- alias = bufferRead.readLine();
- System.out.println("Enter password:");
- credential = bufferRead.readLine();
- System.out.println("Enter .jceks output file name with path:");
- providerPath = bufferRead.readLine();
- if(providerPath!=null && !providerPath.trim().isEmpty() && !providerPath.startsWith("jceks://file"))
- {
- if(providerPath.startsWith("/")){
- providerPath="jceks://file"+providerPath;
- }else{
- providerPath="jceks://file/"+providerPath;
- }
- }
- command="create";
- valueOption="-value";
- providerOption="-provider";
- if(!isValidCreateCommand(command,alias,valueOption,credential,providerOption,providerPath)){
- return returnCode;
- }
- args=new String[6];
- args[0]=command;
- args[1]=alias;
- args[2]=valueOption;
- args[3]=credential;
- args[4]=providerOption;
- args[5]=providerPath;
- CredentialShell cs = new CredentialShell();
- Configuration conf = new Configuration();
- //parse argument
- GenericOptionsParser parser = new GenericOptionsParser(conf, args);
- //set the configuration back, so that Tool can configure itself
- cs.setConf(conf);
- //get valid and remaining argument
- String[] toolArgs = parser.getRemainingArgs();
- //execute command in CredentialShell
- returnCode= cs.run(toolArgs);
- //if response code is zero then success else failure
- //System.out.println("Response Code:"+returnCode);
- }catch(IOException ex){
- ex.printStackTrace();
- } catch(Exception ex){
- ex.printStackTrace();
- }
- return returnCode;
- }
-
- public int listCredential(String args[]){
- int returnCode=-1;
- try{
- if(args!=null && args.length==3)
- {
- //display command which need to be executed or entered
- displayCommand(args);
- }else{
- return returnCode;
- }
- CredentialShell cs = new CredentialShell();
- Configuration conf = new Configuration();
- //parse argument
- GenericOptionsParser parser = new GenericOptionsParser(conf, args);
- //set the configuration back, so that Tool can configure itself
- cs.setConf(conf);
- //get valid and remaining argument
- String[] toolArgs = parser.getRemainingArgs();
- //execute command in CredentialShell
- returnCode= cs.run(toolArgs);
- //if response code is zero then success else failure
- //System.out.println("Response Code:"+returnCode);
- }catch(IOException ex){
- ex.printStackTrace();
- } catch(Exception ex){
- ex.printStackTrace();
- }
- return returnCode;
- }
-
- public int deleteCredential(String args[]){
- int returnCode=-1;
- try{
- if(args!=null && args.length==4)
- {
- //display command which need to be executed or entered
- displayCommand(args);
- }else{
- return returnCode;
- }
- CredentialShell cs = new CredentialShell();
- Configuration conf = new Configuration();
- //parse argument
- GenericOptionsParser parser = new GenericOptionsParser(conf, args);
- //set the configuration back, so that Tool can configure itself
- cs.setConf(conf);
- //get valid and remaining argument
- String[] toolArgs = parser.getRemainingArgs();
- //execute command in CredentialShell
- returnCode= cs.run(toolArgs);
- //if response code is zero then success else failure
- //System.out.println("Response Code:"+returnCode);
- }catch(IOException ex){
- ex.printStackTrace();
- } catch(Exception ex){
- ex.printStackTrace();
- }
- return returnCode;
- }
-
- public static boolean isValidCreateCommand(String command,String alias,String valueOption,String credential,String providerOption,String providerPath)
- {
- boolean isValid=true;
- try{
- if(command==null || !"create".equalsIgnoreCase(command.trim()))
- {
- System.out.println("Invalid create phrase in credential creation command!!");
- System.out.println("Expected:'create' Found:'"+command+"'");
- displaySyntax("create");
- return false;
- }
- if(alias==null || "".equalsIgnoreCase(alias.trim()))
- {
- System.out.println("Invalid alias name phrase in credential creation command!!");
- System.out.println("Found:'"+alias+"'");
- displaySyntax("create");
- return false;
- }
- if(valueOption==null || !"-value".equalsIgnoreCase(valueOption.trim()))
- {
- System.out.println("Invalid value option switch in credential creation command!!");
- System.out.println("Expected:'-value' Found:'"+valueOption+"'");
- displaySyntax("create");
- return false;
- }
- if(valueOption==null || !"-value".equalsIgnoreCase(valueOption.trim()))
- {
- System.out.println("Invalid value option in credential creation command!!");
- System.out.println("Expected:'-value' Found:'"+valueOption+"'");
- displaySyntax("create");
- return false;
- }
- if(credential==null)
- {
- System.out.println("Invalid credential value in credential creation command!!");
- System.out.println("Found:"+credential);
- displaySyntax("create");
- return false;
- }
- if(providerOption==null || !"-provider".equalsIgnoreCase(providerOption.trim()))
- {
- System.out.println("Invalid provider option in credential creation command!!");
- System.out.println("Expected:'-provider' Found:'"+providerOption+"'");
- displaySyntax("create");
- return false;
- }
- if(providerPath==null || "".equalsIgnoreCase(providerPath.trim()) || !providerPath.startsWith("jceks://"))
- {
- System.out.println("Invalid provider option in credential creation command!!");
- System.out.println("Found:'"+providerPath+"'");
- displaySyntax("create");
- return false;
- }
- }catch(Exception ex){
- System.out.println("Invalid input or runtime error! Please try again.");
- System.out.println("Input:"+command+" "+alias+" "+valueOption+" "+credential+" "+providerOption+" "+providerPath);
- displaySyntax("create");
- ex.printStackTrace();
- return false;
- }
- return isValid;
- }
-
- public static void displayCommand(String args[])
- {
- String debugOption = System.getProperty("debug") ;
- if (debugOption != null && "TRUE".equalsIgnoreCase(debugOption)) {
- StringBuffer tempBuffer=new StringBuffer("");
- if(args!=null && args.length>0){
- for(int index=0;index<args.length;index++){
- tempBuffer.append(args[index]+" ");
- }
- System.out.println("Command to execute:["+tempBuffer+"]");
- }
- }
- }
-
- public static void displaySyntax(String command){
- if(command!=null && command.trim().equalsIgnoreCase("create")){
- System.out.println("Correct syntax is:create <aliasname> -value <password> -provider <jceks://file/filepath>");
- System.out.println("sample command is:create myalias -value password123 -provider jceks://file/tmp/ks/myks.jceks");
- }
- }
- public String getCredential(String args[]){
- String command=null;
- String alias=null;
- String providerOption=null;
- String providerPath=null;
- String tempCredential=null;
- try{
- if(args!=null && args.length==4){
- command=args[0];
- alias=args[1];
- providerOption=args[2];
- providerPath=args[3];
- if(!isValidGetCommand(command,alias,providerOption,providerPath)){
- displaySyntax("get");
- }else{
- tempCredential=CredentialReader.getDecryptedString(providerPath, alias);
- }
- }else{
- displaySyntax("get");
- }
- if(tempCredential==null){
- System.out.println("Alias "+ alias +" does not exist!!");
- }
- }catch(Exception ex){
- ex.printStackTrace();
- }
- return tempCredential;
- }
-
- public static boolean isValidGetCommand(String command,String alias,String providerOption,String providerPath){
- boolean isValid=true;
- try{
- if(command==null || !"get".equalsIgnoreCase(command.trim())){
- System.out.println("Invalid get phrase in credential get command!!");
- System.out.println("Expected:'get' Found:'"+command+"'");
- displaySyntax("get");
- return false;
- }
- if(alias==null || "".equalsIgnoreCase(alias.trim()))
- {
- System.out.println("Invalid alias name phrase in credential get command!!");
- System.out.println("Found:'"+alias+"'");
- displaySyntax("get");
- return false;
- }
- if(providerOption==null || !"-provider".equalsIgnoreCase(providerOption.trim()))
- {
- System.out.println("Invalid provider option in credential get command!!");
- System.out.println("Expected:'-provider' Found:'"+providerOption+"'");
- displaySyntax("get");
- return false;
- }
- if(providerPath==null || "".equalsIgnoreCase(providerPath.trim()) || !providerPath.startsWith("jceks://"))
- {
- System.out.println("Invalid provider option in credential get command!!");
- System.out.println("Found:'"+providerPath+"'");
- displaySyntax("get");
- return false;
- }
- }catch(Exception ex){
- System.out.println("Invalid input or runtime error! Please try again.");
- System.out.println("Input:"+command+" "+alias+" "+providerOption+" "+providerPath);
- displaySyntax("get");
- ex.printStackTrace();
- return false;
- }
- return isValid;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/credentialbuilder/src/main/java/org/apache/ranger/credentialapi/CredentialReader.java
----------------------------------------------------------------------
diff --git a/credentialbuilder/src/main/java/org/apache/ranger/credentialapi/CredentialReader.java b/credentialbuilder/src/main/java/org/apache/ranger/credentialapi/CredentialReader.java
new file mode 100644
index 0000000..0b4a71a
--- /dev/null
+++ b/credentialbuilder/src/main/java/org/apache/ranger/credentialapi/CredentialReader.java
@@ -0,0 +1,87 @@
+/*
+ * 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.credentialapi;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.security.alias.CredentialProvider;
+import org.apache.hadoop.security.alias.CredentialProviderFactory;
+import org.apache.hadoop.security.alias.JavaKeyStoreProvider;
+
+public class CredentialReader {
+
+ public static String getDecryptedString(String CrendentialProviderPath,String alias) {
+ String credential=null;
+ try{
+ if(CrendentialProviderPath==null || alias==null){
+ return null;
+ }
+ char[] pass = null;
+ Configuration conf = new Configuration();
+ String crendentialProviderPrefix=JavaKeyStoreProvider.SCHEME_NAME + "://file";
+ crendentialProviderPrefix=crendentialProviderPrefix.toLowerCase();
+ CrendentialProviderPath=CrendentialProviderPath.trim();
+ alias=alias.trim();
+ if(CrendentialProviderPath.toLowerCase().startsWith(crendentialProviderPrefix)){
+ conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
+ //UserProvider.SCHEME_NAME + ":///," +
+ CrendentialProviderPath);
+ }else{
+ if(CrendentialProviderPath.startsWith("/")){
+ conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
+ //UserProvider.SCHEME_NAME + ":///," +
+ JavaKeyStoreProvider.SCHEME_NAME + "://file" + CrendentialProviderPath);
+ }else{
+ conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
+ //UserProvider.SCHEME_NAME + ":///," +
+ JavaKeyStoreProvider.SCHEME_NAME + "://file/" + CrendentialProviderPath);
+ }
+ }
+ List<CredentialProvider> providers = CredentialProviderFactory.getProviders(conf);
+ List<String> aliasesList=new ArrayList<String>();
+ CredentialProvider.CredentialEntry credEntry=null;
+ for(CredentialProvider provider: providers) {
+ //System.out.println("Credential Provider :" + provider);
+ aliasesList=provider.getAliases();
+ if(aliasesList!=null && aliasesList.contains(alias.toLowerCase())){
+ credEntry=null;
+ credEntry= provider.getCredentialEntry(alias);
+ pass = credEntry.getCredential();
+ if(pass!=null && pass.length>0){
+ credential=String.valueOf(pass);
+ break;
+ }
+ }
+ }
+ }catch(Exception ex){
+ ex.printStackTrace();
+ credential=null;
+ }
+ return credential;
+ }
+
+ /*
+ public static void main(String args[]) throws Exception{
+ String keystoreFile =new String("/tmp/mykey3.jceks");
+ String password=CredentialReader.getDecryptedString(keystoreFile, "mykey3");
+ System.out.println(password);
+ }*/
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/credentialbuilder/src/main/java/org/apache/ranger/credentialapi/buildks.java
----------------------------------------------------------------------
diff --git a/credentialbuilder/src/main/java/org/apache/ranger/credentialapi/buildks.java b/credentialbuilder/src/main/java/org/apache/ranger/credentialapi/buildks.java
new file mode 100644
index 0000000..25be1d6
--- /dev/null
+++ b/credentialbuilder/src/main/java/org/apache/ranger/credentialapi/buildks.java
@@ -0,0 +1,433 @@
+/*
+ * 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.credentialapi;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.security.alias.CredentialShell;
+import org.apache.hadoop.util.GenericOptionsParser;
+
+public class buildks {
+ public static void main(String[] args) {
+ buildks buildksOBJ=new buildks();
+ String command=null;
+ try{
+ if(args!=null && args.length>=3){
+ command=args[0];
+ if(command!=null && !command.trim().isEmpty()){
+ if(command.equalsIgnoreCase("create")){
+ buildksOBJ.createCredential(args);
+ }else if(command.equalsIgnoreCase("list")){
+ buildksOBJ.listCredential(args);
+ }else if(command.equalsIgnoreCase("get")){
+ String credential=buildksOBJ.getCredential(args);
+ if(credential!=null){
+ System.out.println(credential);
+ System.exit(0);
+ }else{
+ System.exit(1);
+ }
+ }else{
+ System.out.println(command +" is not supported in current version of CredentialBuilder API.");
+ System.exit(1);
+ }
+ }
+ }else{
+ System.out.println("Invalid Command line argument.");
+ System.exit(1);
+ }
+ }catch(Exception ex){
+ ex.printStackTrace();
+ System.exit(1);
+ }
+ }
+
+ public int createCredential(String args[]){
+ int returnCode=-1;
+ String command=null;
+ String alias=null;
+ String valueOption=null;
+ String credential=null;
+ String providerOption=null;
+ String providerPath=null;
+ String tempCredential=null;
+ try{
+ if(args!=null && args.length==6)
+ {
+ command=args[0];
+ alias=args[1];
+ valueOption=args[2];
+ credential=args[3];
+ providerOption=args[4];
+ providerPath=args[5];
+ if(!isValidCreateCommand(command,alias,valueOption,credential,providerOption,providerPath)){
+ return returnCode;
+ }
+ tempCredential=CredentialReader.getDecryptedString(providerPath, alias);
+ }else{
+ return returnCode;
+ }
+
+ if(tempCredential==null){
+ returnCode=createKeyStore(args);
+ }else{
+ try{
+ System.out.println("Alias already exist!! will try to delete first.");
+ String argsDelete[]=new String[4];
+ argsDelete[0]="delete";
+ argsDelete[1]=alias;
+ argsDelete[2]=providerOption;
+ argsDelete[3]=providerPath;
+ returnCode=deleteCredential(argsDelete);
+ if(returnCode==0){
+ returnCode=createKeyStore(args);
+ }
+ }catch(Exception ex){
+ returnCode=-1;
+ }
+ }
+ }catch(Exception ex){
+ ex.printStackTrace();
+ }
+ return returnCode;
+ }
+
+ public int createKeyStore(String args[]){
+ int returnCode=-1;
+ try{
+ String command=null;
+ String alias=null;
+ String valueOption=null;
+ String credential=null;
+ String providerOption=null;
+ String providerPath=null;
+ if(args!=null && args.length==6)
+ {
+ command=args[0];
+ alias=args[1];
+ valueOption=args[2];
+ credential=args[3];
+ providerOption=args[4];
+ providerPath=args[5];
+ if(!isValidCreateCommand(command,alias,valueOption,credential,providerOption,providerPath)){
+ return returnCode;
+ }
+ displayCommand(args);
+ }else{
+ return returnCode;
+ }
+
+ CredentialShell cs = new CredentialShell();
+ Configuration conf = new Configuration();
+ //parse argument
+ GenericOptionsParser parser = new GenericOptionsParser(conf, args);
+ //set the configuration back, so that Tool can configure itself
+ cs.setConf(conf);
+ //get valid and remaining argument
+ String[] toolArgs = parser.getRemainingArgs();
+ //execute command in CredentialShell
+ // int i = 0 ;
+ // for(String s : toolArgs) {
+ // System.out.println("TooArgs [" + i + "] = [" + s + "]") ;
+ // i++ ;
+ // }
+ returnCode= cs.run(toolArgs);
+ //if response code is zero then success else failure
+ //System.out.println("Response Code:"+returnCode);
+ }catch(IOException ex){
+ ex.printStackTrace();
+ } catch(Exception ex){
+ ex.printStackTrace();
+ }
+ return returnCode;
+ }
+ public int createCredentialFromUserInput(){
+ int returnCode=-1;
+ try{
+ String[] args=null;
+ String command=null;
+ String alias=null;
+ String valueOption=null;
+ String credential=null;
+ String providerOption=null;
+ String providerPath=null;
+ //below code can ask user to input if command line input fails
+ System.out.println("Enter Alias Name:");
+ BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
+ alias = bufferRead.readLine();
+ System.out.println("Enter password:");
+ credential = bufferRead.readLine();
+ System.out.println("Enter .jceks output file name with path:");
+ providerPath = bufferRead.readLine();
+ if(providerPath!=null && !providerPath.trim().isEmpty() && !providerPath.startsWith("jceks://file"))
+ {
+ if(providerPath.startsWith("/")){
+ providerPath="jceks://file"+providerPath;
+ }else{
+ providerPath="jceks://file/"+providerPath;
+ }
+ }
+ command="create";
+ valueOption="-value";
+ providerOption="-provider";
+ if(!isValidCreateCommand(command,alias,valueOption,credential,providerOption,providerPath)){
+ return returnCode;
+ }
+ args=new String[6];
+ args[0]=command;
+ args[1]=alias;
+ args[2]=valueOption;
+ args[3]=credential;
+ args[4]=providerOption;
+ args[5]=providerPath;
+ CredentialShell cs = new CredentialShell();
+ Configuration conf = new Configuration();
+ //parse argument
+ GenericOptionsParser parser = new GenericOptionsParser(conf, args);
+ //set the configuration back, so that Tool can configure itself
+ cs.setConf(conf);
+ //get valid and remaining argument
+ String[] toolArgs = parser.getRemainingArgs();
+ //execute command in CredentialShell
+ returnCode= cs.run(toolArgs);
+ //if response code is zero then success else failure
+ //System.out.println("Response Code:"+returnCode);
+ }catch(IOException ex){
+ ex.printStackTrace();
+ } catch(Exception ex){
+ ex.printStackTrace();
+ }
+ return returnCode;
+ }
+
+ public int listCredential(String args[]){
+ int returnCode=-1;
+ try{
+ if(args!=null && args.length==3)
+ {
+ //display command which need to be executed or entered
+ displayCommand(args);
+ }else{
+ return returnCode;
+ }
+ CredentialShell cs = new CredentialShell();
+ Configuration conf = new Configuration();
+ //parse argument
+ GenericOptionsParser parser = new GenericOptionsParser(conf, args);
+ //set the configuration back, so that Tool can configure itself
+ cs.setConf(conf);
+ //get valid and remaining argument
+ String[] toolArgs = parser.getRemainingArgs();
+ //execute command in CredentialShell
+ returnCode= cs.run(toolArgs);
+ //if response code is zero then success else failure
+ //System.out.println("Response Code:"+returnCode);
+ }catch(IOException ex){
+ ex.printStackTrace();
+ } catch(Exception ex){
+ ex.printStackTrace();
+ }
+ return returnCode;
+ }
+
+ public int deleteCredential(String args[]){
+ int returnCode=-1;
+ try{
+ if(args!=null && args.length==4)
+ {
+ //display command which need to be executed or entered
+ displayCommand(args);
+ }else{
+ return returnCode;
+ }
+ CredentialShell cs = new CredentialShell();
+ Configuration conf = new Configuration();
+ //parse argument
+ GenericOptionsParser parser = new GenericOptionsParser(conf, args);
+ //set the configuration back, so that Tool can configure itself
+ cs.setConf(conf);
+ //get valid and remaining argument
+ String[] toolArgs = parser.getRemainingArgs();
+ //execute command in CredentialShell
+ returnCode= cs.run(toolArgs);
+ //if response code is zero then success else failure
+ //System.out.println("Response Code:"+returnCode);
+ }catch(IOException ex){
+ ex.printStackTrace();
+ } catch(Exception ex){
+ ex.printStackTrace();
+ }
+ return returnCode;
+ }
+
+ public static boolean isValidCreateCommand(String command,String alias,String valueOption,String credential,String providerOption,String providerPath)
+ {
+ boolean isValid=true;
+ try{
+ if(command==null || !"create".equalsIgnoreCase(command.trim()))
+ {
+ System.out.println("Invalid create phrase in credential creation command!!");
+ System.out.println("Expected:'create' Found:'"+command+"'");
+ displaySyntax("create");
+ return false;
+ }
+ if(alias==null || "".equalsIgnoreCase(alias.trim()))
+ {
+ System.out.println("Invalid alias name phrase in credential creation command!!");
+ System.out.println("Found:'"+alias+"'");
+ displaySyntax("create");
+ return false;
+ }
+ if(valueOption==null || !"-value".equalsIgnoreCase(valueOption.trim()))
+ {
+ System.out.println("Invalid value option switch in credential creation command!!");
+ System.out.println("Expected:'-value' Found:'"+valueOption+"'");
+ displaySyntax("create");
+ return false;
+ }
+ if(valueOption==null || !"-value".equalsIgnoreCase(valueOption.trim()))
+ {
+ System.out.println("Invalid value option in credential creation command!!");
+ System.out.println("Expected:'-value' Found:'"+valueOption+"'");
+ displaySyntax("create");
+ return false;
+ }
+ if(credential==null)
+ {
+ System.out.println("Invalid credential value in credential creation command!!");
+ System.out.println("Found:"+credential);
+ displaySyntax("create");
+ return false;
+ }
+ if(providerOption==null || !"-provider".equalsIgnoreCase(providerOption.trim()))
+ {
+ System.out.println("Invalid provider option in credential creation command!!");
+ System.out.println("Expected:'-provider' Found:'"+providerOption+"'");
+ displaySyntax("create");
+ return false;
+ }
+ if(providerPath==null || "".equalsIgnoreCase(providerPath.trim()) || !providerPath.startsWith("jceks://"))
+ {
+ System.out.println("Invalid provider option in credential creation command!!");
+ System.out.println("Found:'"+providerPath+"'");
+ displaySyntax("create");
+ return false;
+ }
+ }catch(Exception ex){
+ System.out.println("Invalid input or runtime error! Please try again.");
+ System.out.println("Input:"+command+" "+alias+" "+valueOption+" "+credential+" "+providerOption+" "+providerPath);
+ displaySyntax("create");
+ ex.printStackTrace();
+ return false;
+ }
+ return isValid;
+ }
+
+ public static void displayCommand(String args[])
+ {
+ String debugOption = System.getProperty("debug") ;
+ if (debugOption != null && "TRUE".equalsIgnoreCase(debugOption)) {
+ StringBuffer tempBuffer=new StringBuffer("");
+ if(args!=null && args.length>0){
+ for(int index=0;index<args.length;index++){
+ tempBuffer.append(args[index]+" ");
+ }
+ System.out.println("Command to execute:["+tempBuffer+"]");
+ }
+ }
+ }
+
+ public static void displaySyntax(String command){
+ if(command!=null && command.trim().equalsIgnoreCase("create")){
+ System.out.println("Correct syntax is:create <aliasname> -value <password> -provider <jceks://file/filepath>");
+ System.out.println("sample command is:create myalias -value password123 -provider jceks://file/tmp/ks/myks.jceks");
+ }
+ }
+ public String getCredential(String args[]){
+ String command=null;
+ String alias=null;
+ String providerOption=null;
+ String providerPath=null;
+ String tempCredential=null;
+ try{
+ if(args!=null && args.length==4){
+ command=args[0];
+ alias=args[1];
+ providerOption=args[2];
+ providerPath=args[3];
+ if(!isValidGetCommand(command,alias,providerOption,providerPath)){
+ displaySyntax("get");
+ }else{
+ tempCredential=CredentialReader.getDecryptedString(providerPath, alias);
+ }
+ }else{
+ displaySyntax("get");
+ }
+ if(tempCredential==null){
+ System.out.println("Alias "+ alias +" does not exist!!");
+ }
+ }catch(Exception ex){
+ ex.printStackTrace();
+ }
+ return tempCredential;
+ }
+
+ public static boolean isValidGetCommand(String command,String alias,String providerOption,String providerPath){
+ boolean isValid=true;
+ try{
+ if(command==null || !"get".equalsIgnoreCase(command.trim())){
+ System.out.println("Invalid get phrase in credential get command!!");
+ System.out.println("Expected:'get' Found:'"+command+"'");
+ displaySyntax("get");
+ return false;
+ }
+ if(alias==null || "".equalsIgnoreCase(alias.trim()))
+ {
+ System.out.println("Invalid alias name phrase in credential get command!!");
+ System.out.println("Found:'"+alias+"'");
+ displaySyntax("get");
+ return false;
+ }
+ if(providerOption==null || !"-provider".equalsIgnoreCase(providerOption.trim()))
+ {
+ System.out.println("Invalid provider option in credential get command!!");
+ System.out.println("Expected:'-provider' Found:'"+providerOption+"'");
+ displaySyntax("get");
+ return false;
+ }
+ if(providerPath==null || "".equalsIgnoreCase(providerPath.trim()) || !providerPath.startsWith("jceks://"))
+ {
+ System.out.println("Invalid provider option in credential get command!!");
+ System.out.println("Found:'"+providerPath+"'");
+ displaySyntax("get");
+ return false;
+ }
+ }catch(Exception ex){
+ System.out.println("Invalid input or runtime error! Please try again.");
+ System.out.println("Input:"+command+" "+alias+" "+providerOption+" "+providerPath);
+ displaySyntax("get");
+ ex.printStackTrace();
+ return false;
+ }
+ return isValid;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/credentialbuilder/src/test/java/com/hortonworks/credentialapi/TestCredentialReader.java
----------------------------------------------------------------------
diff --git a/credentialbuilder/src/test/java/com/hortonworks/credentialapi/TestCredentialReader.java b/credentialbuilder/src/test/java/com/hortonworks/credentialapi/TestCredentialReader.java
deleted file mode 100644
index 8becce8..0000000
--- a/credentialbuilder/src/test/java/com/hortonworks/credentialapi/TestCredentialReader.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * 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 com.hortonworks.credentialapi;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import org.junit.Before;
-import org.junit.Test;
-
-public class TestCredentialReader {
- private final String keystoreFile =System.getProperty("user.home")+"/testkeystore.jceks";
- @Before
- public void setup() throws Exception {
- buildks buildksOBJ=new buildks();
- String[] argsCreateCommand = {"create", "TestCredential2", "-value", "PassworD123", "-provider", "jceks://file" + keystoreFile};
- int rc2=buildksOBJ.createCredential(argsCreateCommand);
- assertEquals( 0, rc2);
- assertTrue(rc2==0);
- }
-
- @Test
- public void testPassword() throws Exception {
- String password=CredentialReader.getDecryptedString(keystoreFile, "TestCredential2");
- assertEquals( "PassworD123", password);
- assertTrue(password,"PassworD123".equals(password));
- //delete after use
- String[] argsdeleteCommand = {"delete", "TestCredential2", "-provider", "jceks://file" + keystoreFile};
- buildks buildksOBJ=new buildks();
- buildksOBJ.deleteCredential(argsdeleteCommand);
-
- }
-
-
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/credentialbuilder/src/test/java/com/hortonworks/credentialapi/Testbuildks.java
----------------------------------------------------------------------
diff --git a/credentialbuilder/src/test/java/com/hortonworks/credentialapi/Testbuildks.java b/credentialbuilder/src/test/java/com/hortonworks/credentialapi/Testbuildks.java
deleted file mode 100644
index e4acf89..0000000
--- a/credentialbuilder/src/test/java/com/hortonworks/credentialapi/Testbuildks.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/**
- * 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 com.hortonworks.credentialapi;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import org.junit.Test;
-
-public class Testbuildks {
- private final String keystoreFile =System.getProperty("user.home")+"/testkeystore.jceks";
- @Test
- public void testBuildKSsuccess() throws Exception {
- buildks buildksOBJ=new buildks();
- String[] argsCreateCommand = {"create", "TestCredential1", "-value", "PassworD123", "-provider", "jceks://file" + keystoreFile};
- int rc1=buildksOBJ.createCredential(argsCreateCommand);
- assertEquals( 0, rc1);
- assertTrue(rc1==0);
-
- String[] argsListCommand = {"list", "-provider","jceks://file" + keystoreFile};
- int rc2=buildksOBJ.listCredential(argsListCommand);
- assertEquals(0, rc2);
- assertTrue(rc2==0);
-
- String[] argsGetCommand = {"get", "TestCredential1", "-provider", "jceks://file" +keystoreFile };
- String pw=buildksOBJ.getCredential(argsGetCommand);
- assertEquals("PassworD123", pw);
- assertTrue(pw.equals("PassworD123"));
- boolean getCredentialPassed = pw.equals("PassworD123");
-
- String[] argsDeleteCommand = {"delete", "TestCredential1", "-provider", "jceks://file" +keystoreFile };
- int rc3=buildksOBJ.deleteCredential(argsDeleteCommand);
- assertEquals(0, rc3);
- assertTrue(rc3==0);
-
- if(rc1==rc2 && rc2==rc3 && rc3==0 && getCredentialPassed){
- System.out.println("Test Case has been completed successfully..");
- }
- }
-
- @Test
- public void testInvalidProvider() throws Exception {
- buildks buildksOBJ=new buildks();
- String[] argsCreateCommand = {"create", "TestCredential1", "-value", "PassworD123", "-provider", "jksp://file"+keystoreFile};
- int rc1=buildksOBJ.createCredential(argsCreateCommand);
- assertEquals(-1, rc1);
- assertTrue(rc1==-1);
- }
-
- @Test
- public void testInvalidCommand() throws Exception {
- buildks buildksOBJ=new buildks();
- String[] argsCreateCommand = {"creat", "TestCredential1", "-value", "PassworD123", "-provider", "jksp://file"+keystoreFile};
- int rc1=buildksOBJ.createCredential(argsCreateCommand);
- assertEquals(-1, rc1);
- assertTrue(rc1==-1);
- }
- /*public static void main(String args[]) throws Exception{
- Testbuildks tTestbuildks=new Testbuildks();
- tTestbuildks.testBuildKSsuccess();
- }*/
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/credentialbuilder/src/test/java/org/apache/ranger/credentialapi/TestCredentialReader.java
----------------------------------------------------------------------
diff --git a/credentialbuilder/src/test/java/org/apache/ranger/credentialapi/TestCredentialReader.java b/credentialbuilder/src/test/java/org/apache/ranger/credentialapi/TestCredentialReader.java
new file mode 100644
index 0000000..f3e1ca8
--- /dev/null
+++ b/credentialbuilder/src/test/java/org/apache/ranger/credentialapi/TestCredentialReader.java
@@ -0,0 +1,54 @@
+/**
+ * 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.credentialapi;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import org.apache.ranger.credentialapi.CredentialReader;
+import org.apache.ranger.credentialapi.buildks;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestCredentialReader {
+ private final String keystoreFile =System.getProperty("user.home")+"/testkeystore.jceks";
+ @Before
+ public void setup() throws Exception {
+ buildks buildksOBJ=new buildks();
+ String[] argsCreateCommand = {"create", "TestCredential2", "-value", "PassworD123", "-provider", "jceks://file" + keystoreFile};
+ int rc2=buildksOBJ.createCredential(argsCreateCommand);
+ assertEquals( 0, rc2);
+ assertTrue(rc2==0);
+ }
+
+ @Test
+ public void testPassword() throws Exception {
+ String password=CredentialReader.getDecryptedString(keystoreFile, "TestCredential2");
+ assertEquals( "PassworD123", password);
+ assertTrue(password,"PassworD123".equals(password));
+ //delete after use
+ String[] argsdeleteCommand = {"delete", "TestCredential2", "-provider", "jceks://file" + keystoreFile};
+ buildks buildksOBJ=new buildks();
+ buildksOBJ.deleteCredential(argsdeleteCommand);
+
+ }
+
+
+
+
+}
[27/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/biz/AssetMgr.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/biz/AssetMgr.java b/security-admin/src/main/java/com/xasecure/biz/AssetMgr.java
deleted file mode 100644
index 521cea7..0000000
--- a/security-admin/src/main/java/com/xasecure/biz/AssetMgr.java
+++ /dev/null
@@ -1,3219 +0,0 @@
-/*
- * 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 com.xasecure.biz;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.UnknownHostException;
-import java.security.cert.X509Certificate;
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-import java.util.Set;
-import java.util.concurrent.Callable;
-import java.util.concurrent.TimeUnit;
-
-import javax.naming.InvalidNameException;
-import javax.naming.ldap.LdapName;
-import javax.naming.ldap.Rdn;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.lang.StringUtils;
-import org.apache.hadoop.hive.serde2.lazybinary.LazyBinaryUtils.VLong;
-import org.apache.hive.com.esotericsoftware.minlog.Log;
-import org.apache.log4j.Logger;
-import org.codehaus.jackson.JsonGenerationException;
-import org.codehaus.jackson.map.JsonMappingException;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.stereotype.Component;
-import org.springframework.transaction.PlatformTransactionManager;
-import org.springframework.transaction.TransactionDefinition;
-import org.springframework.transaction.TransactionStatus;
-import org.springframework.transaction.support.TransactionCallback;
-import org.springframework.transaction.support.TransactionTemplate;
-
-import com.xasecure.common.AppConstants;
-import com.xasecure.common.ContextUtil;
-import com.xasecure.common.DateUtil;
-import com.xasecure.common.JSONUtil;
-import com.xasecure.common.MessageEnums;
-import com.xasecure.common.PropertiesUtil;
-import com.xasecure.common.SearchCriteria;
-import com.xasecure.common.StringUtil;
-import com.xasecure.common.TimedEventUtil;
-import com.xasecure.common.UserSessionBase;
-import com.xasecure.common.XACommonEnums;
-import com.xasecure.common.XAConstants;
-import com.xasecure.db.XADaoManager;
-import com.xasecure.entity.XXAsset;
-import com.xasecure.entity.XXAuditMap;
-import com.xasecure.entity.XXGroup;
-import com.xasecure.entity.XXPermMap;
-import com.xasecure.entity.XXPolicyExportAudit;
-import com.xasecure.entity.XXPortalUser;
-import com.xasecure.entity.XXPortalUserRole;
-import com.xasecure.entity.XXResource;
-import com.xasecure.entity.XXTrxLog;
-import com.xasecure.entity.XXUser;
-import com.xasecure.hadoop.client.HadoopFS;
-import com.xasecure.hadoop.client.exceptions.HadoopException;
-import com.xasecure.hbase.client.HBaseClient;
-import com.xasecure.hive.client.HiveClient;
-import com.xasecure.knox.client.KnoxClient;
-import com.xasecure.service.XAccessAuditService;
-import com.xasecure.service.XAuditMapService;
-import com.xasecure.service.XGroupService;
-import com.xasecure.service.XPermMapService;
-import com.xasecure.service.XPolicyService;
-import com.xasecure.service.XTrxLogService;
-import com.xasecure.service.XUserService;
-import com.xasecure.storm.client.StormClient;
-import com.xasecure.util.RestUtil;
-import com.xasecure.view.VXAccessAuditList;
-import com.xasecure.view.VXAsset;
-import com.xasecure.view.VXAuditMap;
-import com.xasecure.view.VXAuditMapList;
-import com.xasecure.view.VXLong;
-import com.xasecure.view.VXMessage;
-import com.xasecure.view.VXPermMap;
-import com.xasecure.view.VXPermMapList;
-import com.xasecure.view.VXPolicy;
-import com.xasecure.view.VXPolicyExportAuditList;
-import com.xasecure.view.VXResource;
-import com.xasecure.view.VXResourceList;
-import com.xasecure.view.VXResponse;
-import com.xasecure.view.VXStringList;
-import com.xasecure.view.VXTrxLog;
-import com.xasecure.view.VXTrxLogList;
-import com.xasecure.view.VXUser;
-
-@Component
-public class AssetMgr extends AssetMgrBase {
-
-
- @Autowired
- XPermMapService xPermMapService;
-
- @Autowired
- XAuditMapService xAuditMapService;
-
- @Autowired
- JSONUtil jsonUtil;
-
- @Autowired
- AssetConnectionMgr assetConnectionMgr;
-
- @Autowired
- XABizUtil msBizUtil;
-
- @Autowired
- StringUtil stringUtil;
-
- @Autowired
- XADaoManager xADaoManager;
-
- @Autowired
- XUserService xUserService;
-
- @Autowired
- XABizUtil xaBizUtil;
-
- @Autowired
- XTrxLogService xTrxLogService;
-
- @Autowired
- XAccessAuditService xAccessAuditService;
-
- @Autowired
- XGroupService xGroupService;
-
- @Autowired
- XUserMgr xUserMgr;
-
- @Autowired
- @Qualifier(value = "transactionManager")
- PlatformTransactionManager txManager;
-
- @Autowired
- XPolicyService xPolicyService;
-
- static Logger logger = Logger.getLogger(AssetMgr.class);
-
- @Override
- public VXResource createXResource(VXResource vXResource) {
- UserSessionBase session = ContextUtil.getCurrentUserSession();
- if (session == null) {
- logger.error("Trying to create/update policy without log-in.");
- throw restErrorUtil.create403RESTException("Resource "
- + "creation/updation not allowed");
- }
-
- Long assetId = vXResource.getAssetId();
- XXAsset xAsset = xADaoManager.getXXAsset().getById(assetId);
- if (xAsset == null) {
- logger.error("Repository not found for assetId : " + assetId);
- throw restErrorUtil.create403RESTException("Repository for which"
- + " the policy is created, doesn't exist.");
- }
-
- if(xAsset.getActiveStatus()==XACommonEnums.ACT_STATUS_DISABLED){
- if(!session.isUserAdmin()){
- logger.error("Trying to create/update policy in disabled repository");
- throw restErrorUtil.createRESTException("Resource "
- + "creation/updation not allowed in disabled repository",MessageEnums.OPER_NO_PERMISSION);
- }
- }
- // Create resource path for HIVE/Hbase policy.
- if (xAsset.getAssetType() == AppConstants.ASSET_HIVE) {
- createResourcePathForHive(vXResource);
- } else if (xAsset.getAssetType() == AppConstants.ASSET_HBASE) {
- createResourcePathForHbase(vXResource);
- }else if (xAsset.getAssetType() == AppConstants.ASSET_KNOX) {
- createResourcePathForKnox(vXResource);
- }else if (xAsset.getAssetType() == AppConstants.ASSET_STORM) {
- createResourcePathForStorm(vXResource);
- }
-
- String resourceName = vXResource.getName();
- String[] orgResNameList = stringUtil.split(resourceName, ",");
- List<String> newResNameList = new ArrayList<String>();
- for(String resName : orgResNameList) {
- if(resName.length() > 1 && (resName.substring(resName.length()-1).equalsIgnoreCase("/"))) {
- resName = resName.substring(0, resName.length()-1);
- newResNameList.add(resName);
- logger.info("Resource Name is not valid : " +resName + " Ignoring last /");
- } else {
- newResNameList.add(resName);
- }
- }
- String updResName = StringUtils.join(newResNameList, ",");
- vXResource.setName(updResName);
-
- SearchCriteria searchCriteria=new SearchCriteria();
- searchCriteria.getParamList().put("assetId", vXResource.getAssetId());
- searchCriteria.getParamList().put("fullname", vXResource.getName());
-
- if (xAsset.getAssetType() == AppConstants.ASSET_HIVE) {
- if(stringUtil.isEmpty(vXResource.getUdfs())) {
- searchCriteria.addParam("tableType", vXResource.getTableType());
- searchCriteria.addParam("columnType", vXResource.getColumnType());
- } else {
- searchCriteria.addParam("udfs", vXResource.getUdfs());
- }
- } else if (xAsset.getAssetType() == AppConstants.ASSET_HDFS) {
- searchCriteria.addParam("isRecursive", vXResource.getIsRecursive());
- }
-
- VXResourceList vXResourceList=xResourceService.searchXResources(searchCriteria);
- if(vXResourceList!=null && vXResourceList.getListSize()>0){
- logger.error("policy already exist with resource "+vXResource.getName());
- throw restErrorUtil.createRESTException("policy already exist with resource "
- +vXResource.getName(),MessageEnums.ERROR_DUPLICATE_OBJECT);
- }
-
- VXResponse vXResponse = xaBizUtil.hasPermission(vXResource,
- AppConstants.XA_PERM_TYPE_ADMIN);
- if (vXResponse.getStatusCode() == VXResponse.STATUS_ERROR) {
- throw restErrorUtil.createRESTException(vXResponse);
- }
-
- if (vXResource.getCheckParentPermission() != XAConstants.BOOL_FALSE) {
- // check parent access for user and group
- xResourceService.checkAccess(vXResource);
- }
- vXResourceList=null;
- if(vXResource.getPolicyName()!=null && !vXResource.getPolicyName().trim().isEmpty()){
- searchCriteria=new SearchCriteria();
- searchCriteria.getParamList().put("fullPolicyName", vXResource.getPolicyName());
- vXResourceList=xResourceService.searchXResourcesWithoutLogin(searchCriteria);
- //if policyname already exist then set null to generate from system
- if(vXResourceList!=null && vXResourceList.getListSize()>0){
- logger.error("policy already exist with name "+vXResource.getPolicyName());
- //logger.info("A system generated policy name shall be assigned to "+vXResource.getPolicyName());
- //vXResource.setPolicyName(null);
- throw restErrorUtil.createRESTException("policy already exist with name "
- +vXResource.getPolicyName(),MessageEnums.ERROR_DUPLICATE_OBJECT);
- }
- }
-
- int tempPoliciesCount=0;
- String tempPolicyName=null;
- vXResourceList=null;
- if(vXResource.getPolicyName()==null ||vXResource.getPolicyName().trim().isEmpty()){
- searchCriteria=new SearchCriteria();
- searchCriteria.getParamList().put("assetId", vXResource.getAssetId());
- vXResourceList=xResourceService.searchXResourcesWithoutLogin(searchCriteria);
- if(vXResourceList!=null && vXResourceList.getListSize()>0){
- tempPoliciesCount=vXResourceList.getListSize();
- }
- vXResourceList=null;
- while(true){
- tempPoliciesCount++;
- tempPolicyName=xAsset.getName()+"-"+tempPoliciesCount+"-"+DateUtil.dateToString(DateUtil.getUTCDate(),"yyyyMMddHHmmss");
- vXResource.setPolicyName(tempPolicyName);
- searchCriteria=new SearchCriteria();
- searchCriteria.getParamList().put("policyName", vXResource.getPolicyName());
- vXResourceList=xResourceService.searchXResourcesWithoutLogin(searchCriteria);
- //if policy name not exist then list will be empty and generated policyname will valid
- if(vXResourceList==null|| vXResourceList.getListSize()==0){
- break;
- }
- }
- }
-
-
- vXResource = xResourceService.createResource(vXResource);
-
- List<VXPermMap> permMapList = vXResource.getPermMapList();
- List<VXAuditMap> auditMapList = vXResource.getAuditList();
-
- List<XXTrxLog> trxLogList = xResourceService.getTransactionLog(
- vXResource, "create");
- for (VXPermMap vXPermMap : permMapList) {
- trxLogList.addAll(xPermMapService.getTransactionLog(vXPermMap,
- "create"));
- }
- for (VXAuditMap vXAuditMap : auditMapList) {
- trxLogList.addAll(xAuditMapService.getTransactionLog(vXAuditMap,
- "create"));
- }
-
- xaBizUtil.createTrxLog(trxLogList);
-
- return vXResource;
- }
-
- @Override
- public VXResource updateXResource(VXResource vXResource) {
-
- UserSessionBase currentUserSession = ContextUtil
- .getCurrentUserSession();
- if (currentUserSession == null) {
- throw restErrorUtil.createRESTException("Resource updation not "
- + "allowed",MessageEnums.OPER_NO_PERMISSION);
- }
-
- Long assetId = vXResource.getAssetId();
- XXAsset xAsset = xADaoManager.getXXAsset().getById(assetId);
- if (xAsset == null) {
- throw restErrorUtil.createRESTException("The repository for which "
- + "you're updating policy, doesn't exist.",
- MessageEnums.INVALID_INPUT_DATA);
- }
-
- if(xAsset.getActiveStatus()==XACommonEnums.STATUS_DISABLED){
- if(!currentUserSession.isUserAdmin()){
- logger.error("Trying to update policy in disabled repository");
- throw restErrorUtil.createRESTException("Resource "
- + "updation not allowed in disabled repository",MessageEnums.OPER_NO_PERMISSION);
- }
- }
-
- if (xAsset.getAssetType() == AppConstants.ASSET_HIVE) {
- createResourcePathForHive(vXResource);
- } else if (xAsset.getAssetType() == AppConstants.ASSET_HBASE) {
- createResourcePathForHbase(vXResource);
- }else if (xAsset.getAssetType() == AppConstants.ASSET_KNOX) {
- createResourcePathForKnox(vXResource);
- }else if (xAsset.getAssetType() == AppConstants.ASSET_STORM) {
- createResourcePathForStorm(vXResource);
- }
-
- SearchCriteria searchCriteria = new SearchCriteria();
- searchCriteria.getParamList().put("assetId", vXResource.getAssetId());
- searchCriteria.getParamList().put("fullname", vXResource.getName());
-
- if (xAsset.getAssetType() == AppConstants.ASSET_HIVE) {
- if(stringUtil.isEmpty(vXResource.getUdfs())) {
- searchCriteria.addParam("tableType", vXResource.getTableType());
- searchCriteria.addParam("columnType", vXResource.getColumnType());
- } else {
- searchCriteria.addParam("udfs", vXResource.getUdfs());
- }
- } else if (xAsset.getAssetType() == AppConstants.ASSET_HDFS) {
- searchCriteria.addParam("isRecursive", vXResource.getIsRecursive());
- }
-
- VXResourceList vXResourceList=xResourceService.searchXResourcesWithoutLogin(searchCriteria);
- if(vXResourceList!=null && vXResourceList.getListSize()>0){
- if(vXResource!=null && vXResource.getId()!=null){
- for(VXResource vXResourceTemp :vXResourceList.getList()){
- if(vXResourceTemp!=null && !(vXResource.getId().equals(vXResourceTemp.getId()))){
- logger.error("policy already exists with name "+vXResource.getName());
- throw restErrorUtil.createRESTException("policy already exists with name "
- +vXResource.getName(),MessageEnums.ERROR_DUPLICATE_OBJECT);
- }
- }
- }
- }
-
- VXResponse vXResponse = xaBizUtil.hasPermission(vXResource,
- AppConstants.XA_PERM_TYPE_ADMIN);
- if (vXResponse.getStatusCode() == VXResponse.STATUS_ERROR) {
- throw restErrorUtil.createRESTException(vXResponse);
- }
-
- if (vXResource.getCheckParentPermission() != XAConstants.BOOL_FALSE) {
- // check parent access for user and group
- xResourceService.checkAccess(vXResource);
- }
-
- //policyName creation and validation logic start here
- if(vXResource.getPolicyName()!=null && !vXResource.getPolicyName().trim().isEmpty()){
- searchCriteria=new SearchCriteria();
- searchCriteria.getParamList().put("fullPolicyName", vXResource.getPolicyName());
- vXResourceList=xResourceService.searchXResourcesWithoutLogin(searchCriteria);
- if(vXResourceList!=null && vXResourceList.getListSize()>0){
- if(vXResource!=null && vXResource.getId()!=null){
- for (VXResource newVXResource : vXResourceList.getList()) {
- if(newVXResource!=null && newVXResource.getId()!=null){
- if(!vXResource.getId().equals(newVXResource.getId()) && vXResource.getPolicyName().trim().equalsIgnoreCase((newVXResource.getPolicyName()!=null?newVXResource.getPolicyName().trim():newVXResource.getPolicyName()))){
- logger.error("policy already exists with name "+vXResource.getPolicyName());
-// logger.info("A system generated policy name shall be assigned to "+vXResource.getPolicyName());
-// vXResource.setPolicyName(null);
-// break;
- throw restErrorUtil.createRESTException("policy already exists with name "
- +vXResource.getPolicyName(),MessageEnums.ERROR_DUPLICATE_OBJECT);
- }
- }
- }
- }
- }
- }
-
- int tempPoliciesCount=0;
- int totalPoliciesCount=1;
- String tempPolicyName=null;
- vXResourceList=null;
- if(vXResource!=null && (vXResource.getPolicyName()==null ||vXResource.getPolicyName().trim().isEmpty())){
- searchCriteria=new SearchCriteria();
- searchCriteria.getParamList().put("assetId", vXResource.getAssetId());
- vXResourceList=xResourceService.searchXResourcesWithoutLogin(searchCriteria);
- if(vXResourceList!=null && vXResourceList.getListSize()>0){
- totalPoliciesCount=vXResourceList.getListSize();
- tempPoliciesCount++;
- for(VXResource newVXResource : vXResourceList.getList()) {
- if(newVXResource!=null && newVXResource.getId()!=null){
- if(vXResource.getId().equals(newVXResource.getId())){
- break;
- }
- }
- tempPoliciesCount++;
- }
- tempPolicyName=xAsset.getName()+"-"+tempPoliciesCount+"-"+DateUtil.dateToString(DateUtil.getUTCDate(),"yyyyMMddHHmmss");
- vXResource.setPolicyName(tempPolicyName);
- vXResourceList=null;
- }else{
- tempPoliciesCount++;
- tempPolicyName=xAsset.getName()+"-"+tempPoliciesCount+"-"+DateUtil.dateToString(DateUtil.getUTCDate(),"yyyyMMddHHmmss");
- vXResource.setPolicyName(tempPolicyName);
- }
- while(true){
- searchCriteria=new SearchCriteria();
- searchCriteria.getParamList().put("policyName", vXResource.getPolicyName());
- vXResourceList=xResourceService.searchXResourcesWithoutLogin(searchCriteria);
- if(vXResourceList==null || vXResourceList.getListSize()==0){
- break;
- }else{
- tempPolicyName=xAsset.getName()+"-"+totalPoliciesCount+"-"+DateUtil.dateToString(DateUtil.getUTCDate(),"yyyyMMddHHmmss");
- vXResource.setPolicyName(tempPolicyName);
- }
- }
-
- }
-
- //policyName creation and validation logic end here
-
- XXResource xResouce = xADaoManager.getXXResource().getById(
- vXResource.getId());
-
- List<XXTrxLog> trxLogList = xResourceService.getTransactionLog(
- vXResource, xResouce, "update");
-
- VXResource resource = super.updateXResource(vXResource);
-
- List<VXPermMap> newPermMapList = vXResource.getPermMapList();
- searchCriteria = new SearchCriteria();
- searchCriteria.addParam("resourceId", vXResource.getId());
- VXPermMapList prevPermMaps = xPermMapService
- .searchXPermMaps(searchCriteria);
- List<VXPermMap> prevPermMapList = new ArrayList<VXPermMap>();
- if (prevPermMaps != null) {
- prevPermMapList = prevPermMaps.getVXPermMaps();
- }
-
- List<VXPermMap> permMaps = new ArrayList<VXPermMap>();
- List<VXAuditMap> auditMaps = new ArrayList<VXAuditMap>();
-
- List<VXPermMap> permMapsToDelete = new ArrayList<VXPermMap>();
- List<VXAuditMap> auditMapsToDelete = new ArrayList<VXAuditMap>();
-
- // Create and update permissions
- if (newPermMapList != null) {
- for (VXPermMap newObj : newPermMapList) {
- if (newObj.getUserId() == null && newObj.getGroupId() == null
- && !stringUtil.isEmpty(newObj.getUserName())) {
- XXUser xxUser = xADaoManager.getXXUser().findByUserName(
- newObj.getUserName());
- if (xxUser != null) {
- newObj.setUserId(xxUser.getId());
- } else {
- VXUser vxUser = new VXUser();
- vxUser.setName(newObj.getUserName());
- vxUser.setDescription(newObj.getUserName());
- vxUser = xUserService.createResource(vxUser);
- newObj.setUserId(vxUser.getId());
- }
- }
- newObj.setResourceId(resource.getId());
- if (newObj.getId() != null) {
- /**
- * Considering the new objects won't have id however the
- * existing ones will have id.
- */
- for (VXPermMap oldObj : prevPermMapList) {
- if (oldObj.getId().equals(newObj.getId())) {
- if (oldObj.getPermType() != newObj.getPermType()) {
- // This should never be the case because we're
- // not supporting perm map update.
- // doNothing...
- logger.error(
- "Invalid use case: shouldn't be happening, need to debug.",
- new IllegalStateException());
- break;
- } else {
- xPermMapService.updateResource(newObj);
- trxLogList.addAll(xPermMapService
- .getTransactionLog(newObj, oldObj,
- "update"));
- }
- }
- }
- // newObj = xPermMapService.updateResource(newObj);
- } else {
- newObj = xPermMapService.createResource(newObj);
- trxLogList.addAll(xPermMapService.getTransactionLog(newObj,
- "create"));
- }
- permMaps.add(newObj);
- }
- }
-
- // Delete old removed permissions
- if (prevPermMapList != null) {
- for (VXPermMap oldObj : prevPermMapList) {
- boolean found = false;
- if (newPermMapList != null) {
- for (VXPermMap newObj : newPermMapList) {
- if (newObj.getId() != null
- && newObj.getId().equals(oldObj.getId())) {
- found = true;
- break;
- }
- }
- }
- if (!found) {
- trxLogList.addAll(xPermMapService.getTransactionLog(oldObj,
- "delete"));
- permMapsToDelete.add(oldObj);
- // xPermMapService.deleteResource(oldObj.getId());
- }
- }
- }
-
- List<VXAuditMap> newAuditMapList = vXResource.getAuditList();
- VXAuditMapList vXAuditMaps = xAuditMapService
- .searchXAuditMaps(searchCriteria);
- List<VXAuditMap> prevAuditMapList = new ArrayList<VXAuditMap>();
- if (vXAuditMaps != null && vXAuditMaps.getResultSize() != 0) {
- prevAuditMapList = vXAuditMaps.getList();
- }
-
- // Create and update permissions
- if (newAuditMapList != null) {
- for (VXAuditMap newObj : newAuditMapList) {
- if (newObj.getId() != null) {
- /**
- * Considering the new objects won't have id however the
- * existing ones will have id.
- */
- for (VXAuditMap oldObj : prevAuditMapList) {
- if (oldObj.getId().equals(newObj.getId())
- && oldObj.getAuditType() != newObj
- .getAuditType()) {
- // This should never be the case because we're not
- // supporting perm map update.
- // doNothing...
- logger.error(
- "Invalid use case: shouldn't be happening, need to debug.",
- new IllegalStateException());
- break;
- // } else {
- // trxLogList.addAll(xAuditMapService.getTransactionLog(newObj,
- // oldObj, "update"));
- }
- }
- // newObj = xAuditMapService.updateResource(newObj);
- } else {
- newObj = xAuditMapService.createResource(newObj);
- trxLogList.addAll(xAuditMapService.getTransactionLog(
- newObj, "create"));
- }
- auditMaps.add(newObj);
- }
- }
-
- // Delete old removed permissions
- if (prevAuditMapList != null) {
- for (VXAuditMap oldObj : prevAuditMapList) {
- boolean found = false;
- if (newAuditMapList != null) {
- for (VXAuditMap newObj : newAuditMapList) {
- if (newObj.getId() != null
- && newObj.getId().equals(oldObj.getId())) {
- found = true;
- break;
- }
- }
- }
-
- if (!found) {
- trxLogList.addAll(xAuditMapService.getTransactionLog(
- oldObj, "delete"));
- auditMapsToDelete.add(oldObj);
- // xAuditMapService.deleteResource(oldObj.getId());
- }
- }
- }
-
- xaBizUtil.createTrxLog(trxLogList);
-
- for (VXPermMap permMap : permMapsToDelete) {
- xPermMapService.deleteResource(permMap.getId());
- }
-
- for (VXAuditMap auditMap : auditMapsToDelete) {
- xAuditMapService.deleteResource(auditMap.getId());
- }
- resource.setPermMapList(permMaps);
- resource.setAuditList(auditMaps);
- return resource;
- }
-
- @Override
- public void deleteXResource(Long id, boolean force) {
-
- VXResource vResource = xResourceService.readResource(id);
- UserSessionBase currentUserSession = ContextUtil
- .getCurrentUserSession();
- if (currentUserSession == null) {
- throw restErrorUtil.createRESTException("Resource deletion not "
- + "allowed",MessageEnums.OPER_NO_PERMISSION);
- }
-
- Long assetId = vResource.getAssetId();
- XXAsset xAsset = xADaoManager.getXXAsset().getById(assetId);
- if (xAsset == null) {
- throw restErrorUtil.createRESTException("The repository for which "
- + "you're deleting policy, doesn't exist.",
- MessageEnums.INVALID_INPUT_DATA);
- }
-
- if(xAsset.getActiveStatus()==XACommonEnums.STATUS_DISABLED){
- if(!currentUserSession.isUserAdmin()){
- logger.error("Trying to delete policy in disabled repository");
- throw restErrorUtil.createRESTException("Resource "
- + "deletion not allowed in disabled repository",MessageEnums.OPER_NO_PERMISSION);
- }
- }
-
- SearchCriteria searchCriteria = new SearchCriteria();
- searchCriteria.addParam("resourceId", id);
-
- VXPermMapList permMaps = xPermMapService
- .searchXPermMaps(searchCriteria);
- VXAuditMapList vXAuditMapsList = xAuditMapService
- .searchXAuditMaps(searchCriteria);
-
- List<XXTrxLog> trxLogList = xResourceService.getTransactionLog(
- vResource, "delete");
-
- for (VXPermMap vxPermMap : permMaps.getVXPermMaps()) {
- trxLogList.addAll(xPermMapService.getTransactionLog(vxPermMap,
- "delete"));
- }
-
- for (VXAuditMap vXAuditMaps : vXAuditMapsList.getVXAuditMaps()) {
- trxLogList.addAll(xAuditMapService.getTransactionLog(vXAuditMaps,
- "delete"));
- }
-
- xaBizUtil.createTrxLog(trxLogList);
-
- for (VXPermMap vxPermMap : permMaps.getVXPermMaps()) {
- xPermMapService.deleteResource(vxPermMap.getId());
- }
-
- for (VXAuditMap vXAuditMaps : vXAuditMapsList.getVXAuditMaps()) {
- xAuditMapService.deleteResource(vXAuditMaps.getId());
- }
-
- xResourceService.deleteResource(id);
- }
-
- public File getXResourceFile(Long id, String fileType) {
- VXResource xResource = xResourceService.readResource(id);
- if (xResource == null) {
- throw this.restErrorUtil.createRESTException(
- "serverMsg.datasourceIdEmpty" + "id " + id,
- MessageEnums.DATA_NOT_FOUND, id, "dataSourceId",
- "DataSource not found with " + "id " + id);
- }
- File file = null;
- try {
- if (fileType != null) {
- if (fileType.equalsIgnoreCase("json")) {
- file = jsonUtil.writeJsonToFile(xResource,
- xResource.getName());
- } else {
- throw restErrorUtil.createRESTException(
- "Please send the supported filetype.",
- MessageEnums.INVALID_INPUT_DATA);
- }
- } else {
- throw restErrorUtil
- .createRESTException(
- "Please send the file format in which you want to export.",
- MessageEnums.DATA_NOT_FOUND);
- }
- } catch (JsonGenerationException e) {
- throw this.restErrorUtil.createRESTException(
- "serverMsg.jsonGeneration" + " : " + e.getMessage(),
- MessageEnums.ERROR_SYSTEM);
- } catch (JsonMappingException e) {
- throw this.restErrorUtil.createRESTException(
- "serverMsg.jsonMapping" + " : " + e.getMessage(),
- MessageEnums.ERROR_SYSTEM);
- } catch (IOException e) {
- throw this.restErrorUtil.createRESTException(
- "serverMsg.ioException" + " : " + e.getMessage(),
- MessageEnums.ERROR_SYSTEM);
- }
-
- return file;
- }
-
- public VXStringList getHdfsResources(final String dataSourceName,
- String baseDir) {
- if (dataSourceName != null && baseDir != null) {
- List<String> strList = new ArrayList<String>();
- try {
- String wildCardToMatch;
- final HadoopFS hdfsClient = assetConnectionMgr
- .getHadoopConnection(dataSourceName);
-
- if (hdfsClient != null) {
- Integer lastIndex = baseDir.lastIndexOf("/");
- if (lastIndex < 0) {
- wildCardToMatch = baseDir + "*";
- baseDir = "/";
- } else if (lastIndex == 0 && baseDir.length() == 1) {
- wildCardToMatch = null;
- baseDir = "/";
- } else if ((lastIndex + 1) == baseDir.length()) {
- wildCardToMatch = null;
- baseDir = baseDir.substring(0, lastIndex + 1);
- } else {
- wildCardToMatch = baseDir.substring(lastIndex + 1)
- + "*";
- baseDir = baseDir.substring(0, lastIndex + 1);
- }
-
- final String finalBaseDir = baseDir;
- final String finalWildCardToMatch = wildCardToMatch;
- final Callable<List<String>> callableObj = new Callable<List<String>>() {
-
- @Override
- public List<String> call() throws Exception {
- return hdfsClient.listFiles(finalBaseDir,
- finalWildCardToMatch);
- }
-
- };
-
- strList = TimedEventUtil.timedTask(callableObj, 5,
- TimeUnit.SECONDS); // If
- // strList = hdfsClient.listFiles(finalBaseDir,
- // finalWildCardToMatch);
- logger.debug("Resource dir : " + baseDir
- + " wild card to match : " + wildCardToMatch
- + "\n Matching resources : " + strList);
- }
- } catch (Exception e) {
- logger.error("Unable to get hdfs resources.", e);
- }
-
- return msBizUtil.mapStringListToVStringList(strList);
- } else {
- return new VXStringList();
- }
- }
-
- public String getLatestRepoPolicy(String repository,
- X509Certificate[] certchain, boolean httpEnabled, String epoch,
- String ipAddress, boolean isSecure, String count, String agentId) {
-
- XXAsset xAsset = xADaoManager.getXXAsset().findByAssetName(repository);
- if(xAsset==null){
- logger.error("Requested repository not found");
- throw restErrorUtil.createRESTException("No Data Found.",
- MessageEnums.DATA_NOT_FOUND);
- }
- if(xAsset.getActiveStatus()==XACommonEnums.ACT_STATUS_DISABLED){
- logger.error("Requested repository is disabled");
- throw restErrorUtil.createRESTException("Unauthorized access.",
- MessageEnums.OPER_NO_EXPORT);
- }
-
- XXPolicyExportAudit policyExportAudit = new XXPolicyExportAudit();
- policyExportAudit.setRepositoryName(repository);
-
- if (agentId != null && !agentId.isEmpty()) {
- policyExportAudit.setAgentId(agentId);
- }
-
- policyExportAudit.setClientIP(ipAddress);
-
- if (epoch != null && !epoch.trim().isEmpty() && !epoch.equalsIgnoreCase("null")) {
- policyExportAudit.setRequestedEpoch(Long.parseLong(epoch));
- } else {
- policyExportAudit.setRequestedEpoch(0l);
- }
-
- if (!httpEnabled) {
- if (!isSecure) {
- policyExportAudit
- .setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST);
- createPolicyAudit(policyExportAudit);
-
- throw restErrorUtil.createRESTException("Unauthorized access -"
- + " only https allowed",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
-
- if (certchain == null || certchain.length == 0) {
-
- policyExportAudit
- .setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST);
- createPolicyAudit(policyExportAudit);
-
- throw restErrorUtil.createRESTException("Unauthorized access -"
- + " unable to get client certificate",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
- }
-
- Long policyCount = restErrorUtil.parseLong(count, "Invalid value for "
- + "policyCount", MessageEnums.INVALID_INPUT_DATA, null,
- "policyCount");
-
- String commonName = null;
-
- if (certchain != null) {
- X509Certificate clientCert = certchain[0];
- String dn = clientCert.getSubjectX500Principal().getName();
-
- try {
- LdapName ln = new LdapName(dn);
- for (Rdn rdn : ln.getRdns()) {
- if (rdn.getType().equalsIgnoreCase("CN")) {
- commonName = rdn.getValue() + "";
- break;
- }
- }
- if (commonName == null) {
- policyExportAudit
- .setHttpRetCode(javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST);
- createPolicyAudit(policyExportAudit);
-
- throw restErrorUtil.createRESTException(
- "Unauthorized access - Unable to find Common Name from ["
- + dn + "]",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
- } catch (InvalidNameException e) {
- policyExportAudit
- .setHttpRetCode(javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST);
- createPolicyAudit(policyExportAudit);
-
- logger.error("Invalid Common Name.", e);
- throw restErrorUtil.createRESTException(
- "Unauthorized access - Invalid Common Name",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
- }
-
- if (repository == null || repository.isEmpty()) {
-
- policyExportAudit
- .setHttpRetCode(javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST);
- createPolicyAudit(policyExportAudit);
-
- logger.error("Repository name not provided");
- throw restErrorUtil.createRESTException("Unauthorized access.",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
-
-
-
- if (xAsset == null) {
- policyExportAudit
- .setHttpRetCode(javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST);
- createPolicyAudit(policyExportAudit);
-
- logger.error("Requested repository doesn't exist");
- throw restErrorUtil.createRESTException("Unauthorized access.",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
-
- if (policyCount == null) {
- policyCount = 0l;
- }
-
- if (commonName != null) {
- String config = xAsset.getConfig();
- Map<String, String> configMap = jsonUtil.jsonToMap(config);
- String cnFromConfig = configMap.get("commonNameForCertificate");
-
- if (cnFromConfig == null
- || !commonName.equalsIgnoreCase(cnFromConfig)) {
- policyExportAudit
- .setHttpRetCode(javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST);
- createPolicyAudit(policyExportAudit);
-
- throw restErrorUtil.createRESTException(
- "Unauthorized access. expected [" + cnFromConfig
- + "], found [" + commonName + "]",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
- }
-
- // //////////////////////////////////////
- // Get latest updated time of repository
- // //////////////////////////////////////
- Timestamp luTime = xADaoManager.getXXResource()
- .getMaxUpdateTimeForAssetName(repository);
-
- HashMap<String, Object> updatedRepo = new HashMap<String, Object>();
- updatedRepo.put("repository_name", repository);
-
- Long updatedTime = 0l;
- List<HashMap<String, Object>> resourceList = new ArrayList<HashMap<String, Object>>();
-
- if (luTime != null) {
- updatedTime = luTime.getTime();
- }
-
- {
- List<XXResource> xResourceList = new ArrayList<XXResource>();
-
- long epochTime = epoch != null ? Long.parseLong(epoch) : 0;
-
- if(epochTime == updatedTime) {
- //TODO: instead of getting entire list, get just count(*) for the given repository
- xResourceList = xADaoManager.getXXResource().findUpdatedResourcesByAssetName(repository, new Date(0L));
-
- int resourceListSz = (xResourceList == null) ? 0 : xResourceList.size() ;
-
- if (policyCount == resourceListSz) {
- policyExportAudit
- .setHttpRetCode(javax.servlet.http.HttpServletResponse.SC_NOT_MODIFIED);
- createPolicyAudit(policyExportAudit);
-
- throw restErrorUtil.createRESTException(
- HttpServletResponse.SC_NOT_MODIFIED,
- "No change since last update", false);
- }
-
- } else {
- xResourceList = xADaoManager.getXXResource().findUpdatedResourcesByAssetName(repository, new Date(0L));
- }
-
-
- // HDFS Repository
- if (xAsset.getAssetType() == AppConstants.ASSET_HDFS) {
- for (XXResource xResource : xResourceList) {
- HashMap<String, Object> resourceMap = new HashMap<String, Object>();
- resourceMap.put("id", xResource.getId());
- resourceMap.put("resource", xResource.getName());
- resourceMap.put("isRecursive",
- getBooleanValue(xResource.getIsRecursive()));
- resourceMap.put("policyStatus", XACommonEnums
- .getLabelFor_ActiveStatus(xResource
- .getResourceStatus()));
- // resourceMap.put("isEncrypt",
- // AKAConstants.getLabelFor_BooleanValue(xResource.getIsEncrypt()));
- populatePermMap(xResource, resourceMap, AppConstants.ASSET_HDFS);
- List<XXAuditMap> xAuditMaps = xADaoManager.getXXAuditMap()
- .findByResourceId(xResource.getId());
- if (xAuditMaps.size() != 0) {
- resourceMap.put("audit", 1);
- } else {
- resourceMap.put("audit", 0);
- }
-
- resourceList.add(resourceMap);
- }
- } else if (xAsset.getAssetType() == AppConstants.ASSET_HIVE) {
- for (XXResource xResource : xResourceList) {
- HashMap<String, Object> resourceMap = new HashMap<String, Object>();
- resourceMap.put("id", xResource.getId());
- resourceMap.put("database_name", xResource.getDatabases());
- resourceMap.put("policyStatus", XACommonEnums
- .getLabelFor_ActiveStatus(xResource
- .getResourceStatus()));
- resourceMap.put("tablePolicyType", AppConstants
- .getLabelFor_PolicyType(xResource.getTableType()));
- resourceMap.put("columnPolicyType", AppConstants
- .getLabelFor_PolicyType(xResource.getColumnType()));
- int resourceType = xResource.getResourceType();
- if (resourceType == AppConstants.RESOURCE_UDF) {
- resourceMap.put("udf_name", xResource.getUdfs());
- } else if (resourceType == AppConstants.RESOURCE_COLUMN) {
- resourceMap.put("table_name", xResource.getTables());
- resourceMap.put("column_name", xResource.getColumns());
- } else if (resourceType == AppConstants.RESOURCE_TABLE) {
- resourceMap.put("table_name", xResource.getTables());
- }
-
- populatePermMap(xResource, resourceMap, AppConstants.ASSET_HIVE);
- List<XXAuditMap> xAuditMaps = xADaoManager.getXXAuditMap()
- .findByResourceId(xResource.getId());
- if (xAuditMaps.size() != 0) {
- resourceMap.put("audit", 1);
- } else {
- resourceMap.put("audit", 0);
- }
- resourceList.add(resourceMap);
- }
- }
-
- else if (xAsset.getAssetType() == AppConstants.ASSET_HBASE) {
- for (XXResource xResource : xResourceList) {
- HashMap<String, Object> resourceMap = new HashMap<String, Object>();
-
- resourceMap.put("id", xResource.getId());
- resourceMap.put("table_name", xResource.getTables());
- resourceMap.put("column_name", xResource.getColumns());
- resourceMap.put("column_families",
- xResource.getColumnFamilies());
- resourceMap.put("policyStatus", XACommonEnums
- .getLabelFor_ActiveStatus(xResource
- .getResourceStatus()));
- if (xResource.getIsEncrypt() == 1) {
- resourceMap.put("encrypt", 1);
- } else {
- resourceMap.put("encrypt", 0);
- }
- // resourceMap.put("isEncrypt",
- // AKAConstants.getLabelFor_BooleanValue(xResource.getIsEncrypt()));
- populatePermMap(xResource, resourceMap, AppConstants.ASSET_HBASE);
- List<XXAuditMap> xAuditMaps = xADaoManager.getXXAuditMap()
- .findByResourceId(xResource.getId());
- if (xAuditMaps.size() != 0) {
- resourceMap.put("audit", 1);
- } else {
- resourceMap.put("audit", 0);
- }
- resourceList.add(resourceMap);
- }
- }
- else if (xAsset.getAssetType() == AppConstants.ASSET_KNOX) {
- for (XXResource xResource : xResourceList) {
- HashMap<String, Object> resourceMap = new HashMap<String, Object>();
-
- resourceMap.put("id", xResource.getId());
- resourceMap.put("topology_name", xResource.getTopologies()) ;
- resourceMap.put("service_name", xResource.getServices()) ;
- resourceMap.put("policyStatus", XACommonEnums
- .getLabelFor_ActiveStatus(xResource
- .getResourceStatus()));
- if (xResource.getIsEncrypt() == 1) {
- resourceMap.put("encrypt", 1);
- } else {
- resourceMap.put("encrypt", 0);
- }
- // resourceMap.put("isEncrypt",
- // AKAConstants.getLabelFor_BooleanValue(xResource.getIsEncrypt()));
- populatePermMap(xResource, resourceMap, AppConstants.ASSET_KNOX);
- List<XXAuditMap> xAuditMaps = xADaoManager.getXXAuditMap()
- .findByResourceId(xResource.getId());
- if (xAuditMaps.size() != 0) {
- resourceMap.put("audit", 1);
- } else {
- resourceMap.put("audit", 0);
- }
- resourceList.add(resourceMap);
- }
-
- }
- else if (xAsset.getAssetType() == AppConstants.ASSET_STORM) {
- for (XXResource xResource : xResourceList) {
- HashMap<String, Object> resourceMap = new HashMap<String, Object>();
-
- resourceMap.put("id", xResource.getId());
- resourceMap.put("topology_name", xResource.getTopologies()) ;
- resourceMap.put("policyStatus", XACommonEnums
- .getLabelFor_ActiveStatus(xResource
- .getResourceStatus()));
- if (xResource.getIsEncrypt() == 1) {
- resourceMap.put("encrypt", 1);
- } else {
- resourceMap.put("encrypt", 0);
- }
- populatePermMap(xResource, resourceMap, AppConstants.ASSET_STORM);
- List<XXAuditMap> xAuditMaps = xADaoManager.getXXAuditMap()
- .findByResourceId(xResource.getId());
- if (xAuditMaps.size() != 0) {
- resourceMap.put("audit", 1);
- } else {
- resourceMap.put("audit", 0);
- }
- resourceList.add(resourceMap);
- }
- } else {
- policyExportAudit
- .setHttpRetCode(javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST);
- createPolicyAudit(policyExportAudit);
- throw restErrorUtil.createRESTException(
- "The operation isn't yet supported for the repository",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
- }
-
- policyCount = Long.valueOf(resourceList.size());
- updatedRepo.put("last_updated", updatedTime);
- updatedRepo.put("policyCount", policyCount);
- updatedRepo.put("acl", resourceList);
-
- String updatedPolicyStr = jsonUtil.readMapToString(updatedRepo);
-
-// File file = null;
-// try {
-// file = jsonUtil.writeMapToFile(updatedRepo, repository);
-// } catch (JsonGenerationException e) {
-// logger.error("Error exporting policies for repository : "
-// + repository, e);
-// } catch (JsonMappingException e) {
-// logger.error("Error exporting policies for repository : "
-// + repository, e);
-// } catch (IOException e) {
-// logger.error("Error exporting policies for repository : "
-// + repository, e);
-// }
-
- policyExportAudit
- .setHttpRetCode(javax.servlet.http.HttpServletResponse.SC_OK);
- createPolicyAudit(policyExportAudit);
-
- return updatedPolicyStr;
- }
-
- public VXStringList getHiveResources(final String dataSourceName,
- String databaseName, String tableName, String columnName) {
-
- List<String> resultList = new ArrayList<String>();
- if (dataSourceName != null) {
- final HiveClient hiveClient = assetConnectionMgr
- .getHiveConnection(dataSourceName);
-
- try {
- final Callable<List<String>> callableObj;
- final String finalDbName;
- final String finalColName;
- final String finalTableName;
-
- if (hiveClient != null && databaseName != null
- && !databaseName.isEmpty()) {
- if (tableName != null && !tableName.isEmpty()) {
- if (columnName != null && !columnName.isEmpty()) {
- columnName += "*";
- finalColName = columnName;
- finalDbName = databaseName;
- finalTableName = tableName;
-
- callableObj = new Callable<List<String>>() {
- @Override
- public List<String> call() {
- return hiveClient.getColumnList(
- finalDbName, finalTableName,
- finalColName);
- }
- };
- } else {
- tableName += "*";
- finalTableName = tableName;
- finalDbName = databaseName;
- callableObj = new Callable<List<String>>() {
-
- @Override
- public List<String> call() {
- return hiveClient.getTableList(finalDbName,
- finalTableName);
- }
-
- };
- }
- } else {
- databaseName += "*";
- finalDbName = databaseName;
- callableObj = new Callable<List<String>>() {
- @Override
- public List<String> call() {
- return hiveClient.getDatabaseList(finalDbName);
- }
- };
-
- }
-
- synchronized (hiveClient) {
- resultList = TimedEventUtil.timedTask(callableObj, 5,
- TimeUnit.SECONDS);
- }
-
- }
- } catch (Exception e) {
- logger.error("Unable to get hive resources.", e);
- }
- }
-
- return msBizUtil.mapStringListToVStringList(resultList);
- }
-
- @Override
- public VXAsset createXAsset(VXAsset vXAsset) {
- UserSessionBase usb = ContextUtil.getCurrentUserSession();
- if (usb != null && usb.isUserAdmin()) {
-
- String defaultConfig = vXAsset.getConfig();
- defaultConfig=xAssetService.getConfigWithEncryptedPassword(defaultConfig,false);
- vXAsset.setConfig(defaultConfig);
- VXAsset createdVXAsset = (VXAsset) xAssetService
- .createResource(vXAsset);
- String udpatedConfig = vXAsset.getConfig();
- createdVXAsset.setConfig(defaultConfig);
-
- createDefaultPolicy(createdVXAsset, vXAsset.getConfig());
- createDefaultUDFPolicy(createdVXAsset, vXAsset.getConfig());
- createdVXAsset.setConfig(udpatedConfig);
-
- List<XXTrxLog> trxLogList = xAssetService.getTransactionLog(
- createdVXAsset, "create");
- xaBizUtil.createTrxLog(trxLogList);
- return createdVXAsset;
- } else {
- logger.debug("User id : " + usb.getUserId() + " doesn't have "
- + "admin access to create repository.");
- throw restErrorUtil
- .createRESTException(
- "Sorry, you don't have permission to perform the operation",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
- }
-
- private void createDefaultPolicy(VXAsset vXAsset, String config) {
- int assetType = vXAsset.getAssetType();
-
- Map<String, String> configMap = jsonUtil.jsonToMap(config);
- String userName = stringUtil.getValidUserName(configMap.get("username"));
-
- VXResource vXResource = new VXResource();
- vXResource.setAssetId(vXAsset.getId());
- vXResource.setAssetName(vXAsset.getName());
- vXResource.setResourceStatus(AppConstants.STATUS_ENABLED);
- String tempPolicyName=vXAsset.getName()+"-"+1+"-"+DateUtil.dateToString(DateUtil.getUTCDate(),"yyyyMMddHHmmss");
- vXResource.setPolicyName(tempPolicyName);
- if (assetType == AppConstants.ASSET_HDFS) {
- vXResource.setName("/");
- vXResource.setIsRecursive(AppConstants.BOOL_TRUE);
- vXResource.setResourceType(AppConstants.RESOURCE_PATH);
- } else if (assetType == AppConstants.ASSET_HIVE) {
- vXResource.setDatabases("*");
- vXResource.setTables("*");
- vXResource.setColumns("*");
- vXResource.setName("/*/*/*");
- vXResource.setResourceType(AppConstants.RESOURCE_COLUMN);
- } else if (assetType == AppConstants.ASSET_HBASE) {
- vXResource.setTables("*");
- vXResource.setColumnFamilies("*");
- vXResource.setColumns("*");
- vXResource.setName("/*/*/*");
- vXResource.setResourceType(AppConstants.RESOURCE_COLUMN);
- } else if (assetType == AppConstants.ASSET_KNOX) {
- vXResource.setTopologies("*");
- vXResource.setServices("*");
- vXResource.setName("/*/*");
- vXResource.setResourceType(AppConstants.RESOURCE_SERVICE_NAME);
- } else if (assetType == AppConstants.ASSET_STORM) {
- vXResource.setTopologies("*");
- vXResource.setName("/*");
- vXResource.setResourceType(AppConstants.RESOURCE_TOPOLOGY);
- }
-
- vXResource = xResourceService.createResource(vXResource);
-
- if (userName != null && !userName.isEmpty()) {
- XXUser xxUser = xADaoManager.getXXUser().findByUserName(userName);
- VXUser vXUser;
- if (xxUser != null) {
- vXUser = xUserService.populateViewBean(xxUser);
- } else {
- vXUser = new VXUser();
- vXUser.setName(userName);
- vXUser.setUserSource(XACommonEnums.USER_EXTERNAL);
- vXUser=xUserMgr.createXUser(vXUser);
- //vXUser = xUserService.createResource(vXUser);
- }
-
- Random rand = new Random();
- String permGrp = new Date() + " : " + rand.nextInt(9999);
-
- VXPermMap vXPermMap = new VXPermMap();
- vXPermMap.setUserId(vXUser.getId());
- vXPermMap.setResourceId(vXResource.getId());
- vXPermMap.setPermGroup(permGrp);
- xPermMapService.createResource(vXPermMap);
-
- if (assetType == AppConstants.ASSET_KNOX) {
- String permGroup = new Date() + " : " + rand.nextInt(9999);
-
- VXPermMap permAdmin = new VXPermMap();
- permAdmin.setPermFor(AppConstants.XA_PERM_FOR_USER);
- permAdmin.setPermType(AppConstants.XA_PERM_TYPE_ADMIN);
- permAdmin.setUserId(vXUser.getId());
- permAdmin.setPermGroup(permGroup);
- permAdmin.setResourceId(vXResource.getId());
- xPermMapService.createResource(permAdmin);
-
- VXPermMap permAllow = new VXPermMap();
- permAllow.setPermFor(AppConstants.XA_PERM_FOR_USER);
- permAllow.setPermType(AppConstants.XA_PERM_TYPE_ALLOW);
- permAllow.setUserId(vXUser.getId());
- permAllow.setPermGroup(permGroup);
- permAllow.setResourceId(vXResource.getId());
- xPermMapService.createResource(permAllow);
- }
- }
-
- VXAuditMap vXAuditMap = new VXAuditMap();
- vXAuditMap.setAuditType(AppConstants.XA_AUDIT_TYPE_ALL);
- vXAuditMap.setResourceId(vXResource.getId());
- vXAuditMap = xAuditMapService.createResource(vXAuditMap);
- vXResource=xResourceService.readResource(vXResource.getId());
- List<VXPermMap> permMapList = vXResource.getPermMapList();
- List<VXAuditMap> auditMapList = vXResource.getAuditList();
-
- List<XXTrxLog> trxLogList = xResourceService.getTransactionLog(
- vXResource, "create");
- for (VXPermMap vXPermMap : permMapList) {
- trxLogList.addAll(xPermMapService.getTransactionLog(vXPermMap,
- "create"));
- }
- for (VXAuditMap vXAuditMapObj : auditMapList) {
- trxLogList.addAll(xAuditMapService.getTransactionLog(vXAuditMapObj,
- "create"));
- }
-
- xaBizUtil.createTrxLog(trxLogList);
-
-
- }
-
- @Override
- public VXAsset updateXAsset(VXAsset vXAsset) {
- UserSessionBase usb = ContextUtil.getCurrentUserSession();
- if (usb != null && usb.isUserAdmin()) {
- String newConfig=vXAsset.getConfig();
- HashMap<String, String> configMap = (HashMap<String, String>) jsonUtil
- .jsonToMap(newConfig);
- String password = configMap.get("password");
- String hiddenPasswordString = PropertiesUtil.getProperty(
- "xa.password.hidden", "*****");
- if (password != null && !password.equals(hiddenPasswordString)) {
- String defaultConfig = vXAsset.getConfig();
- defaultConfig=xAssetService.getConfigWithEncryptedPassword(defaultConfig,true);
- vXAsset.setConfig(defaultConfig);
- }
- XXAsset xAsset = xADaoManager.getXXAsset()
- .getById(vXAsset.getId());
-
- if (xAsset.getActiveStatus() == XACommonEnums.STATUS_DELETED) {
- logger.error("Trying to update Asset which is soft deleted");
- throw restErrorUtil.createRESTException(
- "Repository that you want to update does not exist.",
- MessageEnums.DATA_NOT_FOUND, xAsset.getId(), null,
- "Repository not exist for this Id : " + xAsset.getId());
- }
-
- List<XXTrxLog> trxLogList = xAssetService.getTransactionLog(
- vXAsset, xAsset, "update");
- vXAsset = (VXAsset) xAssetService.updateResource(vXAsset);
- // update default policy permission and user
- updateDefaultPolicy(vXAsset, vXAsset.getConfig());
- // TODO this should reset the connection
- assetConnectionMgr.destroyConnection(vXAsset);
- // TODO : Log in transaction log table
- xaBizUtil.createTrxLog(trxLogList);
- return vXAsset;
- } else {
- throw restErrorUtil.createRESTException(
- "serverMsg.modelMgrBaseUpdateModel",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
- }
-
- @Override
- public void deleteXAsset(Long id, boolean force) {
- UserSessionBase usb = ContextUtil.getCurrentUserSession();
- if (usb != null && usb.isUserAdmin() && force) {
- VXAsset vxAsset = xAssetService.readResource(id);
-
- if (vxAsset.getActiveStatus() == XACommonEnums.STATUS_DELETED) {
- logger.error("Trying to delete Asset which is already soft deleted");
- throw restErrorUtil.createRESTException(
- "Repository not found or its already deleted, for Id : "
- + id, MessageEnums.DATA_NOT_FOUND, id, null,
- "Repository not exist for this Id : " + id);
- }
-
- SearchCriteria searchCriteria = new SearchCriteria();
- searchCriteria.addParam("assetId", id);
- VXResourceList resources = searchXResources(searchCriteria);
- if (resources != null && resources.getResultSize() != 0) {
- for (VXResource resource : resources.getList()) {
- deleteXResource(resource.getId(), true);
- }
- }
- vxAsset.setActiveStatus(XACommonEnums.STATUS_DELETED);
- xAssetService.updateResource(vxAsset);
- List<XXTrxLog> trxLogList = xAssetService.getTransactionLog(
- vxAsset, "delete");
- xaBizUtil.createTrxLog(trxLogList);
- } else {
- throw restErrorUtil.createRESTException(
- "serverMsg.modelMgrBaseDeleteModel",
- MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
- }
- }
-
- public VXStringList getHBaseResources(final String dataSourceName,
- String tableName, String columnFamilies) {
-
- List<String> resultList = new ArrayList<String>();
- if (dataSourceName != null) {
- final HBaseClient hBaseClient = assetConnectionMgr
- .getHBaseConnection(dataSourceName);
-
- try {
- final Callable<List<String>> callableObj;
- if (hBaseClient != null && tableName != null
- && !tableName.isEmpty()) {
- final String finalColFamilies;
- final String finalTableName;
-
- if (columnFamilies != null && !columnFamilies.isEmpty()) {
- if (!columnFamilies.endsWith("*")) {
- columnFamilies += "*";
- }
-
- columnFamilies = columnFamilies.replaceAll("\\*",
- ".\\*");
- finalColFamilies = columnFamilies;
- finalTableName = tableName;
-
- callableObj = new Callable<List<String>>() {
- @Override
- public List<String> call() {
- return hBaseClient.getColumnFamilyList(
- finalTableName, finalColFamilies);
- }
- };
-
- } else {
- if (!tableName.endsWith("*")) {
- tableName += "*";
- }
-
- tableName = tableName.replaceAll("\\*", ".\\*");
- finalTableName = tableName;
-
- callableObj = new Callable<List<String>>() {
- @Override
- public List<String> call() {
- return hBaseClient.getTableList(finalTableName);
- }
- };
-
- }
- resultList = TimedEventUtil.timedTask(callableObj, 5,
- TimeUnit.SECONDS);
- }
-
- } catch (Exception e) {
- logger.error("Unable to get hbase resources.", e);
- }
- }
-
- return msBizUtil.mapStringListToVStringList(resultList);
- }
-
- public VXStringList getKnoxResources(
- String knoxUrl,String knoxAdminUser, String knoxAdminPassword,
- String topologyName, String serviceName) {
- List<String> resultList = new ArrayList<String>();
- if (knoxUrl == null || knoxUrl.isEmpty()) {
- logger.error("Unable to get knox resources: knoxUrl is empty");
- return msBizUtil.mapStringListToVStringList(resultList);
- } else if (knoxAdminUser == null || knoxAdminUser.isEmpty()) {
- logger.error("Unable to get knox resources: knoxAdminUser is empty");
- return msBizUtil.mapStringListToVStringList(resultList);
- } else if (knoxAdminPassword == null || knoxAdminPassword.isEmpty()) {
- logger.error("Unable to get knox resources: knoxAdminPassword is empty");
- return msBizUtil.mapStringListToVStringList(resultList);
- }
-
- final KnoxClient knoxClient = assetConnectionMgr
- .getKnoxClient(knoxUrl, knoxAdminUser, knoxAdminPassword);
- VXStringList knoxResources = getKnoxResources(knoxClient, topologyName, serviceName);
- return knoxResources;
- }
-
- public VXStringList getKnoxResources(final String dataSourceName,
- String topologyName, String serviceName) {
- List<String> resultList = new ArrayList<String>();
- if (dataSourceName == null || dataSourceName.isEmpty()) {
- logger.error("Unable to get knox resources: dataSourceName is null");
- return msBizUtil.mapStringListToVStringList(resultList);
- }
-
- final KnoxClient knoxClient = assetConnectionMgr
- .getKnoxClient(dataSourceName);
- VXStringList knoxResources = getKnoxResources(knoxClient, topologyName, serviceName);
- return knoxResources;
- }
-
-
- public VXStringList getKnoxResources(final KnoxClient knoxClient,
- String topologyName, String serviceName) {
-
- List<String> resultList = new ArrayList<String>();
-
- try {
- if (knoxClient == null) {
- logger.error("Unable to get knox resources: knoxClient is null");
- return msBizUtil.mapStringListToVStringList(resultList);
- }
-
- final Callable<List<String>> callableObj;
- if (serviceName != null) {
- final String finalServiceNameMatching = serviceName.trim();
- final String finalTopologyName = topologyName;
- callableObj = new Callable<List<String>>() {
- @Override
- public List<String> call() {
- return knoxClient.getServiceList(finalTopologyName,
- finalServiceNameMatching);
- }
- };
-
- } else {
- final String finalTopologyNameMatching = (topologyName == null) ?
- "" : topologyName.trim();
- callableObj = new Callable<List<String>>() {
- @Override
- public List<String> call() {
- return knoxClient.getTopologyList(finalTopologyNameMatching);
- }
- };
- }
- resultList = TimedEventUtil.timedTask(callableObj, 5,
- TimeUnit.SECONDS);
-
- } catch (Exception e) {
- logger.error("Unable to get knox resources.", e);
- }
-
- return msBizUtil.mapStringListToVStringList(resultList);
- }
-
- public VXResponse testConfig(VXAsset vXAsset) {
-
- if (vXAsset.getActiveStatus() == XACommonEnums.STATUS_DELETED) {
- logger.error("Trying to test Asset which is soft deleted");
- throw restErrorUtil.createRESTException(
- "Repository not found, Repository Name : " + vXAsset.getName(),
- MessageEnums.DATA_NOT_FOUND, vXAsset.getId(), null,
- "Repository not exist for this Id : " + vXAsset.getId());
- }
-
- int assetType = vXAsset.getAssetType();
-
- VXResponse testResponse = new VXResponse();
- HashMap<String, Object> responseData = new HashMap<String, Object>();
-
- HashMap<String, String> configMap = (HashMap<String, String>) jsonUtil
- .jsonToMap(vXAsset.getConfig());
- String password = configMap.get("password");
- String hiddenPasswordString = PropertiesUtil.getProperty(
- "xa.password.hidden", "*****");
-
- if (password != null && password.equals(hiddenPasswordString)) {
- String assetName = vXAsset.getName();
- if (assetName != null) {
- XXAsset existingVXAsset = xADaoManager.getXXAsset()
- .findByAssetName(assetName);
- if (existingVXAsset != null
- && existingVXAsset.getConfig() != null) {
- String existingConfig = existingVXAsset.getConfig();
- existingConfig=xAssetService.getConfigWithDecryptedPassword(existingConfig);
- HashMap<String, String> existingConfigMap = (HashMap<String, String>) jsonUtil
- .jsonToMap(existingConfig);
- String existingPassword = existingConfigMap.get("password");
- if (existingPassword != null) {
- configMap.put("password", existingPassword);
- }
- }
- }
- }
-
- try {
- String dataSource = vXAsset.getName();
- if (assetType == AppConstants.ASSET_HDFS) {
- // HadoopFS connectionObj = new HadoopFS(vXAsset.getName(),
- // configMap);
- // if (connectionObj != null) {
- // List<String> testResult = connectionObj
- // .listFiles("/", null);
- // if (testResult != null && testResult.size() != 0) {
- // connectivityStatus = true;
- // }
- // }
- responseData = HadoopFS.testConnection(dataSource, configMap);
- } else if (assetType == AppConstants.ASSET_HIVE) {
- // HiveClient connectionObj = new HiveClient(vXAsset.getName(),
- // configMap);
- // if (connectionObj != null) {
- // List<String> testResult = connectionObj
- // .getDatabaseList("*");
- // if (testResult != null && testResult.size() != 0) {
- // connectivityStatus = true;
- // }
- // }
- // connectionObj.close();
- responseData = HiveClient.testConnection(dataSource, configMap);
- } else if (assetType == AppConstants.ASSET_HBASE) {
- // HBaseClient connectionObj = new
- // HBaseClient(vXAsset.getName(),
- // configMap);
- // if (connectionObj != null) {
- // connectivityStatus = connectionObj.getHBaseStatus();
- // } else {
- // Log.error("testConfig: Not able to create HBaseClient");
- // }
- responseData = HBaseClient
- .testConnection(dataSource, configMap);
- } else if (assetType == AppConstants.ASSET_KNOX) {
- // KnoxClient knoxClient = assetConnectionMgr.getKnoxClient(
- // vXAsset.getName(), configMap);
- // VXStringList vxStringList = getKnoxResources(knoxClient, "",
- // null);
- // if (vxStringList != null && (vxStringList.getListSize() !=
- // 0)) {
- // connectivityStatus = true;
- // }
- responseData = KnoxClient.testConnection(dataSource, configMap);
- } else if (assetType == AppConstants.ASSET_STORM) {
- responseData = StormClient.testConnection(dataSource, configMap);
- } else {
- throw restErrorUtil.createRESTException(
- "Invalid repository type.",
- MessageEnums.INVALID_INPUT_DATA);
- }
- testResponse = generateResponseForTestConn(responseData, "");
-
- } catch (Exception e) {
-
- String msg = "Unable to connect repository with given config for "
- + vXAsset.getName();
- HashMap<String, Object> respData = new HashMap<String, Object>();
- String message = "";
- if (e instanceof HadoopException) {
- respData = ((HadoopException) e).responseData;
- message = (respData != null && respData.get("message") != null) ? respData.get(
- "message").toString() : msg;
- }
- if(respData == null) {
- respData = new HashMap<String, Object>();
- }
- testResponse = generateResponseForTestConn(respData, message);
- logger.error(msg, e);
- }
- return testResponse;
- }
-
- private VXResponse generateResponseForTestConn(
- HashMap<String, Object> responseData, String msg) {
- VXResponse vXResponse = new VXResponse();
-
- Long objId = (responseData.get("objectId") != null) ? Long
- .parseLong(responseData.get("objectId").toString()) : null;
- boolean connectivityStatus = (responseData.get("connectivityStatus") != null) ? Boolean
- .parseBoolean(responseData.get("connectivityStatus").toString())
- : false;
- int statusCode = (connectivityStatus) ? VXResponse.STATUS_SUCCESS
- : VXResponse.STATUS_ERROR;
- String message = (responseData.get("message") != null) ? responseData
- .get("message").toString() : msg;
- String description = (responseData.get("description") != null) ? responseData
- .get("description").toString() : msg;
- String fieldName = (responseData.get("fieldName") != null) ? responseData
- .get("fieldName").toString() : null;
-
- VXMessage vXMsg = new VXMessage();
- List<VXMessage> vXMsgList = new ArrayList<VXMessage>();
- vXMsg.setFieldName(fieldName);
- vXMsg.setMessage(message);
- vXMsg.setObjectId(objId);
- vXMsgList.add(vXMsg);
-
- vXResponse.setMessageList(vXMsgList);
- vXResponse.setMsgDesc(description);
- vXResponse.setStatusCode(statusCode);
- return vXResponse;
- }
-
- private void createResourcePathForHive(VXResource vXResource) {
-
- String[] databases = (vXResource.getDatabases() == null || vXResource
- .getDatabases().equalsIgnoreCase("")) ? null : stringUtil
- .split(vXResource.getDatabases(), ",");
- String[] tables = (vXResource.getTables() == null || vXResource
- .getTables().equalsIgnoreCase("")) ? null : stringUtil.split(
- vXResource.getTables(), ",");
- String[] udfs = (vXResource.getUdfs() == null || vXResource.getUdfs()
- .equalsIgnoreCase("")) ? null : stringUtil.split(
- vXResource.getUdfs(), ",");
- String[] columns = (vXResource.getColumns() == null || vXResource
- .getColumns().equalsIgnoreCase("")) ? null : stringUtil.split(
- vXResource.getColumns(), ",");
-
- StringBuilder stringBuilder = new StringBuilder();
-
-// int resourceType = vXResource.getResourceType();
- int resourceType = xPolicyService.getResourceType(vXResource);
-
- if (databases == null) {
- logger.error("Invalid resources for hive policy.");
- throw restErrorUtil.createRESTException("Please provide the"
- + " valid resources.", MessageEnums.INVALID_INPUT_DATA);
- }
-
- switch (resourceType) {
-
- case AppConstants.RESOURCE_COLUMN:
- for (String column : columns) {
- for (String table : tables) {
- for (String database : databases) {
- stringBuilder.append("/" + database + "/" + table + "/"
- + column + ",");
- }
- }
- }
- break;
-
- case AppConstants.RESOURCE_TABLE:
- for (String table : tables) {
- for (String database : databases) {
- stringBuilder.append("/" + database + "/" + table + ",");
- }
- }
- break;
-
- case AppConstants.RESOURCE_UDF:
- for (String udf : udfs) {
- for (String database : databases) {
- stringBuilder.append("/" + database + "/" + udf + ",");
- }
- }
- break;
-
- case AppConstants.RESOURCE_DB:
- for (String database : databases) {
- stringBuilder.append("/" + database + ",");
- }
- break;
-
- default:
- logger.error("Invalid resource type : " + resourceType
- + " for hive policy.");
- throw restErrorUtil.createRESTException("Please provide the"
- + " valid resource type.", MessageEnums.INVALID_INPUT_DATA);
- }
-
- int lastIndexOfSeperator = stringBuilder.lastIndexOf(",");
- if (lastIndexOfSeperator > 0) {
- String name = stringBuilder.substring(0,
- stringBuilder.lastIndexOf(","));
- vXResource.setName(name);
- } else {
- vXResource.setName(stringBuilder.toString());
- }
- }
-
- private void createResourcePathForHbase(VXResource vXResource) {
-
- String[] tables = (vXResource.getTables() == null || vXResource
- .getTables().equalsIgnoreCase("")) ? null : stringUtil.split(
- vXResource.getTables(), ",");
- String[] columnFamilies = (vXResource.getColumnFamilies() == null || vXResource
- .getColumnFamilies().equalsIgnoreCase("")) ? null : stringUtil
- .split(vXResource.getColumnFamilies(), ",");
- String[] columns = (vXResource.getColumns() == null || vXResource
- .getColumns().equalsIgnoreCase("")) ? null : stringUtil.split(
- vXResource.getColumns(), ",");
-
- StringBuilder stringBuilder = new StringBuilder();
-
-// int resourceType = vXResource.getResourceType();
- int resourceType = xPolicyService.getResourceType(vXResource);
-
- if (tables == null) {
- logger.error("Invalid resources for hbase policy.");
- throw restErrorUtil.createRESTException("Please provide the"
- + " valid resources.", MessageEnums.INVALID_INPUT_DATA);
- }
-
- switch (resourceType) {
-
- case AppConstants.RESOURCE_COLUMN:
- for (String column : columns) {
- for (String columnFamily : columnFamilies) {
- for (String table : tables) {
- stringBuilder.append("/" + table + "/" + columnFamily
- + "/" + column + ",");
- }
- }
- }
- break;
-
- case AppConstants.RESOURCE_COL_FAM:
- for (String columnFamily : columnFamilies) {
- for (String table : tables) {
- stringBuilder
- .append("/" + table + "/" + columnFamily + ",");
- }
- }
- break;
-
- case AppConstants.RESOURCE_TABLE:
- for (String table : tables) {
- stringBuilder.append("/" + table + ",");
- }
- break;
-
- default:
- logger.error("Invalid resource type : " + resourceType
- + " for hbase policy.");
- throw restErrorUtil.createRESTException("Please provide the"
- + " valid resource type.", MessageEnums.INVALID_INPUT_DATA);
- }
-
- int lastIndexOfSeperator = stringBuilder.lastIndexOf(",");
- if (lastIndexOfSeperator > 0) {
- String name = stringBuilder.substring(0,
- stringBuilder.lastIndexOf(","));
- vXResource.setName(name);
- } else {
- vXResource.setName(stringBuilder.toString());
- }
- }
- private void createResourcePathForKnox(VXResource vXResource) {
-
- String[] topologies = (vXResource.getTopologies() == null || vXResource
- .getTopologies().equalsIgnoreCase("")) ? null : stringUtil.split(
- vXResource.getTopologies(), ",");
- String[] serviceNames = (vXResource.getServices() == null || vXResource
- .getServices().equalsIgnoreCase("")) ? null : stringUtil
- .split(vXResource.getServices(), ",");
-
- StringBuilder stringBuilder = new StringBuilder();
-
-// int resourceType = vXResource.getResourceType();
- int resourceType = xPolicyService.getResourceType(vXResource);
-
- if (topologies == null) {
- logger.error("Invalid resources for knox policy.");
- throw restErrorUtil.createRESTException("Please provide the"
- + " valid resources.", MessageEnums.INVALID_INPUT_DATA);
- }
-
- switch (resourceType) {
-
- case AppConstants.RESOURCE_SERVICE_NAME:
- for (String serviceName : serviceNames) {
- for (String topology : topologies) {
- stringBuilder
- .append("/" + topology + "/" + serviceName + ",");
- }
- }
- break;
-
- case AppConstants.RESOURCE_TOPOLOGY:
- for (String topology : topologies) {
- stringBuilder.append("/" + topology + ",");
- }
- break;
-
- default:
- logger.error("Invalid resource type : " + resourceType
- + " for hbase policy.");
- throw restErrorUtil.createRESTException("Please provide the"
- + " valid resource type.", MessageEnums.INVALID_INPUT_DATA);
- }
-
- int lastIndexOfSeperator = stringBuilder.lastIndexOf(",");
- if (lastIndexOfSeperator > 0) {
- String name = stringBuilder.substring(0,
- stringBuilder.lastIndexOf(","));
- vXResource.setName(name);
- } else {
- vXResource.setName(stringBuilder.toString());
- }
- }
- private void createResourcePathForStorm(VXResource vXResource) {
-
- String[] topologies = (vXResource.getTopologies() == null || vXResource
- .getTopologies().equalsIgnoreCase("")) ? null : stringUtil.split(
- vXResource.getTopologies(), ",");
-
- String[] serviceNames = (vXResource.getServices() == null || vXResource
- .getServices().equalsIgnoreCase("")) ? null : stringUtil
- .split(vXResource.getServices(), ",");
-
- StringBuilder stringBuilder = new StringBuilder();
-
-// int resourceType = vXResource.getResourceType();
- int resourceType = xPolicyService.getResourceType(vXResource);
-
- if (topologies == null) {
- logger.error("Invalid resources for Storm policy.");
- throw restErrorUtil.createRESTException("Please provide the"
- + " valid resources.", MessageEnums.INVALID_INPUT_DATA);
- }
-
- switch (resourceType) {
-
- case AppConstants.RESOURCE_TOPOLOGY:
- for (String topology : topologies) {
- stringBuilder.append("/" + topology + ",");
- }
- break;
-
- case AppConstants.RESOURCE_SERVICE_NAME:
- for (String serviceName : serviceNames) {
- for (String topology : topologies) {
- stringBuilder.append("/" + topology + "/" + serviceName + ",");
- }
- }
- break;
-
- default:
- logger.error("Invalid resource type : " + resourceType
- + " for Storm policy.");
- throw restErrorUtil.createRESTException("Please provide the"
- + " valid resource type.", MessageEnums.INVALID_INPUT_DATA);
- }
-
- int lastIndexOfSeperator = stringBuilder.lastIndexOf(",");
- if (lastIndexOfSeperator > 0) {
- String name = stringBuilder.substring(0,
- stringBuilder.lastIndexOf(","));
- vXResource.setName(name);
- } else {
- vXResource.setName(stringBuilder.toString());
- }
- }
- @SuppressWarnings("unchecked")
- private HashMap<String, Object> populatePermMap(XXResource xResource,
- HashMap<String, Object> resourceMap, int assetType) {
- List<XXPermMap> xPermMapList = xADaoManager.getXXPermMap()
- .findByResourceId(xResource.getId());
-
- Set<Long> groupList = new HashSet<Long>();
- for (XXPermMap xPermMap : xPermMapList) {
- groupList.add(xPermMap.getId());
- }
-
- List<HashMap<String, Object>> sortedPermMapGroupList = new ArrayList<HashMap<String, Object>>();
-
- // Loop for adding group perms
- for (XXPermMap xPermMap : xPermMapList) {
- String groupKey = xPermMap.getPermGroup();
- if (groupKey != null) {
- boolean found = false;
- for (HashMap<String, Object> sortedPermMap : sortedPermMapGroupList) {
- if (sortedPermMap.containsValue(groupKey)) {
- found = true;
-
- Long groupId = xPermMap.getGroupId();
- Long userId = xPermMap.getUserId();
-
- if (groupId != null) {
- Set<String> groups = (Set<String>) sortedPermMap
- .get("groups");
- XXGroup xGroup = xADaoManager.getXXGroup()
- .getById(groupId);
- if(xGroup!=null && groups != null){
- groups.add(xGroup.getName());
- sortedPermMap.put("groups", groups);
- }
- } else if (userId != null) {
- Set<String> users = (Set<String>) sortedPermMap
- .get("users");
- XXUser xUser = xADaoManager.getXXUser().getById(
- userId);
- if (users != null && xUser != null) {
- users.add(xUser.getName());
- sortedPermMap.put("users", users);
- }
- }
-
- Set<String> access = (Set<String>) sortedPermMap
- .get("access");
- String perm = AppConstants
- .getLabelFor_XAPermType(xPermMap.getPermType());
- access.add(perm);
- sortedPermMap.put("access", access);
- }
- }
- if (!found) {
- HashMap<String, Object> sortedPermMap = new HashMap<String, Object>();
- sortedPermMap.put("groupKey", xPermMap.getPermGroup());
-
- Set<String> permSet = new HashSet<String>();
- String perm = AppConstants.getLabelFor_XAPermType(xPermMap
- .getPermType());
- permSet.add(perm);
-
- sortedPermMap.put("access", permSet);
-
- if(assetType == AppConstants.ASSET_KNOX){
- String[] ipAddrList = new String[0];
- if(xPermMap.getIpAddress() != null){
- ipAddrList = xPermMap.getIpAddress().split(",");
- sortedPermMap.put("ipAddress", ipAddrList);
- }else
- sortedPermMap.put("ipAddress",ipAddrList);
- }
-
- Long groupId = xPermMap.getGroupId();
- Long userId = xPermMap.getUserId();
-
- if (groupId != null) {
- Set<String> groupSet = new HashSet<String>();
- XXGroup xGroup = xADaoManager.getXXGroup().getById(
- xPermMap.getGroupId());
- String group = xGroup.getName();
- groupSet.add(group);
- sortedPermMap.put("groups", groupSet);
- } else if (userId != null) {
- Set<String> userSet = new HashSet<String>();
- XXUser xUser = xADaoManager.getXXUser()
- .getById(userId);
- String user = xUser.getName();
- userSet.add(user);
- sortedPermMap.put("users", userSet);
- }
-
- sortedPermMapGroupList.add(sortedPermMap);
- }
- }
- }
-
- for (HashMap<String, Object> sortedPermMap : sortedPermMapGroupList) {
- sortedPermMap.remove("groupKey");
- }
-
- for (HashMap<String, Object> sortedPermMap : sortedPermMapGroupList) {
- sortedPermMap.remove("groupKey");
- }
-
- resourceMap.put("permission", sortedPermMapGroupList);
- return resourceMap;
- }
-
- private String getBooleanValue(int elementValue) {
- if (elementValue == 1) {
- return "1"; // BOOL_TRUE
- }
- return "0"; // BOOL_FALSE
- }
-
- public void updateDefaultPolicy(VXAsset vXAsset, String config) {
- int assetType = vXAsset.getAssetType();
- Map<String, String> configMap = jsonUtil.jsonToMap(config);
- String userName = stringUtil.getValidUserName(configMap.get("username"));
- VXResource vxResource = fetchDefaultPolicyForAsset(vXAsset.getId(),
- assetType);
- if (vxResource != null) {
- UpdateDefaultPolicyUserAndPerm(vxResource, userName);
- }
- }
-
- public void UpdateDefaultPolicyUserAndPerm(VXResource vXResource,
- String userName) {
- if (userName != null && !userName.isEmpty()) {
- XXUser xxUser = xADaoManager.getXXUser().findByUserName(userName);
- VXUser vXUser;
- if (xxUser != null) {
- vXUser = xUserService.populateViewBean(xxUser);
- } else {
- vXUser = new VXUser();
- vXUser.setName(userName);
- // FIXME hack : unnecessary.
- vXUser.setDescription(userName);
- vXUser = xUserService.createResource(vXUser);
- }
- // fetch old permission and consider only one permission for default
- // policy
- List<XXPermMap> xxPermMapList = xADaoManager.getXXPermMap()
- .findByResourceId(vXResource.getId());
- VXPermMap vXPermMap = null;
- if (xxPermMapList != null && xxPermMapList.size() != 0) {
- vXPermMap = xPermMapService.populateViewBean(xxPermMapList
- .get(0));
- }
-
- if (vXPermMap == null) {
- // create new permission
- vXPermMap = new VXPermMap();
- vXPermMap.setUserId(vXUser.getId());
- vXPermMap.setResourceId(vXResource.getId());
- } else {
- // update old permission after updating userid
- vXPermMap.setUserId(vXUser.getId());
- xPermMapService.updateResource(vXPermMap);
- }
-
- }
-
- }
-
- public VXResource fetchDefaultPolicyForAsset(Long assetId, int assetType) {
- String resourceName = "";
- List<XXResource> xxResourceList = new ArrayList<XXResource>();
- if (assetType == AppConstants.ASSET_HDFS) {
- resourceName = "/*";
- xxResourceList = xADaoManager.getXXResource()
- .findByResourceNameAndAssetIdAndRecursiveFlag(resourceName,
- assetId, AppConstants.BOOL_TRUE);
- } else if (assetType == AppConstants.ASSET_HIVE) {
- resourceName = "/*/*/*";
- xxResourceList = xADaoManager.getXXResource()
- .findByResourceNameAndAssetIdAndResourceType(resourceName,
- assetId, AppConstants.RESOURCE_UNKNOWN);
- } else if (assetType == AppConstants.ASSET_HBASE) {
- resourceName = "/*/*/*";
- xxResourceList = xADaoManager.getXXResource()
- .findByResourceNameAndAssetIdAndResourceType(resourceName,
- assetId, AppConstants.RESOURCE_UNKNOWN);
- }
- XXResource xxResource = null;
- for (XXResource resource : xxResourceList) {
- if (resource.getName().equals(resourceName)) {
- xxResource = resource;
- break;
- }
- }
-
- if (xxResource != null) {
- return xResourceService.populateViewBean(xxResource);
- }
- return null;
-
- }
-
- public XXPolicyExportAudit createPolicyAudit(
- final XXPolicyExportAudit xXPolicyExportAudit) {
- TransactionTemplate txTemplate = new TransactionTemplate(txManager);
- txTemplate
- .setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
- XXPolicyExportAudit policyExportAudit = (XXPolicyExportAudit) txTemplate
- .execute(new TransactionCallback<Object>() {
- public Object doInTransaction(TransactionStatus status) {
- if (xXPolicyExportAudit.getHttpRetCode() == HttpServletResponse.SC_NOT_MODIFIED) {
- boolean logNotModified = PropertiesUtil
- .getBooleanProperty(
- "xa.log.SC_NOT_MODIFIED", false);
- if (!logNotModified) {
- logger.info("Not logging HttpServletResponse."
- + "SC_NOT_MODIFIED, to enable, update "
- + ": xa.log.SC_NOT_MODIFIED");
- return null;
- }
- }
- return xADaoManager.getXXPolicyExportAudit().create(
- xXPolicyExportAudit);
- }
- });
- return policyExportAudit;
- }
-
- public VXTrxLogList getReportLogs(SearchCriteria searchCriteria) {
- if (!xaBizUtil.isAdmin()) {
- throw restErrorUtil.create403RESTException("Permission Denied !");
- }
-
- if (searchCriteria != null && searchCriteria.getParamList() != null
- && searchCriteria.getParamList().size() > 0) {
- int clientTimeOffsetInMinute = RestUtil.getClientTimeOffset();
- java.util.Date temp = null;
- DateUtil dateUtil = new DateUtil();
- if (searchCriteria.getParamList().containsKey("startDate")) {
- temp = (java.util.Date) searchCriteria.getParamList().get(
- "startDate");
- temp = dateUtil.getDateFromGivenDate(temp, 0, 0, 0, 0);
- temp = dateUtil.addTimeOffset(temp, clientTimeOffsetInMinute);
- searchCriteria.getParamList().put("startDate", temp);
- }
- if (searchCriteria.getParamList().containsKey("endDate")) {
- temp = (java.util.Date) searchCriteria.getParamList().get(
- "endDate");
- temp = dateUtil.getDateFromGivenDate(temp, 0, 23, 59, 59);
- temp = dateUtil.addTimeOffset(temp, clientTimeOffsetInMinute);
- searchCriteria.getParamList().put("endDate", temp);
- }
- if (searchCriteria.getParamList().containsKey("owner")) {
- XXPortalUser xXPortalUser= xADaoManager.getXXPortalUser().findByLoginId(
- (searchCriteria.getParamList().get("owner").toString()));
- if(xXPortalUser!=null){
- searchCriteria.getParamList().put("owner", xXPortalUser.getId());
- }else{
- searchCriteria.getParamList().put("owner", 0);
- }
-
- }
-
- }
-
- VXTrxLogList vXTrxLogList = xTrxLogService
- .searchXTrxLogs(searchCriteria);
- Long count=xTrxLogService
- .searchXTrxLogsCount(searchCriteria);
- vXTrxLogList.setTotalCount(count);
- return vXTrxLogList;
- }
-
- public VXAccessAuditList getAccessLogs(SearchCriteria searchCriteria) {
-
- if (searchCriteria != null && searchCriteria.getParamList() != null
- && searchCriteria.getParamList().size() > 0) {
- int clientTimeOffsetInMinute = RestUtil.getClientTimeOffset();
- java.util.Date temp = null;
- DateUtil dateUtil = new DateUtil();
- if (searchCriteria.getParamList().containsKey("startDate")) {
- temp = (java.util.Date) searchCriteria.getParamList().get(
- "startDate");
- temp = dateUtil.getDateFromGivenDate(temp, 0, 0, 0, 0);
- temp = dateUtil.addTimeOffset(temp, clientTimeOffsetInMinute);
- searchCriteria.getParamList().put("startDate", temp);
- }
- if (searchCriteria.getParamList().containsKey("endDate")) {
- temp = (java.util.Date) searchCriteria.getParamList().get(
- "endDate");
- temp = dateUtil.getDateFromGivenDate(temp, 0, 23, 59, 59);
- temp = dateUtil.addTimeOffset(temp, clientTimeOffsetInMinute);
- searchCriteria.getParamList().put("endDate", temp);
- }
-
- }
- if(searchCriteria.getSortType()==null){
- searchCriteria.setSortType("desc");
- }else if(!searchCriteria.getSortType().equalsIgnoreCase("asc")&& !searchCriteria.getSortType().equalsIgnoreCase("desc")){
- searchCriteria.setSortType("desc");
- }
- return xAccessAuditService.searchXAccessAudits(searchCriteria);
- }
-
- public VXTrxLogList getTransactionReport(String transactionId) {
- List<XXTrxLog> xTrxLogList = xADaoManager.getXXTrxLog()
- .findByTransactionId(transactionId);
- VXTrxLogList vXTrxLogList = new VXTrxLogList();
- List<VXTrxLog> vXTrxLogs = vXTrxLogList.getVXTrxLogs();
- for (XXTrxLog xTrxLog : xTrxLogList) {
- VXTrxLog vXTrxLog = xTrxLogService.populateViewBean(xTrxLog);
- if(vXTrxLog.getPreviousValue()==null || vXTrxLog.getPreviousValue().equalsIgnoreCase("null")){
- vXTrxLog.setPreviousValue("");
- }
- if(vXTrxLog.getAttributeName()!=null && vXTrxLog.getAttributeName().equalsIgnoreCase("Password")){
- vXTrxLog.setPreviousValue("*********");
- vXTrxLog.setNewValue("***********");
- }
- if(vXTrxLog.getAttributeName()!=null && vXTrxLog.getAttributeName().equalsIgnoreCase("Connection Configurations")){
- if(vXTrxLog.getPreviousValue()!=null && vXTrxLog.getPreviousValue().contains("password")){
- String tempPreviousStr=vXTrxLog.getPreviousValue();
- String tempPreviousArr[]=vXTrxLog.getPreviousValue().split(",");
- for(int i=0;i<tempPreviousArr.length;i++){
- if(tempPreviousArr[i].contains("{\"password")){
- vXTrxLog.setPreviousValue(tempPreviousStr.replace(tempPreviousArr[i], "{\"password\":\"*****\"}"));
- break;
- }else if(tempPreviousArr[i].contains("\"password") && tempPreviousArr[i].contains("}")){
- vXTrxLog.setPreviousValue(tempPreviousStr.replace(tempPreviousArr[i], "\"password\":\"******\"}"));
- break;
- }else if(tempPreviousArr[i].contains("\"password")){
- vXTrxLog.setPreviousValue(tempPreviousStr.replace(tempPreviousArr[i], "\"password\":\"******\""));
- break;
- }
- }
- }
- if(vXTrxLog.getNewValue()!=null && vXTrxLog.getNewValue().contains("password")){
- String tempNewStr=vXTrxLog.getNewValue();
- String tempNewArr[]=vXTrxLog.getNewValue().split(",");
- for(int i=0;i<tempNewArr.length;i++){
- if(tempNewArr[i].contains("{\"password")){
- vXTrxLog.setNewValue(tempNewStr.replace(tempNewArr[i], "{\"password\":\"*****\"}"));
- break;
- }else if(tempNewArr[i].contains("\"password") && tempNewArr[i].contains("}")){
- vXTrxLog.setNewValue(tempNewStr.replace(tempNewArr[i], "\"password\":\"******\"}"));
- break;
- }else if(tempNewArr[i].contains("\"password")){
- vXTrxLog.setNewValue(tempNewStr.replace(tempNewArr[i], "\"password\":\"******\""));
- break;
- }
- }
- }
- }
- vXTrxLogs.add(vXTrxLog);
- }
- vXTrxLogList.setVXTrxLogs(vXTrxLogs);
- return vXTrxLogList;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * com.xasecure.biz.AssetMgrBase#searchXPolicyExportAudits(com.xasecure.
- * common.SearchCriteria)
- */
- @Override
- public VXPolicyExportAuditList searchXPolicyExportAudits(
- SearchCriteria searchCriteria) {
- if (searchCriteria != null && searchCriteria.getParamList() != null
- && searchCriteria.getParamList().size() > 0) {
-
- int clientTimeOffsetInMinute = RestUtil.getClientTimeOffset();
- java.util.Date temp = null;
- DateUtil dateUtil = new DateUtil();
- if (searchCriteria.getParamList().containsKey("startDate")) {
- temp = (java.util.Date) searchCriteria.getParamList().get(
- "startDate");
- temp = dateUtil.getDateFromGivenDate(temp, 0, 0, 0, 0);
- temp = dateUtil.addTimeOffset(temp, clientTimeOffsetInMinute);
- searchCriteria.getParamList().put("startDate", temp);
- }
- if (searchCriteria.getParamList().containsKey("endDate")) {
- temp = (java.util.Date) searchCriteria.getParamList().get(
- "endDate");
- temp = dateUtil.getDateFromGivenDate(temp, 0, 23, 59, 59);
- temp = dateUtil.addTimeOffset(temp, clientTimeOffsetInMinute);
- searchCriteria.getParamList().put("endDate", temp);
- }
- }
-
- return xPolicyExportAuditService.searchXPolicyExportAudits(searchCriteria);
- }
-
- public VXAsset getXAsset(Long id){
- UserSessionBase currentUserSession = ContextUtil
- .getCurrentUserSession();
- VXAsset vXAsset=null;
- if (currentUserSession.isUserAdmin()) {
- vXAsset = xAssetService.readResource(id);
- if (vXAsset.getActiveStatus() == XACommonEnums.STATUS_DELETED) {
- logger.error("Trying to read Asset which is soft deleted");
- throw restErrorUtil.createRESTException(
- "Repository not found for this Id : " + id,
- MessageEnums.DATA_NOT_FOUND, id, null,
- "Repository does not exist for this Id : " + id);
- }
- }else{
- XXAsset xXAsset=xADaoManager.getXXAsset().getById(id);
-
- if (xXAsset.getActiveStatus() == XACommonEnums.STATUS_DELETED) {
- logger.error("Trying to read Asset which is soft deleted");
- throw restErrorUtil.createRESTException(
- "Repository not found for this Id : " + id,
- MessageEnums.DATA_NOT_FOUND, id, null,
- "Repository does not exist for this Id : " + id);
- }
-
- vXAsset=xAssetService.populateViewBean(xXAsset);
- /*List<XXResource> xXResourceList=xADaoManager
- .getXXResource().findByAssetId(id);
- for (XXResource xXResource : xXResourceList) {
- VXResponse vXResponse = xaBizUtil.hasPermission(xResourceService.populateViewBean(xXResource),
- AppConstants.XA_PERM_TYPE_ADMIN);
- if(vXResponse.getStatusCode() == VXResponse.STATUS_SUCCESS){
- XXAsset xXAsset=xADaoManager.getXXAsset().getById(id);
- vXAsset=xAssetService.populateViewBean(xXAsset);
- break;
- }
- }*/
- }
- return vXAsset;
- }
-
- private void createDefaultUDFPolicy(VXAsset vXAsset, String config) {
- int assetType = vXAsset.getAssetType();
- if (assetType != AppConstants.ASSET_HIVE) {
- return ;
- }
- Map<String, String> configMap = jsonUtil.jsonToMap(config);
- String userName = stringUtil.getValidUserName(configMap.get("username"));
- VXResource vXResource = new VXResource();
- vXResource.setAssetId(vXAsset.getId());
- vXResource.setAssetName(vXAsset.getName());
- vXResource.setResourceStatus(AppConstants.STATUS_ENABLED);
- String tempPolicyName=vXAsset.getName()+"-"+2+"-"+DateUtil.dateToString(DateUtil.getUTCDate(),"yyyyMMddHHmmss");
- vXResource.setPolicyName(tempPolicyName);
- if (assetType == AppConstants.ASSET_HIVE) {
- vXResource.setDatabases("*");
- vXResource.setTables("");
- vXResource.setColumns("");
- vXResource.setUdfs("*");
- vXResource.setName("/*/*");
- vXResource.setResourceType(AppConstant
<TRUNCATED>
[43/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/config/Jersey2ConfigWatcher.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/config/Jersey2ConfigWatcher.java b/agents-impl/src/main/java/com/xasecure/pdp/config/Jersey2ConfigWatcher.java
deleted file mode 100644
index e58ff60..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/config/Jersey2ConfigWatcher.java
+++ /dev/null
@@ -1,565 +0,0 @@
-/**
- * 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 com.xasecure.pdp.config;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.security.KeyManagementException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.SecureRandom;
-import java.security.UnrecoverableKeyException;
-import java.security.cert.CertificateException;
-
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
-import javax.ws.rs.client.Client;
-import javax.ws.rs.client.ClientBuilder;
-import javax.ws.rs.client.WebTarget;
-import javax.ws.rs.core.Response;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.conf.Configuration;
-import org.glassfish.jersey.client.ClientConfig;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.sun.jersey.client.urlconnection.HTTPSProperties;
-import com.xasecure.authorization.hadoop.utils.XaSecureCredentialProvider;
-import com.xasecure.pdp.config.gson.PolicyExclusionStrategy;
-import com.xasecure.pdp.constants.XaSecureConstants;
-import com.xasecure.pdp.model.PolicyContainer;
-
-public abstract class Jersey2ConfigWatcher extends Thread {
-
- private static final Log LOG = LogFactory.getLog(Jersey2ConfigWatcher.class);
-
- public static final String EXPECTED_MIME_TYPE = "application/json" ;
-
- // public static final String EXPECTED_MIME_TYPE = "application/octet-stream";
-
- private static final String LASTUPDATED_PARAM = "epoch";
- private static final String POLICY_COUNT_PARAM = "policyCount";
- private static final String AGENT_NAME_PARAM = "agentId" ;
-
- private static final int MAX_AGENT_NAME_LEN = 255 ;
-
- private static final String XASECURE_KNOX_CREDENTIAL_PROVIDER_FILE
- = "xasecure.knox.credential.provider.file";
-
- private String url;
-
- private long intervalInMilliSeconds;
-
- private long lastModifiedTime = 0;
-
- private boolean shutdownFlag = false;
-
- private String lastStoredFileName = null;
-
- protected PolicyContainer policyContainer = null;
-
- private static PolicyExclusionStrategy policyExclusionStrategy = new PolicyExclusionStrategy();
-
- private static XaSecureCredentialProvider xasecurecp = null;
-
- public abstract void doOnChange();
-
- private String credentialProviderFile = null;
- private String keyStoreFile = null ;
- private String keyStorePassword = null;
- private String trustStoreFile = null ;
- private String trustStorePassword = null ;
- private String keyStoreType = null ;
- private String trustStoreType = null ;
- private SSLContext sslContext = null ;
- private HostnameVerifier hv = null ;
- private String agentName = "unknown" ;
-
- private String sslConfigFileName = null ;
-
- boolean policyCacheLoadedOnce = false;
-
- public Jersey2ConfigWatcher(String url, long aIntervalInMilliSeconds,String sslConfigFileName,String lastStoredFileName) {
- super("XaSecureConfigURLWatcher");
- setDaemon(true);
- this.url = url;
- intervalInMilliSeconds = aIntervalInMilliSeconds;
- this.sslConfigFileName = sslConfigFileName ;
- this.agentName = getAgentName(this.url) ;
- this.lastStoredFileName = lastStoredFileName;
- if (LOG.isInfoEnabled()) {
- LOG.info("Creating PolicyRefreshser with url: " + url +
- ", refreshInterval(milliSeconds): " + aIntervalInMilliSeconds +
- ", sslConfigFileName: " + sslConfigFileName +
- ", lastStoredFileName: " + lastStoredFileName);
- }
- init();
- validateAndRun();
- LOG.debug("Created new ConfigWatcher for URL [" + url + "]");
- }
-
-
- public void init() {
- if (sslConfigFileName != null) {
- LOG.debug("Loading SSL Configuration from [" + sslConfigFileName
- + "]");
- InputStream in = null;
- try {
- Configuration conf = new Configuration();
- in = getFileInputStream(sslConfigFileName);
- if (in != null) {
- conf.addResource(in);
- }
-
- if (url.startsWith("https")) {
- xasecurecp = XaSecureCredentialProvider.getInstance();
-
- keyStoreFile = conf
- .get(XaSecureConstants.XASECURE_POLICYMGR_CLIENT_KEY_FILE);
-
- credentialProviderFile = conf
- .get(XASECURE_KNOX_CREDENTIAL_PROVIDER_FILE);
- String keyStorePasswordAlias = XaSecureConstants.XASECURE_POLICYMGR_CLIENT_KEY_FILE_CREDENTIAL_ALIAS;
-
- char[] v_keyStorePassword = getCredential(credentialProviderFile,
- keyStorePasswordAlias);
- if (v_keyStorePassword == null) {
- keyStorePassword = null;
- } else {
- keyStorePassword = new String(v_keyStorePassword);
- }
-
- trustStoreFile = conf
- .get(XaSecureConstants.XASECURE_POLICYMGR_TRUSTSTORE_FILE);
-
- //trustStoreURL = conf
- // .get(XaSecureConstants.XASECURE_POLICYMGR_TRUSTSTORE_FILE_CREDENTIAL);
- String trustStorePasswordAlias = XaSecureConstants.XASECURE_POLICYMGR_TRUSTSTORE_FILE_CREDENTIAL_ALIAS;
-
- char[] v_trustStorePassword = getCredential(credentialProviderFile,
- trustStorePasswordAlias);
- if (v_trustStorePassword == null) {
- trustStorePassword = null;
- } else {
- trustStorePassword = new String(v_trustStorePassword);
- }
-
- keyStoreType = conf
- .get(XaSecureConstants.XASECURE_POLICYMGR_CLIENT_KEY_FILE_TYPE,
- XaSecureConstants.XASECURE_POLICYMGR_CLIENT_KEY_FILE_TYPE_DEFAULT);
- trustStoreType = conf
- .get(XaSecureConstants.XASECURE_POLICYMGR_TRUSTSTORE_FILE_TYPE,
- XaSecureConstants.XASECURE_POLICYMGR_TRUSTSTORE_FILE_TYPE_DEFAULT);
- }
- } catch (IOException ioe) {
- LOG.error("Unable to load SSL Config FileName: ["
- + sslConfigFileName + "]", ioe);
- } finally {
- if (in != null) {
- try {
- in.close();
- } catch (IOException e) {
- LOG.error("Unable to close SSL Config FileName: ["
- + sslConfigFileName + "]", e);
- }
- }
- }
-
- LOG.debug("Keystore filename:[" + keyStoreFile + "]");
- LOG.debug("TrustStore filename:[" + trustStoreFile + "]");
-
- }
- }
-
- public String getURL() {
- return url;
- }
-
- public long getIntervalInMilliSeconds() {
- return intervalInMilliSeconds;
- }
-
- public long getLastModifiedTime() {
- return lastModifiedTime;
- }
-
- public void run() {
- while (!shutdownFlag) {
- validateAndRun();
- try {
- Thread.sleep(intervalInMilliSeconds);
- } catch (InterruptedException e) {
- LOG.error("Unable to complete sleep for [" + intervalInMilliSeconds + "]", e);
- }
- }
- }
-
- private void validateAndRun() {
- if (isFileChanged()) {
- LOG.debug("Policy has been changed from " + url + " ... RELOADING");
- try {
- doOnChange();
- } catch (Exception e) {
- LOG.error("Unable to complete doOnChange() method on file change [" + url + "]", e);
- }
- } else {
- LOG.debug("No Change found in the policy from " + url);
- }
- }
-
- private boolean isFileChanged() {
- boolean isChanged = false;
-
-
- try {
-
- Client client = null;
- Response response = null;
-
- try {
-
- int policyCount = getPolicyCount(policyContainer);
-
- if (url.contains("https")) {
- // build SSL Client
- client = buildSSLClient();
- }
-
- if (client == null) {
- client = ClientBuilder.newClient();
- }
-
- WebTarget webTarget = client.target(url)
- .queryParam(LASTUPDATED_PARAM, String.valueOf(lastModifiedTime))
- .queryParam(POLICY_COUNT_PARAM, String.valueOf(policyCount))
- .queryParam(AGENT_NAME_PARAM, agentName);
-
- response = webTarget.request().accept(EXPECTED_MIME_TYPE).get();
-
-
- if (response != null) {
-
- Boolean responsePresent = true;
- int responseStatus = response.getStatus();
-
- if ( fetchPolicyfromCahce(responsePresent,responseStatus,lastStoredFileName) ) {
- /* If the response is other than 200 and 304 load the policy from the cache */
- isChanged = true;
-
- } else {
- /*
- * If Policy Manager is available fetch the policy from
- * it
- */
- if (response.getStatus() == 200) {
-
- String entityString = response
- .readEntity(String.class);
- if (LOG.isDebugEnabled()) {
- LOG.debug("JSON response from server: "
- + entityString);
- }
-
- Gson gson = new GsonBuilder()
- .setPrettyPrinting()
- .addDeserializationExclusionStrategy(
- policyExclusionStrategy).create();
- PolicyContainer newPolicyContainer = gson.fromJson(
- entityString, PolicyContainer.class);
- if ((newPolicyContainer.getLastUpdatedTimeInEpoc() > lastModifiedTime)
- || (getPolicyCount(newPolicyContainer) != policyCount)) {
- policyContainer = newPolicyContainer;
- lastModifiedTime = policyContainer
- .getLastUpdatedTimeInEpoc();
- isChanged = true;
- if (LOG.isDebugEnabled()) {
- LOG.debug("Got response: 200 with {change in lastupdatedTime}\n"
- + gson.toJson(newPolicyContainer));
- }
- } else {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Got response: 200 with {no-change in lastupdatedTime}\n"
- + gson.toJson(newPolicyContainer));
- }
- isChanged = false;
- }
- } else if (response.getStatus() == 304) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Got response: 304 ");
- }
- isChanged = false; // No Change has been there since
- // our
- // earlier request
- } else {
- LOG.error("Unable to get a valid response for isFileChanged() call for ["
- + url
- + "] = response code found ["
- + response.getStatus() + "]");
- }
- }
-
- } else {
- LOG.error("Unable to get a valid response for isFileChanged() call for [" + url + "] - got null response.");
- // force the policy update to get fresh copy
- lastModifiedTime = 0;
- }
-
- } finally {
- if (response != null) {
- response.close();
- }
- if (client != null) {
- client.close();
- }
- }
- } catch (Throwable t) {
-
- Boolean responsePresent = false;
- int responseStatus = -1;
-
- if ( fetchPolicyfromCahce(responsePresent,responseStatus,lastStoredFileName) ) {
- /* Successfully found the Policy Cache file and loaded */
- isChanged = true;
- } else {
- LOG.error("Unable to complete isFileChanged() call for [" + url + "]", t);
- // force the policy update to get fresh copy
- lastModifiedTime = 0;
- LOG.error("Policy file Cache not found..");
- throw new RuntimeException("Unable to find Enterprise Policy Storage");
- }
-
- } finally {
- if (isChanged) {
- LOG.info("URL: [" + url + "], isModified: " + isChanged + ", lastModifiedTime:" + lastModifiedTime);
- } else if (LOG.isDebugEnabled()) {
- LOG.debug("URL: [" + url + "], isModified: " + isChanged + ", lastModifiedTime:" + lastModifiedTime);
- }
- }
- return isChanged;
- }
-
- public PolicyContainer getPolicyContainer() {
- return policyContainer;
- }
-
- private int getPolicyCount(PolicyContainer aPolicyContainer) {
- return (aPolicyContainer == null ? 0 : (aPolicyContainer.getAcl() == null ? 0 : aPolicyContainer.getAcl().size()));
- }
-
-
- public synchronized Client buildSSLClient() {
- Client client = null;
- try {
-
- ClientConfig config = new ClientConfig();
-
- if (sslContext == null) {
-
- KeyManager[] kmList = null;
- TrustManager[] tmList = null;
-
- if (keyStoreFile != null && keyStorePassword != null) {
-
- KeyStore keyStore = KeyStore.getInstance(keyStoreType);
- InputStream in = null ;
- try {
- in = getFileInputStream(keyStoreFile) ;
- if (in == null) {
- LOG.error("Unable to obtain keystore from file [" + keyStoreFile + "]");
- return client ;
- }
- keyStore.load(in, keyStorePassword.toCharArray());
- KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(XaSecureConstants.XASECURE_SSL_KEYMANAGER_ALGO_TYPE);
- keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
- kmList = keyManagerFactory.getKeyManagers();
- }
- finally {
- if (in != null) {
- in.close();
- }
- }
-
- }
-
- if (trustStoreFile != null && trustStorePassword != null) {
-
- KeyStore trustStore = KeyStore.getInstance(trustStoreType);
- InputStream in = null ;
- try {
- in = getFileInputStream(trustStoreFile) ;
- if (in == null) {
- LOG.error("Unable to obtain keystore from file [" + trustStoreFile + "]");
- return client ;
- }
- trustStore.load(in, trustStorePassword.toCharArray());
- TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(XaSecureConstants.XASECURE_SSL_TRUSTMANAGER_ALGO_TYPE);
- trustManagerFactory.init(trustStore);
- tmList = trustManagerFactory.getTrustManagers();
- }
- finally {
- if (in != null) {
- in.close() ;
- }
- }
- }
-
- sslContext = SSLContext.getInstance(XaSecureConstants.XASECURE_SSL_CONTEXT_ALGO_TYPE);
-
- sslContext.init(kmList, tmList, new SecureRandom());
-
- hv = new HostnameVerifier() {
- public boolean verify(String urlHostName, SSLSession session) {
- return session.getPeerHost().equals(urlHostName);
- }
- };
-
- }
-
- config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(hv, sslContext));
-
- client = ClientBuilder.newClient(config);
-
- } catch (KeyStoreException e) {
- LOG.error("Unable to obtain from KeyStore", e);
- } catch (NoSuchAlgorithmException e) {
- LOG.error("SSL algorithm is available in the environment", e);
- } catch (CertificateException e) {
- LOG.error("Unable to obtain the requested certification ", e);
- } catch (FileNotFoundException e) {
- LOG.error("Unable to find the necessary SSL Keystore and TrustStore Files", e);
- } catch (IOException e) {
- LOG.error("Unable to read the necessary SSL Keystore and TrustStore Files", e);
- } catch (KeyManagementException e) {
- LOG.error("Unable to initials the SSLContext", e);
- } catch (UnrecoverableKeyException e) {
- LOG.error("Unable to recover the key from keystore", e);
- }
- return client;
- }
-
- private InputStream getFileInputStream(String fileName) throws IOException {
- InputStream in = null ;
-
- File f = new File(fileName) ;
-
- if (f.exists()) {
- in = new FileInputStream(f) ;
- }
- else {
- in = ClassLoader.getSystemResourceAsStream(fileName) ;
- }
- return in ;
- }
-
- public static String getAgentName(String aUrl) {
- String hostName = null ;
- String repoName = null ;
- try {
- hostName = InetAddress.getLocalHost().getHostName() ;
- } catch (UnknownHostException e) {
- LOG.error("ERROR: Unable to find hostname for the agent ", e);
- hostName = "unknownHost" ;
- }
-
- String[] tokens = aUrl.split("/") ;
-
- if ( tokens.length > 0 ) {
- repoName = tokens[tokens.length-1] ;
- }
- else {
- repoName = "unknownRepo" ;
- }
-
- String agentName = hostName + "-" + repoName ;
-
- if (agentName.length() > MAX_AGENT_NAME_LEN ) {
- agentName = agentName.substring(0,MAX_AGENT_NAME_LEN) ;
- }
-
- return agentName ;
- }
-
- private boolean fetchPolicyfromCahce( Boolean responsePresent, int responseStatus, String lastStoredFileName){
-
- boolean cacheFound = false;
-
- if ( ( responsePresent == false ) || ( responseStatus != 200 && responseStatus != 304) ) {
-
- /* Policy Manager not available read the policy from the last enforced one */
-
- if (policyCacheLoadedOnce) {
- cacheFound = true;
- return cacheFound;
- }
-
- try {
- /* read the last stored policy file and load the PolicyContainer */
- LOG.info("Policy Manager not available, using the last stored Policy File" + this.lastStoredFileName );
- LOG.debug("LastStoredFileName when policymgr was available" + this.lastStoredFileName);
-
- BufferedReader jsonString = new BufferedReader(new FileReader(this.lastStoredFileName));
- Gson gson = new GsonBuilder().setPrettyPrinting().addDeserializationExclusionStrategy(policyExclusionStrategy).create();
- PolicyContainer newPolicyContainer = gson.fromJson(jsonString, PolicyContainer.class);
- policyContainer = newPolicyContainer;
- lastModifiedTime = policyContainer.getLastUpdatedTimeInEpoc();
- if (LOG.isDebugEnabled()) {
- LOG.debug("Policy Manager not available.Got response =" + responseStatus +"\n" + gson.toJson(newPolicyContainer));
- }
-
- cacheFound = true;
- policyCacheLoadedOnce = true;
-
- } catch( FileNotFoundException fe ){
-
- /* unable to get the last stored policy, raise warning for unavailability of policy cache file and continue...*/
- if ( this.lastStoredFileName == null ) {
- LOG.info("Policy cache file not found...XAagent authorization not enabled");
- }
- else {
- LOG.info("Unable to access Policy cache file...XAagent authorization not enabled");
- }
- }
-
- }
-
- return cacheFound;
- }
-
- private char[] getCredential(String url, String alias) {
- char[] credStr=xasecurecp.getCredentialString(url,alias);
- return credStr;
- }
-
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/config/Jersey2PolicyRefresher.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/config/Jersey2PolicyRefresher.java b/agents-impl/src/main/java/com/xasecure/pdp/config/Jersey2PolicyRefresher.java
deleted file mode 100644
index 1a1fe79..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/config/Jersey2PolicyRefresher.java
+++ /dev/null
@@ -1,207 +0,0 @@
-/*
- * 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 com.xasecure.pdp.config;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.xasecure.pdp.config.gson.PolicyExclusionStrategy;
-import com.xasecure.pdp.model.PolicyContainer;
-
-public class Jersey2PolicyRefresher {
-
- private static final Log LOG = LogFactory.getLog(Jersey2PolicyRefresher.class);
-
- private String url ;
- private long refreshInterval ;
-
- private Jersey2ConfigWatcher watcherDaemon = null;
-
- protected PolicyContainer policyContainer = null ;
-
- private PolicyChangeListener policyChangeListener = null ;
-
- private String saveAsFileName = null ;
-
- private String sslConfigFileName = null ;
-
- private String lastStoredFileName = null;
-
- private PolicyExclusionStrategy policyExclusionStrategy = new PolicyExclusionStrategy() ;
-
- public Jersey2PolicyRefresher(String url, long refreshInterval, String sslConfigFileName, String lastStoredFileName) {
- if (LOG.isInfoEnabled()) {
- LOG.info("Creating PolicyRefreshser with url: " + url +
- ", refreshInterval: " + refreshInterval +
- ", sslConfigFileName: " + sslConfigFileName +
- ", lastStoredFileName: " + lastStoredFileName);
- }
- this.url = url ;
- this.refreshInterval = refreshInterval ;
- this.sslConfigFileName = sslConfigFileName ;
- this.lastStoredFileName = lastStoredFileName;
- checkFileWatchDogThread();
- }
-
- public PolicyChangeListener getPolicyChangeListener() {
- return policyChangeListener;
- }
-
- public synchronized void setPolicyChangeListener(PolicyChangeListener policyChangeListener) {
- this.policyChangeListener = policyChangeListener;
- if (this.policyContainer != null) {
- savePolicyToFile() ;
- notifyPolicyChange() ;
- }
- }
-
- private void setPolicyContainer(PolicyContainer aPolicyContainer) {
- this.policyContainer = aPolicyContainer ;
- }
-
- public PolicyContainer getPolicyContainer() {
- return policyContainer ;
- }
-
- public String getSaveAsFileName() {
- return saveAsFileName;
- }
-
- public void setSaveAsFileName(String saveAsFileName) {
- this.saveAsFileName = saveAsFileName;
- }
-
- public String getSslConfigFileName() {
- return sslConfigFileName;
- }
-
- public String getLastStoredFileName() {
- return lastStoredFileName;
- }
-
- public void setLastStoredFileName(String lastStoredFileName) {
- this.lastStoredFileName = lastStoredFileName;
- }
-
- public void setSslConfigFileName(String sslConfigFileName) {
- this.sslConfigFileName = sslConfigFileName;
- }
-
-
- private synchronized void checkFileWatchDogThread() {
- if (watcherDaemon == null) {
- try {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Starting WatchDog for the Path [" + url + "] ....");
- }
- watcherDaemon = new Jersey2ConfigWatcher(url, refreshInterval,sslConfigFileName,this.getLastStoredFileName()) {
- public void doOnChange() {
- PolicyContainer newPolicyContainer = getPolicyContainer() ;
- setPolicyContainer(newPolicyContainer) ;
- savePolicyToFile() ;
- notifyPolicyChange();
- };
- };
- watcherDaemon.start();
- if (LOG.isDebugEnabled()) {
- LOG.debug("Completed kick-off of FileWatchDog for the Path [" + url + "] interval in millisecond:" + refreshInterval);
- }
- } catch (Throwable t) {
- LOG.error("Unable to start the FileWatchDog for path [" + url + "]", t);
- }
- }
- }
-
- private void notifyPolicyChange() {
- if (policyChangeListener != null) {
- try {
- policyChangeListener.OnPolicyChange(policyContainer);
- }
- catch(Throwable t) {
- LOG.error("Error during notification of policy changes to listener [" + policyChangeListener + "]", t) ;
- }
- finally {
- LOG.debug("Completed notification of policy changes to listener [" + policyChangeListener + "]") ;
- }
- }
- }
-
-
- private void savePolicyToFile() {
-
- LOG.debug("savePolicyToFile() is called with [" + saveAsFileName + "] - START") ;
- String fileName = null;
- if (saveAsFileName != null) {
- String currentDateTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) ;
- fileName = saveAsFileName + "." + currentDateTime ;
- File saveFile = new File(fileName) ;
- Gson gson = new GsonBuilder().setPrettyPrinting().setExclusionStrategies(policyExclusionStrategy).create() ;
- String policyAsJson = gson.toJson(policyContainer) ;
- PrintWriter writer = null ;
- try {
- writer = new PrintWriter(new FileWriter(saveFile)) ;
- writer.println(policyAsJson) ;
- }
- catch(IOException ioe) {
- LOG.error("Unable to save policy into file: [" + saveFile.getAbsolutePath() + "]", ioe);
- }
- finally {
- if (writer != null) {
- writer.close();
- }
- }
-
- if (lastStoredFileName != null) {
- File lastSaveFileName = new File(lastStoredFileName);
-
- try {
- writer = new PrintWriter(new FileWriter(lastSaveFileName));
- writer.println(policyAsJson);
-
- }
- catch(IOException ioe){
- LOG.error("Unable to save the policy into Last Stored Policy File [" + lastSaveFileName.getAbsolutePath() + "]", ioe );
- }
- finally {
- //make the policy file cache to be 600 permission when it gets created and updated
- lastSaveFileName.setReadable(false,false);
- lastSaveFileName.setReadable(true,true);
- if (writer != null) {
- writer.close();
- }
- }
-
- }
- }
-
- LOG.debug("savePolicyToFile() is called with [" + fileName + "] - END") ;
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/config/PolicyChangeListener.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/config/PolicyChangeListener.java b/agents-impl/src/main/java/com/xasecure/pdp/config/PolicyChangeListener.java
deleted file mode 100644
index e6ce2aa..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/config/PolicyChangeListener.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * 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 com.xasecure.pdp.config;
-
-import com.xasecure.pdp.model.PolicyContainer;
-
-public interface PolicyChangeListener {
- public void OnPolicyChange(PolicyContainer aPolicyContainer) ;
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/config/PolicyRefresher.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/config/PolicyRefresher.java b/agents-impl/src/main/java/com/xasecure/pdp/config/PolicyRefresher.java
deleted file mode 100644
index b2e33ff..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/config/PolicyRefresher.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/*
- * 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 com.xasecure.pdp.config;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.xasecure.pdp.config.gson.PolicyExclusionStrategy;
-import com.xasecure.pdp.model.PolicyContainer;
-
-public class PolicyRefresher {
-
- private static final Log LOG = LogFactory.getLog(PolicyRefresher.class);
-
- private String url ;
- private long refreshInterval ;
-
- private ConfigWatcher watcherDaemon = null;
-
- protected PolicyContainer policyContainer = null ;
-
- private PolicyChangeListener policyChangeListener = null ;
-
- private String saveAsFileName = null ;
-
- private String sslConfigFileName = null ;
-
- private String lastStoredFileName = null;
-
- private PolicyExclusionStrategy policyExclusionStrategy = new PolicyExclusionStrategy() ;
-
- public PolicyRefresher(String url, long refreshInterval, String sslConfigFileName, String lastStoredFileName) {
- if (LOG.isInfoEnabled()) {
- LOG.info("Creating PolicyRefreshser with url: " + url +
- ", refreshInterval: " + refreshInterval +
- ", sslConfigFileName: " + sslConfigFileName +
- ", lastStoredFileName: " + lastStoredFileName);
- }
- this.url = url ;
- this.refreshInterval = refreshInterval ;
- this.sslConfigFileName = sslConfigFileName ;
- this.lastStoredFileName = lastStoredFileName;
- checkFileWatchDogThread();
- }
-
- public PolicyChangeListener getPolicyChangeListener() {
- return policyChangeListener;
- }
-
- public synchronized void setPolicyChangeListener(PolicyChangeListener policyChangeListener) {
- this.policyChangeListener = policyChangeListener;
- if (this.policyContainer != null) {
- savePolicyToFile() ;
- savePolicyToCacheFile();
- notifyPolicyChange() ;
- }
- }
-
- public void setPolicyContainer(PolicyContainer aPolicyContainer) {
- this.policyContainer = aPolicyContainer ;
- }
-
- public PolicyContainer getPolicyContainer() {
- return policyContainer ;
- }
-
- public String getSaveAsFileName() {
- return saveAsFileName;
- }
-
- public void setSaveAsFileName(String saveAsFileName) {
- this.saveAsFileName = saveAsFileName;
- }
-
- public String getSslConfigFileName() {
- return sslConfigFileName;
- }
-
- public String getLastStoredFileName() {
- return lastStoredFileName;
- }
-
- public void setLastStoredFileName(String lastStoredFileName) {
- this.lastStoredFileName = lastStoredFileName;
- }
-
- public void setSslConfigFileName(String sslConfigFileName) {
- this.sslConfigFileName = sslConfigFileName;
- }
-
-
- private synchronized void checkFileWatchDogThread() {
- if (watcherDaemon == null) {
- try {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Starting WatchDog for the Path [" + url + "] ....");
- }
- watcherDaemon = new ConfigWatcher(url, refreshInterval,sslConfigFileName,this.getLastStoredFileName()) {
- public void doOnChange() {
- PolicyContainer newPolicyContainer = getPolicyContainer() ;
- setPolicyContainer(newPolicyContainer) ;
- savePolicyToFile() ;
- savePolicyToCacheFile();
- notifyPolicyChange();
- };
- };
- watcherDaemon.start();
- if (LOG.isDebugEnabled()) {
- LOG.debug("Completed kick-off of FileWatchDog for the Path [" + url + "] interval in millisecond:" + refreshInterval);
- }
- } catch (Throwable t) {
- LOG.error("Unable to start the FileWatchDog for path [" + url + "]", t);
- }
- }
- }
-
- private void notifyPolicyChange() {
- if (policyChangeListener != null) {
- try {
- policyChangeListener.OnPolicyChange(policyContainer);
- }
- catch(Throwable t) {
- LOG.error("Error during notification of policy changes to listener [" + policyChangeListener + "]", t) ;
- }
- finally {
- LOG.debug("Completed notification of policy changes to listener [" + policyChangeListener + "]") ;
- }
- }
- }
-
-
- private void savePolicyToFile() {
- if (watcherDaemon != null && !watcherDaemon.iscacheModfied()) {
- // Do not Save the file if the policy is not modified.
- return;
- }
- LOG.debug("savePolicyToFile() is called with [" + saveAsFileName + "] - START") ;
- String fileName = null;
- if (saveAsFileName != null) {
- String currentDateTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) ;
- fileName = saveAsFileName + "." + currentDateTime ;
- File saveFile = new File(fileName) ;
- Gson gson = new GsonBuilder().setPrettyPrinting().setExclusionStrategies(policyExclusionStrategy).create() ;
- String policyAsJson = gson.toJson(policyContainer) ;
- PrintWriter writer = null ;
- try {
- writer = new PrintWriter(new FileWriter(saveFile)) ;
- writer.println(policyAsJson) ;
- }
- catch(IOException ioe) {
- LOG.warn("Unable to save policy into file: [" + saveFile.getAbsolutePath() + "]");
- }
- finally {
- if (writer != null) {
- writer.close();
- }
- }
- LOG.debug("savePolicyToFile() is called with [" + fileName + "] - END") ;
- }
- }
-
- private void savePolicyToCacheFile() {
-
- if (watcherDaemon != null && !watcherDaemon.iscacheModfied()) {
- // Don't Save the file if the policy is not modified.
- return;
- }
-
- LOG.debug("savePolicyToCacheFile() is called with [" + lastStoredFileName + "] - START") ;
-
- if (lastStoredFileName != null) {
-
- File lastSaveFile = new File(lastStoredFileName) ;
- Gson gson = new GsonBuilder().setPrettyPrinting().setExclusionStrategies(policyExclusionStrategy).create() ;
- String policyAsJson = gson.toJson(policyContainer) ;
- PrintWriter writer = null ;
-
- try {
- writer = new PrintWriter(new FileWriter(lastSaveFile));
- writer.println(policyAsJson);
-
- }
- catch(IOException ioe){
- LOG.warn("Unable to save the policy into Last Stored Policy File [" + lastSaveFile.getAbsolutePath() + "]");
- }
- finally {
- //make the policy file cache to be 600 permission when it gets created and updated
- lastSaveFile.setReadable(false,false);
- lastSaveFile.setWritable(false,false);
- lastSaveFile.setReadable(true,true);
- lastSaveFile.setWritable(true,true);
- if (writer != null) {
- writer.close();
- }
- }
-
- }
-
- LOG.debug("savePolicyToCacheFile() is called with [" + lastStoredFileName + "] - END") ;
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/config/gson/ExcludeSerialization.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/config/gson/ExcludeSerialization.java b/agents-impl/src/main/java/com/xasecure/pdp/config/gson/ExcludeSerialization.java
deleted file mode 100644
index 29c6646..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/config/gson/ExcludeSerialization.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * 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 com.xasecure.pdp.config.gson;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-@Retention(RetentionPolicy.RUNTIME)
-@Target({ElementType.FIELD})
-
-public @interface ExcludeSerialization {
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/config/gson/PolicyExclusionStrategy.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/config/gson/PolicyExclusionStrategy.java b/agents-impl/src/main/java/com/xasecure/pdp/config/gson/PolicyExclusionStrategy.java
deleted file mode 100644
index fa1ee70..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/config/gson/PolicyExclusionStrategy.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * 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 com.xasecure.pdp.config.gson;
-
-import com.google.gson.ExclusionStrategy;
-import com.google.gson.FieldAttributes;
-
-public class PolicyExclusionStrategy implements ExclusionStrategy {
-
- @Override
- public boolean shouldSkipClass(Class<?> objectClass) {
- return (objectClass.getAnnotation(ExcludeSerialization.class) != null) ;
- }
-
- @Override
- public boolean shouldSkipField(FieldAttributes aFieldAttributes) {
- return (aFieldAttributes.getAnnotation(ExcludeSerialization.class) != null) ;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/constants/XaSecureConstants.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/constants/XaSecureConstants.java b/agents-impl/src/main/java/com/xasecure/pdp/constants/XaSecureConstants.java
deleted file mode 100644
index db2552c..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/constants/XaSecureConstants.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * 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 com.xasecure.pdp.constants;
-
-public class XaSecureConstants {
- public static final String PUBLIC_ACCESS_ROLE = "public" ;
-
- public static final String XASECURE_HBASE_POLICYMGR_URL_PROP = "xasecure.hbase.policymgr.url";
- public static final String XASECURE_HBASE_POLICYMGR_URL_SAVE_FILE_PROP = "xasecure.hbase.policymgr.url.saveAsFile";
- public static final String XASECURE_HBASE_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_PROP = "xasecure.hbase.policymgr.url.reloadIntervalInMillis";
- public static final String XASECURE_HBASE_POLICYMGR_SSL_CONFIG_FILE_PROP = "xasecure.hbase.policymgr.ssl.config";
- public static final long XASECURE_HBASE_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_DEFAULT = 60000L ;
- public static final String XASECURE_HBASE_LAST_SAVED_POLICY_FILE_PROP = "xasecure.hbase.policymgr.url.laststoredfile";
-
- public static final String XASECURE_HDFS_POLICYMGR_URL_PROP = "xasecure.hdfs.policymgr.url";
- public static final String XASECURE_HDFS_POLICYMGR_URL_SAVE_FILE_PROP = "xasecure.hdfs.policymgr.url.saveAsFile";
- public static final String XASECURE_HDFS_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_PROP = "xasecure.hdfs.policymgr.url.reloadIntervalInMillis";
- public static final String XASECURE_HDFS_POLICYMGR_SSL_CONFIG_FILE_PROP = "xasecure.hdfs.policymgr.ssl.config";
- public static final long XASECURE_HDFS_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_DEFAULT = 60000L ;
- public static final String XASECURE_HDFS_LAST_SAVED_POLICY_FILE_PROP = "xasecure.hdfs.policymgr.url.laststoredfile";
-
-
- public static final String XASECURE_KNOX_POLICYMGR_URL_PROP = "xasecure.knox.policymgr.url";
- public static final String XASECURE_KNOX_POLICYMGR_URL_SAVE_FILE_PROP = "xasecure.knox.policymgr.url.saveAsFile";
- public static final String XASECURE_KNOX_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_PROP = "xasecure.knox.policymgr.url.reloadIntervalInMillis";
- public static final String XASECURE_KNOX_POLICYMGR_SSL_CONFIG_FILE_PROP = "xasecure.knox.policymgr.ssl.config";
- public static final long XASECURE_KNOX_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_DEFAULT = 60000L ;
- public static final String XASECURE_KNOX_LAST_SAVED_POLICY_FILE_PROP = "xasecure.knox.policymgr.url.laststoredfile";
-
-
- public static final String XASECURE_HIVE_POLICYMGR_URL_PROP = "xasecure.hive.policymgr.url";
- public static final String XASECURE_HIVE_POLICYMGR_URL_SAVE_FILE_PROP = "xasecure.hive.policymgr.url.saveAsFile";
- public static final String XASECURE_HIVE_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_PROP = "xasecure.hive.policymgr.url.reloadIntervalInMillis";
- public static final String XASECURE_HIVE_POLICYMGR_SSL_CONFIG_FILE_PROP = "xasecure.hive.policymgr.ssl.config";
- public static final long XASECURE_HIVE_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_DEFAULT = 60000L ;
- public static final String XASECURE_HIVE_LAST_SAVED_POLICY_FILE_PROP = "xasecure.hive.policymgr.url.laststoredfile";
-
-
- // xasecure 2-way ssl configuration
-
- public static final String XASECURE_POLICYMGR_CLIENT_KEY_FILE = "xasecure.policymgr.clientssl.keystore";
- public static final String XASECURE_POLICYMGR_CLIENT_KEY_FILE_PASSWORD = "xasecure.policymgr.clientssl.keystore.password";
- public static final String XASECURE_POLICYMGR_CLIENT_KEY_FILE_TYPE = "xasecure.policymgr.clientssl.keystore.type";
- public static final String XASECURE_POLICYMGR_CLIENT_KEY_FILE_CREDENTIAL = "xasecure.policymgr.clientssl.keystore.credential.file";
- public static final String XASECURE_POLICYMGR_CLIENT_KEY_FILE_CREDENTIAL_ALIAS = "sslKeyStore";
-
- public static final String XASECURE_POLICYMGR_CLIENT_KEY_FILE_TYPE_DEFAULT = "jks";
-
- public static final String XASECURE_POLICYMGR_TRUSTSTORE_FILE = "xasecure.policymgr.clientssl.truststore";
- public static final String XASECURE_POLICYMGR_TRUSTSTORE_FILE_PASSWORD = "xasecure.policymgr.clientssl.truststore.password";
- public static final String XASECURE_POLICYMGR_TRUSTSTORE_FILE_TYPE = "xasecure.policymgr.clientssl.truststore.type";
- public static final String XASECURE_POLICYMGR_TRUSTSTORE_FILE_CREDENTIAL = "xasecure.policymgr.clientssl.truststore.credential.file";
- public static final String XASECURE_POLICYMGR_TRUSTSTORE_FILE_CREDENTIAL_ALIAS = "sslTrustStore";
-
- public static final String XASECURE_POLICYMGR_TRUSTSTORE_FILE_TYPE_DEFAULT = "jks";
-
-
- public static final String XASECURE_SSL_KEYMANAGER_ALGO_TYPE = "SunX509" ;
- public static final String XASECURE_SSL_TRUSTMANAGER_ALGO_TYPE = "SunX509" ;
- public static final String XASECURE_SSL_CONTEXT_ALGO_TYPE = "SSL" ;
-
-
-
- public static final String XASECURE_STORM_POLICYMGR_URL_PROP = "xasecure.storm.policymgr.url";
- public static final String XASECURE_STORM_POLICYMGR_URL_SAVE_FILE_PROP = "xasecure.storm.policymgr.url.saveAsFile";
- public static final String XASECURE_STORM_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_PROP = "xasecure.storm.policymgr.url.reloadIntervalInMillis";
- public static final String XASECURE_STORM_POLICYMGR_SSL_CONFIG_FILE_PROP = "xasecure.storm.policymgr.ssl.config";
- public static final long XASECURE_STORM_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_DEFAULT = 60000L ;
- public static final String XASECURE_STORM_LAST_SAVED_POLICY_FILE_PROP = "xasecure.storm.policymgr.url.laststoredfile";
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/hbase/HBaseAuthDB.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/hbase/HBaseAuthDB.java b/agents-impl/src/main/java/com/xasecure/pdp/hbase/HBaseAuthDB.java
deleted file mode 100644
index 1a039cb..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/hbase/HBaseAuthDB.java
+++ /dev/null
@@ -1,489 +0,0 @@
-/*
- * 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 com.xasecure.pdp.hbase;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-
-import org.apache.commons.io.FilenameUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.hbase.security.User;
-import org.apache.hadoop.hbase.security.access.Permission.Action;
-import org.apache.hadoop.hbase.security.access.UserPermission;
-import org.apache.hadoop.hbase.util.Bytes;
-import org.apache.hadoop.util.StringUtils;
-
-import com.xasecure.authorization.hbase.HBaseAccessController;
-import com.xasecure.pdp.constants.XaSecureConstants;
-
-public class HBaseAuthDB implements HBaseAccessController {
-
- private static final long MAX_CACHE_AUDIT_ENTRIES = 1000L ;
- private static final long MAX_CACHE_ENCRYPT_ENTRIES = 1000L ;
-
- private static final Log LOG = LogFactory.getLog(HBaseAuthDB.class) ;
-
- private ArrayList<HBaseAuthRules> ruleList = null;
- private ArrayList<HBaseAuthRules> globalList = null;
- private ArrayList<HBaseAuthRules> tableList = null;
-
- private ArrayList<String> auditList = null ;
- private HashMap<byte[],Boolean> cachedAuditTable = new HashMap<byte[],Boolean>() ;
-
- private ArrayList<String> encryptList = null ;
-
- private HashSet<String> encryptTableList = null ;
- private HashMap<byte[],Boolean> cachedEncryptedTable = new HashMap<byte[],Boolean>() ;
-
-
- public HBaseAuthDB(ArrayList<HBaseAuthRules> ruleList, ArrayList<String> auditList, ArrayList<String> encryptList) {
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("+Creating HBaseAuthDB is creating with ruleList [" + (ruleList == null ? 0 : ruleList.size()) + "]" );
- }
-
- this.auditList = auditList;
- this.encryptList = encryptList;
-
-
- this.ruleList = new ArrayList<HBaseAuthRules>() ;
- this.globalList = new ArrayList<HBaseAuthRules>() ;
- this.tableList = new ArrayList<HBaseAuthRules>() ;
-
- for(HBaseAuthRules rule : ruleList ) {
- if (rule.isGlobalRule()) {
- this.globalList.add(rule) ;
- if (LOG.isDebugEnabled()) {
- LOG.debug("RULE:[" + rule + "] is being added as GLOBAL Policy");
- }
- }
- else if (rule.isTableRule()) {
- this.tableList.add(rule) ;
- if (LOG.isDebugEnabled()) {
- LOG.debug("RULE:[" + rule + "] is being added as Table Policy");
- }
- }
- else {
- this.ruleList.add(rule) ;
- if (LOG.isDebugEnabled()) {
- LOG.debug("RULE:[" + rule + "] is being added as non-global, non-table Policy");
- }
- }
- }
-
- this.encryptTableList = new HashSet<String>() ;
-
- if (encryptList != null && encryptList.size() > 0) {
- for(String encryptKey : encryptList) {
- String[] objKeys = encryptKey.split("/") ;
- String tableName = objKeys[0] ;
- if (! encryptTableList.contains(tableName)) {
- encryptTableList.add(tableName) ;
- if (LOG.isDebugEnabled()) {
- LOG.debug("EncryptionList:[" + tableName + "] is being added encrypted table.");
- }
- }
- }
- }
-
-
- }
-
-
- public boolean isAccessAllowed(User user, Action accessAction) {
-
-
- String access = accessAction.toString().toLowerCase() ;
-
- if (user == null) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("rulecheck(GLOBAL," + access + ") => [FALSE] as user passed for check was null.");
- }
- return false ;
- }
-
-
- String username = user.getShortName() ;
-
- String[] groups = user.getGroupNames() ;
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Init of Global access Verification - [" + access + "] for user [" + username + "], groups: [" + Arrays.toString(groups) + "]");
- }
-
- for (HBaseAuthRules rule : globalList) {
-
- if (rule.getAccessType().equals(access)) {
-
- String authorizedUser = rule.getUser() ;
- String authorizedGroup = rule.getGroup();
-
- if (authorizedGroup != null) {
- if (XaSecureConstants.PUBLIC_ACCESS_ROLE.equals(authorizedGroup)) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("rulecheck(GLOBAL," + access + "," + username + "," + StringUtils.arrayToString(groups) + ") => [TRUE] as matched for rule: " + rule);
- }
- return true ;
- }
-
- for (String group : groups) {
- if (group.equals(authorizedGroup)) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("rulecheck(GLOBAL," + access + "," + username + "," + StringUtils.arrayToString(groups) + ") => [TRUE] as matched for rule: " + rule);
- }
- return true;
- }
- }
- }
-
- if (authorizedUser != null) {
- if (username.equals(authorizedUser)) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("rulecheck(GLOBAL," + access + "," + username + "," + StringUtils.arrayToString(groups) + ") => [TRUE] as matched for rule: " + rule);
- }
- return true;
- }
- }
- }
- }
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("rulecheck(GLOBAL," + access + "," + username + "," + StringUtils.arrayToString(groups) + ") => [FALSE] as it did not match any rules.");
- }
-
- return false;
- }
-
- public boolean isAccessAllowed(User user, byte[] tableName, Action accessAction) {
-
-
- if ( isAccessAllowed(user,accessAction)) { // Check Global Action
- return true ;
- }
-
- String tableNameStr = Bytes.toString(tableName) ;
-
- String access = accessAction.toString().toLowerCase() ;
-
- if (user == null) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("rulecheck(" + tableNameStr + "," + access + ") => [FALSE] as user passed for check was null.");
- }
- return false ;
- }
-
- String username = user.getShortName() ;
-
- String[] groups = user.getGroupNames() ;
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Init of Table access Verification - [" + access + "] for user [" + username + "], groups: [" + Arrays.toString(groups) + "], tableName: [" + tableNameStr + "]");
- }
-
- for (HBaseAuthRules rule : tableList) {
-
- if (rule.isTableNameMatched(tableNameStr)) {
- if (rule.getAccessType().equals(access)) {
-
- String authorizedUser = rule.getUser() ;
-
- String authorizedGroup = rule.getGroup();
-
- if (authorizedGroup != null) {
- if (XaSecureConstants.PUBLIC_ACCESS_ROLE.equals(authorizedGroup)) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("rulecheck(" + tableNameStr + "," + access + "," + username + "," + StringUtils.arrayToString(groups) + ") => [TRUE] as matched for rule: " + rule);
- }
- return true ;
- }
-
- for (String group : groups) {
- if (group.equals(authorizedGroup)) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("rulecheck(" + tableNameStr + "," + access + "," + username + "," + StringUtils.arrayToString(groups) + ") => [TRUE] as matched for rule: " + rule);
- }
- return true;
- }
- }
- }
- if (authorizedUser != null && username.equals(authorizedUser)) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("rulecheck(" + tableNameStr + "," + access + "," + username + "," + StringUtils.arrayToString(groups) + ") => [TRUE] as matched for rule: " + rule);
- }
- return true;
- }
- }
- }
- }
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("rulecheck(" + tableNameStr + "," + access + "," + username + "," + StringUtils.arrayToString(groups) + ") => [FALSE] as it did not match any rules.");
- }
-
- return false;
- }
-
-
-
-
-
-
- public boolean isAccessAllowed(User user, byte[] tableName, byte[] columnFamily, byte[] qualifier, Action accessAction) {
-
- String FQColName = getFullyQualifiedColumnName(tableName, columnFamily, qualifier) ;
-
- String access = accessAction.toString().toLowerCase() ;
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("isAccessAllowed on HBaseAuthDB: for FQColName [" + FQColName + "]");
- }
-
-
- if (user == null) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("rulecheck(" + FQColName + "," + access + ") => [FALSE] as as user passed for check was null.");
- }
- return false ;
- }
-
-
- if (isAccessAllowed(user, accessAction)) { // Check Global Action
- return true ;
- }
-
- if (isAccessAllowed(user,tableName, accessAction)) { // Check Table Action
- return true;
- }
-
-
- String username = user.getShortName() ;
-
- String[] groups = user.getGroupNames() ;
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Init of Table access Verification - [" + access + "] for user [" + username + "], groups: [" + Arrays.toString(groups) + "], FQColumnFamily: [" + FQColName + "]");
- }
-
- for (HBaseAuthRules rule : ruleList) {
-
- if (rule.isMatched(FQColName)) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Rule [" + rule + "] matched [" + FQColName + "]");
- }
- if (rule.getAccessType().equals(access)) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Access [" + rule.getAccessType() + "] matched [" + access + "]");
- }
- String authorizedUser = rule.getUser() ;
-
- String authorizedGroup = rule.getGroup();
-
- if (authorizedGroup != null) {
- if (XaSecureConstants.PUBLIC_ACCESS_ROLE.equals(authorizedGroup)) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("rulecheck(" + FQColName + "," + access + "," + username + "," + StringUtils.arrayToString(groups) + ") => [TRUE] as matched for rule: " + rule);
- }
- return true ;
- }
- for (String group : groups) {
- if (group.equals(authorizedGroup)) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("rulecheck(" + FQColName + "," + access + "," + username + "," + StringUtils.arrayToString(groups) + ") => [TRUE] as matched for rule: " + rule);
- }
- return true;
- }
- }
- }
-
- if (authorizedUser != null) {
- if (username.equals(authorizedUser)) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("rulecheck(" + FQColName + "," + access + "," + username + "," + StringUtils.arrayToString(groups) + ") => [TRUE] as matched for rule: " + rule);
- }
- return true;
- }
- }
- }
- else {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Access [" + rule.getAccessType() + "] DID NOT match [" + access + "]");
- }
- }
- }
- else {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Rule [" + rule + "] not matched [" + FQColName + "]");
- }
- }
- }
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("rulecheck(" + FQColName + "," + access + "," + username + "," + StringUtils.arrayToString(groups) + ") => [FALSE] as it did not match any rules.");
- }
-
- return false;
-
- }
-
- public boolean isEncrypted(byte[] tableName, byte[] columnFamily, byte[] qualifier) {
- String colName = getFullyQualifiedColumnName(tableName, columnFamily, qualifier) ;
- for(String encryptable : encryptList) {
- if (FilenameUtils.wildcardMatch(colName,encryptable)) {
- return true ;
- }
- }
- return false;
- }
-
- public boolean isAudited(byte[] tableName) {
- Boolean ret = cachedAuditTable.get(tableName) ;
- if (ret == null) {
- ret = isAuditedFromTableList(tableName) ;
- synchronized(cachedAuditTable) {
- if (cachedAuditTable.size() > MAX_CACHE_AUDIT_ENTRIES) {
- cachedAuditTable.clear();
- }
- cachedAuditTable.put(tableName,ret) ;
- }
- }
- return ret.booleanValue();
- }
-
- private boolean isAuditedFromTableList(byte[] tableName) {
- boolean ret = false ;
- String tableNameStr = Bytes.toString(tableName) ;
- for(String auditable : auditList) {
- if (FilenameUtils.wildcardMatch(tableNameStr,auditable)) {
- ret = true ;
- break ;
- }
- }
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("isAudited(" + tableNameStr + "):" + ret) ;
- }
-
- return ret;
- }
-
-
- public boolean isTableHasEncryptedColumn(byte[] tableName) {
- Boolean ret = cachedEncryptedTable.get(tableName) ;
- if (ret == null) {
- ret = isTableHasEncryptedColumnFromTableList(tableName) ;
- synchronized(cachedEncryptedTable) {
- if (cachedEncryptedTable.size() > MAX_CACHE_ENCRYPT_ENTRIES) {
- cachedEncryptedTable.clear();
- }
- cachedEncryptedTable.put(tableName, ret) ;
- }
- }
- return ret.booleanValue() ;
- }
-
-
- private boolean isTableHasEncryptedColumnFromTableList(byte[] tableName)
- {
- boolean ret = false ;
-
- String tableNameStr = Bytes.toString(tableName) ;
-
- for(String encryptTable : encryptTableList) {
- ret = FilenameUtils.wildcardMatch(tableNameStr, encryptTable) ;
- if (ret) {
- break ;
- }
- }
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("isTableHasEncryptedColumn(" + tableNameStr + "):" + ret);
- }
-
- return ret ;
- }
-
-
-
- public static String getFullyQualifiedColumnName(byte[] tableName, byte[] columnFamily, byte[] qualifier) {
- StringBuilder sb = new StringBuilder() ;
-
- sb.append(((tableName != null && tableName.length > 0) ? Bytes.toString(tableName) : "*"))
- .append("/")
- .append(((columnFamily != null && columnFamily.length > 0) ? Bytes.toString(columnFamily) : "*"))
- .append("/")
- .append(((qualifier != null && qualifier.length > 0) ? Bytes.toString(qualifier) : "*")) ;
-
- return sb.toString() ;
- }
-
- public List<UserPermission> getUserPermissions(User user) {
- List<UserPermission> ret = new ArrayList<UserPermission>() ;
-
- if (user != null) {
- ArrayList<ArrayList<HBaseAuthRules>> allList = new ArrayList<ArrayList<HBaseAuthRules>>();
- allList.add(globalList) ;
- allList.add(tableList) ;
- allList.add(ruleList) ;
- for(ArrayList<HBaseAuthRules> rList : allList) {
- for(HBaseAuthRules rule : rList) {
- UserPermission perm = rule.getUserPermission(user) ;
- if (perm != null) {
- ret.add(perm) ;
- }
- }
- }
- }
-
- return ret ;
- }
-
- public List<UserPermission> getUserPermissions(User user, byte[] tableName) {
-
- String tableNameStr = Bytes.toString(tableName) ;
-
- List<UserPermission> ret = new ArrayList<UserPermission>() ;
-
- if (user != null) {
- ArrayList<ArrayList<HBaseAuthRules>> allList = new ArrayList<ArrayList<HBaseAuthRules>>();
- allList.add(globalList) ;
- allList.add(tableList) ;
- allList.add(ruleList) ;
- for(ArrayList<HBaseAuthRules> rList : allList) {
- for(HBaseAuthRules rule : rList) {
- if (rule.isTableNameMatched(tableNameStr)) {
- UserPermission perm = rule.getUserPermission(user) ;
- if (perm != null) {
- ret.add(perm) ;
- }
- }
- }
- }
- }
-
- return ret ;
- }
-
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/hbase/HBaseAuthRules.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/hbase/HBaseAuthRules.java b/agents-impl/src/main/java/com/xasecure/pdp/hbase/HBaseAuthRules.java
deleted file mode 100644
index 4a6ca53..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/hbase/HBaseAuthRules.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * 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 com.xasecure.pdp.hbase;
-
-import org.apache.commons.io.FilenameUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.hbase.TableName;
-import org.apache.hadoop.hbase.security.User;
-import org.apache.hadoop.hbase.security.access.Permission;
-import org.apache.hadoop.hbase.security.access.UserPermission;
-
-import com.xasecure.pdp.constants.XaSecureConstants;
-
-public class HBaseAuthRules {
- private String tableName ;
- private String columnGroupName;
- private String columnName ;
- private String accessType ;
- private String group ;
- private String user ;
- private String fullyQualifiedColumnName ;
-
- private static final Log LOG = LogFactory.getLog(HBaseAuthRules.class) ;
-
- public HBaseAuthRules(String tableName, String columnGroupName, String columnName, String accessType, String user, String group) {
- this.tableName = tableName;
- this.columnGroupName = columnGroupName;
- this.columnName = columnName;
- if (accessType != null) {
- this.accessType = accessType.toLowerCase() ;
- }
- this.user = user ;
- this.group = group;
- this.fullyQualifiedColumnName = tableName + "/" + columnGroupName + "/" + columnName ;
- }
-
- public String getTableName() {
- return tableName;
- }
- public String getColumnGroupName() {
- return columnGroupName;
- }
- public String getColumnName() {
- return columnName;
- }
- public String getAccessType() {
- return accessType;
- }
- public String getGroup() {
- return group;
- }
-
- public String getUser() {
- return user;
- }
-
- @Override
- public String toString() {
- return "table: " + tableName + ", columnGroup:" + columnGroupName + ", columnName: " + columnName + ", accessType: " + accessType + ", user:" + user + ", group: " + group ;
- }
-
- public boolean isMatched(String FQColName) {
- return FQColName.equals(fullyQualifiedColumnName) || FilenameUtils.wildcardMatch(FQColName,fullyQualifiedColumnName) ;
- }
-
- public boolean isGlobalRule() {
- return ("*".equals(tableName) && "*".equals(columnGroupName) && "*".equals(columnName)) ;
- }
-
- public boolean isTableRule() {
- return ( ("*".equals(columnGroupName) && "*".equals(columnName)) || ("admin".equals(accessType) || "control".equals(accessType)) ) ;
- }
-
- public boolean isTableNameMatched(String tableNameStr) {
- boolean ret = (tableNameStr == null) || (tableNameStr.equals(tableName)) || FilenameUtils.wildcardMatch(tableNameStr,tableName) ;
- if (LOG.isDebugEnabled()) {
- LOG.debug("TableMatched returns (" + tableNameStr + ", rule:" + tableName + ") returns: " + ret );
- }
- return ret ;
- }
-
- public UserPermission getUserPermission(User aUser) {
-
- if (user == null) {
- return null ;
- }
-
- Permission.Action action = null ;
-
- try {
- action = Permission.Action.valueOf(accessType.toUpperCase()) ;
- } catch (Throwable e) {
- return null ;
- }
-
- if (XaSecureConstants.PUBLIC_ACCESS_ROLE.equals(group)) {
- return new UserPermission("public".getBytes(), TableName.valueOf ( tableName ) , columnGroupName.getBytes(), columnName.getBytes(), action) ;
- }
-
- if (user != null) {
- if (aUser.getShortName().equals(user)) {
- return new UserPermission(("user:(" + aUser.getShortName() + ")").getBytes(), TableName.valueOf( tableName ) , columnGroupName.getBytes(), columnName.getBytes(), action) ;
- }
- }
-
- if (group != null) {
- for (String ugroups : aUser.getGroupNames()) {
- if (ugroups.equals(group)) {
- return new UserPermission(("group:(" + ugroups + ")").getBytes(), TableName.valueOf( tableName ) , columnGroupName.getBytes(), columnName.getBytes(), action) ;
- }
- }
- }
-
- return null;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/hbase/URLBasedAuthDB.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/hbase/URLBasedAuthDB.java b/agents-impl/src/main/java/com/xasecure/pdp/hbase/URLBasedAuthDB.java
deleted file mode 100644
index 9e599b8..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/hbase/URLBasedAuthDB.java
+++ /dev/null
@@ -1,234 +0,0 @@
-/*
- * 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 com.xasecure.pdp.hbase;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.hbase.security.User;
-import org.apache.hadoop.hbase.security.access.Permission.Action;
-import org.apache.hadoop.hbase.security.access.UserPermission;
-
-import com.xasecure.authorization.hadoop.config.XaSecureConfiguration;
-import com.xasecure.authorization.hbase.HBaseAccessController;
-import com.xasecure.pdp.config.PolicyChangeListener;
-import com.xasecure.pdp.config.PolicyRefresher;
-import com.xasecure.pdp.constants.XaSecureConstants;
-import com.xasecure.pdp.model.Policy;
-import com.xasecure.pdp.model.PolicyContainer;
-import com.xasecure.pdp.model.RolePermission;
-
-public class URLBasedAuthDB implements HBaseAccessController, PolicyChangeListener {
-
- private static final Log LOG = LogFactory.getLog(URLBasedAuthDB.class);
-
- private HBaseAuthDB authDB = null;
-
- private static URLBasedAuthDB me = null ;
-
- private PolicyRefresher refresher = null ;
-
- public static URLBasedAuthDB getInstance() {
- if (me == null) {
- synchronized(URLBasedAuthDB.class) {
- URLBasedAuthDB temp = me ;
- if (temp == null) {
- me = new URLBasedAuthDB() ;
- me.init() ;
- }
- }
- }
- return me ;
- }
-
-
- private URLBasedAuthDB() {
- String url = XaSecureConfiguration.getInstance().get(XaSecureConstants.XASECURE_HBASE_POLICYMGR_URL_PROP);
- long refreshInMilli = XaSecureConfiguration.getInstance().getLong(
- XaSecureConstants.XASECURE_HBASE_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_PROP,
- XaSecureConstants.XASECURE_HBASE_POLICYMGR_URL_RELOAD_INTERVAL_IN_MILLIS_DEFAULT);
-
- String lastStoredFileName = XaSecureConfiguration.getInstance().get(XaSecureConstants.XASECURE_HBASE_LAST_SAVED_POLICY_FILE_PROP) ;
-
- String sslConfigFileName = XaSecureConfiguration.getInstance().get(XaSecureConstants.XASECURE_HBASE_POLICYMGR_SSL_CONFIG_FILE_PROP) ;
- refresher = new PolicyRefresher(url, refreshInMilli,sslConfigFileName,lastStoredFileName) ;
-
- String saveAsFileName = XaSecureConfiguration.getInstance().get(XaSecureConstants.XASECURE_HBASE_POLICYMGR_URL_SAVE_FILE_PROP) ;
- if (saveAsFileName != null) {
- refresher.setSaveAsFileName(saveAsFileName) ;
- }
-
- if (lastStoredFileName != null) {
- refresher.setLastStoredFileName(lastStoredFileName);
- }
- }
-
- private void init() {
- refresher.setPolicyChangeListener(this);
- }
-
- public boolean isAccessAllowed(User user, Action accessAction) {
- if (authDB != null) {
- return authDB.isAccessAllowed(user, accessAction);
- } else {
- return false;
- }
- }
-
- public boolean isAccessAllowed(User user, byte[] tableName, Action accessAction) {
- if (authDB != null) {
- return authDB.isAccessAllowed(user, tableName, accessAction);
- } else {
- return false;
- }
- }
-
-
- public boolean isAccessAllowed(User user, byte[] tableName, byte[] columnFamily, byte[] qualifier, Action accessAction) {
- if (authDB != null) {
- return authDB.isAccessAllowed(user, tableName, columnFamily, qualifier, accessAction);
- } else {
- return false;
- }
- }
-
- public boolean isEncrypted(byte[] tableName, byte[] columnFamily, byte[] qualifier) {
- if (authDB != null) {
- return authDB.isEncrypted(tableName, columnFamily, qualifier);
- } else {
- return false;
- }
- }
-
- public boolean isTableHasEncryptedColumn(byte[] tableName) {
- if (authDB != null) {
- return authDB.isTableHasEncryptedColumn(tableName);
- } else {
- return false;
- }
- }
-
-
- public boolean isAudited(byte[] tableName) {
- if (authDB != null) {
- return authDB.isAudited(tableName);
- } else {
- return false;
- }
- }
-
- public List<UserPermission> getUserPermissions(User aUser) {
- if (authDB != null) {
- return authDB.getUserPermissions(aUser) ;
- } else {
- return null;
- }
- }
-
- public List<UserPermission> getUserPermissions(User aUser, byte[] aTableName) {
- if (authDB != null) {
- return authDB.getUserPermissions(aUser, aTableName) ;
- } else {
- return null;
- }
- }
-
- @Override
- public void OnPolicyChange(PolicyContainer aPolicyContainer) {
-
- if (aPolicyContainer == null) {
- return ;
- }
-
- ArrayList<HBaseAuthRules> ruleListTemp = new ArrayList<HBaseAuthRules>();
-
- HBaseAuthRules globalRule = new HBaseAuthRules(".META.", "*", "*", "read", null, XaSecureConstants.PUBLIC_ACCESS_ROLE) ;
- ruleListTemp.add(globalRule) ;
- globalRule = new HBaseAuthRules("-ROOT-", "*", "*", "read", null, XaSecureConstants.PUBLIC_ACCESS_ROLE) ;
- ruleListTemp.add(globalRule) ;
-
- ArrayList<String> auditListTemp = new ArrayList<String>();
-
- ArrayList<String> encryptList = new ArrayList<String>();
-
- for(Policy acl : aPolicyContainer.getAcl()) {
-
- if (! acl.isEnabled()) {
- LOG.debug("Diabled acl found [" + acl + "]. Skipping this acl ...") ;
- continue ;
- }
-
- for(String table : acl.getTableList()) {
- for(String colfamily : acl.getColumnFamilyList()) {
- for(String col : acl.getColumnList()) {
- if (table == null || table.isEmpty()) {
- table = "*" ;
- }
- if (colfamily == null || colfamily.isEmpty()) {
- colfamily = "*" ;
- }
- if (col == null || col.isEmpty()) {
- col = "*" ;
- }
-
- if (acl.getAuditInd() == 1) {
- if (!auditListTemp.contains(table)) {
- LOG.debug("Adding [" + table + "] to audit list");
- auditListTemp.add(table);
- }
- }
-
- if (acl.getEncryptInd() == 1) {
- String fqn = table + "/" + colfamily + "/" + col ;
- if (!encryptList.contains(fqn)) {
- LOG.debug("Adding [" + fqn + "] to encrypt list");
- encryptList.add(fqn);
- }
- }
-
- for(RolePermission rp : acl.getPermissions()) {
- for (String accessLevel : rp.getAccess() ) {
- if (rp.getGroups() != null && rp.getGroups().size() > 0) {
- for (String group : rp.getGroups()) {
- HBaseAuthRules rule = new HBaseAuthRules(table, colfamily, col, accessLevel, null, group);
- LOG.debug("Adding (group) rule: [" + rule + "]") ;
- ruleListTemp.add(rule);
- }
- }
- if (rp.getUsers() != null && rp.getUsers().size() > 0) {
- for (String user : rp.getUsers()) {
- HBaseAuthRules rule = new HBaseAuthRules(table, colfamily, col, accessLevel, user, null);
- LOG.debug("Adding (user) rule: [" + rule + "]") ;
- ruleListTemp.add(rule);
- }
- }
- }
- }
- }
- }
- }
- }
- HBaseAuthDB authDBTemp = new HBaseAuthDB(ruleListTemp, auditListTemp, encryptList);
- authDB = authDBTemp;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/hbase/XASecureAuthorizer.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/hbase/XASecureAuthorizer.java b/agents-impl/src/main/java/com/xasecure/pdp/hbase/XASecureAuthorizer.java
deleted file mode 100644
index d066070..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/hbase/XASecureAuthorizer.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * 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 com.xasecure.pdp.hbase;
-
-import java.util.List;
-
-import org.apache.hadoop.hbase.security.User;
-import org.apache.hadoop.hbase.security.access.Permission.Action;
-import org.apache.hadoop.hbase.security.access.UserPermission;
-
-import com.xasecure.authorization.hbase.HBaseAccessController;
-
-public class XASecureAuthorizer implements HBaseAccessController {
-
- private HBaseAccessController authDB = URLBasedAuthDB.getInstance();
-
- @Override
- public boolean isAccessAllowed(User user, Action accessAction) {
- if (authDB != null) {
- return authDB.isAccessAllowed(user, accessAction);
- } else {
- return false;
- }
- }
-
- @Override
- public boolean isAccessAllowed(User user, byte[] tableName, Action accessAction) {
- if (authDB != null) {
- return authDB.isAccessAllowed(user, tableName, accessAction);
- } else {
- return false;
- }
- }
-
-
- @Override
- public boolean isAccessAllowed(User user, byte[] tableName, byte[] columnFamily, byte[] qualifier, Action accessAction) {
- if (authDB != null) {
- return authDB.isAccessAllowed(user, tableName, columnFamily, qualifier, accessAction);
- } else {
- return false;
- }
- }
-
- @Override
- public boolean isEncrypted(byte[] tableName, byte[] columnFamily, byte[] qualifier) {
- if (authDB != null) {
- return authDB.isEncrypted(tableName, columnFamily, qualifier);
- } else {
- return false;
- }
- }
-
- @Override
- public boolean isTableHasEncryptedColumn(byte[] tableName) {
- if (authDB != null) {
- return authDB.isTableHasEncryptedColumn(tableName);
- } else {
- return false;
- }
- }
-
-
- @Override
- public boolean isAudited(byte[] tableName) {
- if (authDB != null) {
- return authDB.isAudited(tableName);
- } else {
- return false;
- }
- }
-
- @Override
- public List<UserPermission> getUserPermissions(User aUser) {
- if (authDB != null) {
- return authDB.getUserPermissions(aUser) ;
- } else {
- return null;
- }
- }
-
- @Override
- public List<UserPermission> getUserPermissions(User aUser, byte[] aTableName) {
- if (authDB != null) {
- return authDB.getUserPermissions(aUser, aTableName) ;
- } else {
- return null;
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/hdfs/AdminPolicyChecker.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/hdfs/AdminPolicyChecker.java b/agents-impl/src/main/java/com/xasecure/pdp/hdfs/AdminPolicyChecker.java
deleted file mode 100644
index 327c404..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/hdfs/AdminPolicyChecker.java
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- * 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 com.xasecure.pdp.hdfs;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Random;
-
-import org.apache.commons.io.FilenameUtils;
-
-public class AdminPolicyChecker {
-
- private static final String PATH_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrst0123456789-_." ;
- private static char[] PATH_CHAR_SET = PATH_CHARS.toCharArray() ;
- private static int PATH_CHAR_SET_LEN = PATH_CHAR_SET.length ;
-
-
- public static List<String> adminUserList = new ArrayList<String>() ; // "cli@adfpros.com"
- public static List<String> adminGroupList = new ArrayList<String>() ;
-
- static {
- adminUserList.add("cli@adfpros.com") ;
- adminGroupList.add("policymgradmin") ;
- }
-
-
- public void checkAdminAccessForResource(String selectedResourcePath, boolean isRecursiveFlag, String username) {
-
- if (adminUserList.contains(username)) {
- return ;
- }
-
- List<String> groups = getUserGroupsForUser(username) ;
-
- if (adminGroupList.contains(groups)) {
-
- }
-
- checkAdminAccessForResource(new Path(selectedResourcePath, isRecursiveFlag), username) ;
- }
-
- private void checkAdminAccessForResource(Path resourcePath, String username) {
-
- List<Path> adminPathList = getAdminPathFromDB(username) ;
-
- if (!adminPathList.isEmpty()) {
- for(Path adminPath : adminPathList ) {
- if (adminPath.isMatched(resourcePath)) {
- return ;
- }
- }
- }
-
- throw new SecurityException("User [" + username + "] does not have admin privileges on path [" + resourcePath + "]") ;
-
- }
-
- class Path {
- String fullPath ;
- boolean recursiveFlag ;
-
- Path(String fullPath, boolean recursiveFlag) {
- this.fullPath = fullPath;
- this.recursiveFlag = recursiveFlag;
- }
-
- public boolean isMatched(Path resourcePath) {
- // Since it is a Regular Expression Compared with Regular Expression
- // We will expand the resourcepath to a normalized form and see if it matches with the fullpath using a WildCardMatch
- // THIS IS JUST A WORK-AROUND. Need more permanent solution - 11/19/2013
-
- String expandedPath = repaceMetaChars(resourcePath) ;
-
- if (recursiveFlag) {
- return URLBasedAuthDB.isRecursiveWildCardMatch(expandedPath, fullPath) ;
- }
- else {
- return FilenameUtils.wildcardMatch(expandedPath, fullPath) ;
- }
- }
-
- private String repaceMetaChars(Path regEx) {
-
- String expandedPath = regEx.fullPath ;
-
- if (expandedPath.contains("*")) {
- String replacement = getRandomString(5,60) ;
- expandedPath.replaceAll("\\*", replacement) ;
- }
-
- if (expandedPath.contains("?")) {
- String replacement = getRandomString(1,1) ;
- expandedPath.replaceAll("\\?", replacement) ;
- }
-
- if (regEx.recursiveFlag) {
- int level = getRandomInt(3,10) ;
- if (! expandedPath.endsWith("/")) {
- expandedPath = expandedPath + "/" ;
- }
- expandedPath = expandedPath + getRandomString(5,60) ;
-
- for(int i = 1 ; i < level ; i++) {
- expandedPath = expandedPath + "/" + getRandomString(5,60) ;
- }
- }
- return expandedPath ;
- }
-
-
- private Random random = new Random() ;
-
- private String getRandomString(int minLen, int maxLen) {
- StringBuilder sb = new StringBuilder() ;
- int len = getRandomInt(minLen,maxLen) ;
- for(int i = 0 ; i < len ; i++) {
- int charIdx = random.nextInt(PATH_CHAR_SET_LEN) ;
- sb.append( PATH_CHAR_SET[charIdx] ) ;
- }
- return null;
- }
-
- private int getRandomInt(int min, int max) {
- if (min == max) {
- return min ;
- }
- else {
- int interval = max - min ;
- return ((random.nextInt() % interval) + min) ;
- }
- }
-
- }
-
-
- private List<Path> getAdminPathFromDB(String username) {
-
- List<Path> ret = new ArrayList<Path>() ;
-
- //
- // TODO: database work to get ACL ....
- //
-
- // Get all policy acl where the user has ADMIN permission +
- // Get all policy acl where group associated with user has ADMIN permission
- // For each of the acl
- // For path in acl.getResourcePath().splitBy(",")
- // ret.add(new Path(path, acl.recursiveFlag)) ;
-
- return ret;
- }
-
-
- private List<String> getUserGroupsForUser(String username) {
- List<String> groupList = new ArrayList<String>() ;
-
- //
- // TODO: database work to get List of groups ....
- //
-
- return groupList ;
- }
-
-
-
-}
[23/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/common/SearchField.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/SearchField.java b/security-admin/src/main/java/com/xasecure/common/SearchField.java
deleted file mode 100644
index 03f0315..0000000
--- a/security-admin/src/main/java/com/xasecure/common/SearchField.java
+++ /dev/null
@@ -1,218 +0,0 @@
-/*
- * 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 com.xasecure.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/com/xasecure/common/SearchGroup.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/SearchGroup.java b/security-admin/src/main/java/com/xasecure/common/SearchGroup.java
deleted file mode 100644
index 7702eba..0000000
--- a/security-admin/src/main/java/com/xasecure/common/SearchGroup.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * 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 com.xasecure.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/com/xasecure/common/SearchUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/SearchUtil.java b/security-admin/src/main/java/com/xasecure/common/SearchUtil.java
deleted file mode 100644
index d097a06..0000000
--- a/security-admin/src/main/java/com/xasecure/common/SearchUtil.java
+++ /dev/null
@@ -1,819 +0,0 @@
-/*
- * 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 com.xasecure.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/com/xasecure/common/SearchValue.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/SearchValue.java b/security-admin/src/main/java/com/xasecure/common/SearchValue.java
deleted file mode 100644
index 611d8bf..0000000
--- a/security-admin/src/main/java/com/xasecure/common/SearchValue.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * 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 com.xasecure.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/com/xasecure/common/SortField.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/SortField.java b/security-admin/src/main/java/com/xasecure/common/SortField.java
deleted file mode 100644
index 5e8aaf5..0000000
--- a/security-admin/src/main/java/com/xasecure/common/SortField.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * 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 com.xasecure.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/com/xasecure/common/StringUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/StringUtil.java b/security-admin/src/main/java/com/xasecure/common/StringUtil.java
deleted file mode 100644
index 458bce9..0000000
--- a/security-admin/src/main/java/com/xasecure/common/StringUtil.java
+++ /dev/null
@@ -1,262 +0,0 @@
-/*
- * 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 com.xasecure.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/com/xasecure/common/TimedEventUtil.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/TimedEventUtil.java b/security-admin/src/main/java/com/xasecure/common/TimedEventUtil.java
deleted file mode 100644
index a81469a..0000000
--- a/security-admin/src/main/java/com/xasecure/common/TimedEventUtil.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * 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 com.xasecure.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/com/xasecure/common/UserSessionBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/common/UserSessionBase.java b/security-admin/src/main/java/com/xasecure/common/UserSessionBase.java
deleted file mode 100644
index 5b9a942..0000000
--- a/security-admin/src/main/java/com/xasecure/common/UserSessionBase.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * 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 com.xasecure.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 com.xasecure.entity.XXAuthSession;
-import com.xasecure.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;
- }
-
-}
[19/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/entity/XXPortalUser.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/entity/XXPortalUser.java b/security-admin/src/main/java/com/xasecure/entity/XXPortalUser.java
deleted file mode 100644
index 5b9c45e..0000000
--- a/security-admin/src/main/java/com/xasecure/entity/XXPortalUser.java
+++ /dev/null
@@ -1,378 +0,0 @@
-/*
- * 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 com.xasecure.entity;
-
-/**
- * User details
- *
- */
-
-import java.util.*;
-import javax.persistence.*;
-import javax.xml.bind.annotation.*;
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-
-
-@Entity
-@Table(name="x_portal_user")
-@XmlRootElement
-public class XXPortalUser extends XXDBBase implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
- @Id
- @SequenceGenerator(name="X_PORTAL_USER_SEQ",sequenceName="X_PORTAL_USER_SEQ",allocationSize=1)
- @GeneratedValue(strategy=GenerationType.AUTO,generator="X_PORTAL_USER_SEQ")
- @Column(name="ID")
- protected Long id;
- @Override
- public void setId(Long id) {
- // TODO Auto-generated method stub
- this.id=id;
- }
- @Override
- public Long getId() {
- // TODO Auto-generated method stub
- return id;
- }
- /**
- * First name of the user
- * <ul>
- * <li>The maximum length for this attribute is <b>1022</b>.
- * </ul>
- *
- */
- @Column(name="FIRST_NAME" , length=1022)
- protected String firstName;
-
- /**
- * Last name of the user
- * <ul>
- * <li>The maximum length for this attribute is <b>1022</b>.
- * </ul>
- *
- */
- @Column(name="LAST_NAME" , length=1022)
- protected String lastName;
-
- /**
- * Public screen name for the user
- * <ul>
- * <li>The maximum length for this attribute is <b>2048</b>.
- * </ul>
- *
- */
- @Column(name="PUB_SCR_NAME" , length=2048)
- protected String publicScreenName;
-
- /**
- * Login ID of the user
- * <ul>
- * <li>The maximum length for this attribute is <b>767</b>.
- * </ul>
- *
- */
- @Column(name="LOGIN_ID" , unique=true , length=767)
- protected String loginId;
-
- /**
- * <ul>
- * <li>The maximum length for this attribute is <b>512</b>.
- * </ul>
- *
- */
- @Column(name="PASSWORD" , nullable=false , length=512)
- protected String password;
-
- /**
- * Email address of the user
- * <ul>
- * <li>The maximum length for this attribute is <b>512</b>.
- * </ul>
- *
- */
- @Column(name="EMAIL" , unique=true , length=512)
- protected String emailAddress;
-
- /**
- * Status of the user
- * <ul>
- * <li>This attribute is of type enum CommonEnums::ActivationStatus
- * </ul>
- *
- */
- @Column(name="STATUS" , nullable=false )
- protected int status = XAConstants.ACT_STATUS_DISABLED;
-
- /**
- * Source of the user
- * <ul>
- * <li>This attribute is of type enum CommonEnums::UserSource
- * </ul>
- *
- */
- @Column(name="USER_SRC" , nullable=false )
- protected int userSource = XAConstants.USER_APP;
-
- /**
- * Note
- * <ul>
- * <li>The maximum length for this attribute is <b>4000</b>.
- * </ul>
- *
- */
- @Column(name="NOTES" , length=4000)
- protected String notes;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public XXPortalUser ( ) {
- status = XAConstants.ACT_STATUS_DISABLED;
- userSource = XAConstants.USER_APP;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_USER_PROFILE;
- }
-
- /**
- * This method sets the value to the member attribute <b>firstName</b>.
- * You cannot set null to the attribute.
- * @param firstName Value to set member attribute <b>firstName</b>
- */
- public void setFirstName( String firstName ) {
- this.firstName = firstName;
- }
-
- /**
- * Returns the value for the member attribute <b>firstName</b>
- * @return String - value of member attribute <b>firstName</b>.
- */
- public String getFirstName( ) {
- return this.firstName;
- }
-
- /**
- * This method sets the value to the member attribute <b>lastName</b>.
- * You cannot set null to the attribute.
- * @param lastName Value to set member attribute <b>lastName</b>
- */
- public void setLastName( String lastName ) {
- this.lastName = lastName;
- }
-
- /**
- * Returns the value for the member attribute <b>lastName</b>
- * @return String - value of member attribute <b>lastName</b>.
- */
- public String getLastName( ) {
- return this.lastName;
- }
-
- /**
- * This method sets the value to the member attribute <b>publicScreenName</b>.
- * You cannot set null to the attribute.
- * @param publicScreenName Value to set member attribute <b>publicScreenName</b>
- */
- public void setPublicScreenName( String publicScreenName ) {
- this.publicScreenName = publicScreenName;
- }
-
- /**
- * Returns the value for the member attribute <b>publicScreenName</b>
- * @return String - value of member attribute <b>publicScreenName</b>.
- */
- public String getPublicScreenName( ) {
- return this.publicScreenName;
- }
-
- /**
- * This method sets the value to the member attribute <b>loginId</b>.
- * You cannot set null to the attribute.
- * @param loginId Value to set member attribute <b>loginId</b>
- */
- public void setLoginId( String loginId ) {
- this.loginId = loginId;
- }
-
- /**
- * Returns the value for the member attribute <b>loginId</b>
- * @return String - value of member attribute <b>loginId</b>.
- */
- public String getLoginId( ) {
- return this.loginId;
- }
-
- /**
- * This method sets the value to the member attribute <b>password</b>.
- * You cannot set null to the attribute.
- * @param password Value to set member attribute <b>password</b>
- */
- public void setPassword( String password ) {
- this.password = password;
- }
-
- /**
- * Returns the value for the member attribute <b>password</b>
- * @return String - value of member attribute <b>password</b>.
- */
- public String getPassword( ) {
- return this.password;
- }
-
- /**
- * This method sets the value to the member attribute <b>emailAddress</b>.
- * You cannot set null to the attribute.
- * @param emailAddress Value to set member attribute <b>emailAddress</b>
- */
- public void setEmailAddress( String emailAddress ) {
- this.emailAddress = emailAddress;
- }
-
- /**
- * Returns the value for the member attribute <b>emailAddress</b>
- * @return String - value of member attribute <b>emailAddress</b>.
- */
- public String getEmailAddress( ) {
- return this.emailAddress;
- }
-
- /**
- * This method sets the value to the member attribute <b>status</b>.
- * You cannot set null to the attribute.
- * @param status Value to set member attribute <b>status</b>
- */
- public void setStatus( int status ) {
- this.status = status;
- }
-
- /**
- * Returns the value for the member attribute <b>status</b>
- * @return int - value of member attribute <b>status</b>.
- */
- public int getStatus( ) {
- return this.status;
- }
-
- /**
- * This method sets the value to the member attribute <b>userSource</b>.
- * You cannot set null to the attribute.
- * @param userSource Value to set member attribute <b>userSource</b>
- */
- public void setUserSource( int userSource ) {
- this.userSource = userSource;
- }
-
- /**
- * Returns the value for the member attribute <b>userSource</b>
- * @return int - value of member attribute <b>userSource</b>.
- */
- public int getUserSource( ) {
- return this.userSource;
- }
-
- /**
- * This method sets the value to the member attribute <b>notes</b>.
- * You cannot set null to the attribute.
- * @param notes Value to set member attribute <b>notes</b>
- */
- public void setNotes( String notes ) {
- this.notes = notes;
- }
-
- /**
- * Returns the value for the member attribute <b>notes</b>
- * @return String - value of member attribute <b>notes</b>.
- */
- public String getNotes( ) {
- return this.notes;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- @Override
- public String toString( ) {
- String str = "XXPortalUser={";
- str += super.toString();
- str += "firstName={" + firstName + "} ";
- str += "lastName={" + lastName + "} ";
- str += "publicScreenName={" + publicScreenName + "} ";
- str += "loginId={" + loginId + "} ";
- str += "password={***length=" + (password == null? 0 : password.length()) + "***} ";
- str += "emailAddress={" + emailAddress + "} ";
- str += "status={" + status + "} ";
- str += "userSource={" + userSource + "} ";
- str += "notes={" + notes + "} ";
- str += "}";
- return str;
- }
-
- /**
- * Checks for all attributes except referenced db objects
- * @return true if all attributes match
- */
- @Override
- public boolean equals( Object obj) {
- if ( !super.equals(obj) ) {
- return false;
- }
- XXPortalUser other = (XXPortalUser) obj;
- if ((this.firstName == null && other.firstName != null) || (this.firstName != null && !this.firstName.equals(other.firstName))) {
- return false;
- }
- if ((this.lastName == null && other.lastName != null) || (this.lastName != null && !this.lastName.equals(other.lastName))) {
- return false;
- }
- if ((this.publicScreenName == null && other.publicScreenName != null) || (this.publicScreenName != null && !this.publicScreenName.equals(other.publicScreenName))) {
- return false;
- }
- if ((this.loginId == null && other.loginId != null) || (this.loginId != null && !this.loginId.equals(other.loginId))) {
- return false;
- }
- if ((this.password == null && other.password != null) || (this.password != null && !this.password.equals(other.password))) {
- return false;
- }
- if ((this.emailAddress == null && other.emailAddress != null) || (this.emailAddress != null && !this.emailAddress.equals(other.emailAddress))) {
- return false;
- }
- if( this.status != other.status ) return false;
- if( this.userSource != other.userSource ) return false;
- if ((this.notes == null && other.notes != null) || (this.notes != null && !this.notes.equals(other.notes))) {
- return false;
- }
- return true;
- }
- public static String getEnumName(String fieldName ) {
- if( fieldName.equals("status") ) {
- return "CommonEnums.ActivationStatus";
- }
- if( fieldName.equals("userSource") ) {
- return "CommonEnums.UserSource";
- }
- //Later TODO
- //return super.getEnumName(fieldName);
- return null;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/entity/XXPortalUserRole.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/entity/XXPortalUserRole.java b/security-admin/src/main/java/com/xasecure/entity/XXPortalUserRole.java
deleted file mode 100644
index 8dbd912..0000000
--- a/security-admin/src/main/java/com/xasecure/entity/XXPortalUserRole.java
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * 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 com.xasecure.entity;
-
-/**
- * Role of the user
- *
- */
-
-import java.util.*;
-import javax.persistence.*;
-import javax.xml.bind.annotation.*;
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-
-
-@Entity
-@Table(name="x_portal_user_role")
-@XmlRootElement
-public class XXPortalUserRole extends XXDBBase implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- @Id
- @SequenceGenerator(name="X_PORTAL_USER_ROLE_SEQ",sequenceName="X_PORTAL_USER_ROLE_SEQ",allocationSize=1)
- @GeneratedValue(strategy=GenerationType.AUTO,generator="X_PORTAL_USER_ROLE_SEQ")
- @Column(name="ID")
- protected Long id;
- @Override
- public void setId(Long id) {
- this.id=id;
- }
- @Override
- public Long getId() {
- return id;
- }
- /**
- * Id of the user
- * <ul>
- * </ul>
- *
- */
- @Column(name="USER_ID" , nullable=false )
- protected Long userId;
-
-
- /**
- * Role of the user
- * <ul>
- * <li>The maximum length for this attribute is <b>128</b>.
- * </ul>
- *
- */
- @Column(name="USER_ROLE" , length=128)
- protected String userRole;
-
- /**
- * Status
- * <ul>
- * <li>This attribute is of type enum CommonEnums::ActiveStatus
- * </ul>
- *
- */
- @Column(name="STATUS" , nullable=false )
- protected int status = XAConstants.STATUS_DISABLED;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public XXPortalUserRole ( ) {
- status = XAConstants.STATUS_DISABLED;
- }
-
- /**
- * This method sets the value to the member attribute <b>userId</b>.
- * You cannot set null to the attribute.
- * @param userId Value to set member attribute <b>userId</b>
- */
- public void setUserId( Long userId ) {
- this.userId = userId;
- }
-
- /**
- * Returns the value for the member attribute <b>userId</b>
- * @return Long - value of member attribute <b>userId</b>.
- */
- public Long getUserId( ) {
- return this.userId;
- }
-
-
- /**
- * This method sets the value to the member attribute <b>userRole</b>.
- * You cannot set null to the attribute.
- * @param userRole Value to set member attribute <b>userRole</b>
- */
- public void setUserRole( String userRole ) {
- this.userRole = userRole;
- }
-
- /**
- * Returns the value for the member attribute <b>userRole</b>
- * @return String - value of member attribute <b>userRole</b>.
- */
- public String getUserRole( ) {
- return this.userRole;
- }
-
- /**
- * This method sets the value to the member attribute <b>status</b>.
- * You cannot set null to the attribute.
- * @param status Value to set member attribute <b>status</b>
- */
- public void setStatus( int status ) {
- this.status = status;
- }
-
- /**
- * Returns the value for the member attribute <b>status</b>
- * @return int - value of member attribute <b>status</b>.
- */
- public int getStatus( ) {
- return this.status;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- @Override
- public String toString( ) {
- String str = "XXPortalUserRole={";
- str += super.toString();
- str += "userId={" + userId + "} ";
- str += "userRole={" + userRole + "} ";
- str += "status={" + status + "} ";
- str += "}";
- return str;
- }
-
- /**
- * Checks for all attributes except referenced db objects
- * @return true if all attributes match
- */
- @Override
- public boolean equals( Object obj) {
- if ( !super.equals(obj) ) {
- return false;
- }
- XXPortalUserRole other = (XXPortalUserRole) obj;
- if ((this.userId == null && other.userId != null) || (this.userId != null && !this.userId.equals(other.userId))) {
- return false;
- }
- if ((this.userRole == null && other.userRole != null) || (this.userRole != null && !this.userRole.equals(other.userRole))) {
- return false;
- }
- if( this.status != other.status ) return false;
- return true;
- }
- public static String getEnumName(String fieldName ) {
- if( fieldName.equals("status") ) {
- return "CommonEnums.ActiveStatus";
- }
- //Later TODO
- //return super.getEnumName(fieldName);
- return null;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/entity/XXResource.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/entity/XXResource.java b/security-admin/src/main/java/com/xasecure/entity/XXResource.java
deleted file mode 100644
index 5b38d93..0000000
--- a/security-admin/src/main/java/com/xasecure/entity/XXResource.java
+++ /dev/null
@@ -1,717 +0,0 @@
-/*
- * 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 com.xasecure.entity;
-
-/**
- * Resource
- *
- */
-
-import java.util.*;
-import javax.persistence.*;
-import javax.xml.bind.annotation.*;
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-
-
-@Entity
-@Table(name="x_resource")
-@XmlRootElement
-public class XXResource extends XXDBBase implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- @Id
- @SequenceGenerator(name="X_RESOURCE_SEQ",sequenceName="X_RESOURCE_SEQ",allocationSize=1)
- @GeneratedValue(strategy=GenerationType.AUTO,generator="X_RESOURCE_SEQ")
- @Column(name="ID")
- protected Long id;
- @Override
- public void setId(Long id) {
- this.id=id;
- }
- @Override
- public Long getId() {
- return id;
- }
- /**
- * Name
- * <ul>
- * <li>The maximum length for this attribute is <b>4000</b>.
- * </ul>
- *
- */
- @Column(name="RES_NAME" , length=4000)
- protected String name;
-
- @Column(name="POLICY_NAME" , length=500)
- protected String policyName;
- /**
- * Description
- * <ul>
- * <li>The maximum length for this attribute is <b>4000</b>.
- * </ul>
- *
- */
- @Column(name="DESCR" , length=4000)
- protected String description;
-
- /**
- * Status
- * <ul>
- * <li>This attribute is of type enum CommonEnums::ResourceType
- * </ul>
- *
- */
- @Column(name="RES_TYPE" , nullable=false )
- protected int resourceType = AppConstants.RESOURCE_PATH;
-
- /**
- * Id of the asset
- * <ul>
- * </ul>
- *
- */
- @Column(name="ASSET_ID" , nullable=false )
- protected Long assetId;
-
-
- /**
- * Id of the parent
- * <ul>
- * </ul>
- *
- */
- @Column(name="PARENT_ID" )
- protected Long parentId;
-
-
- /**
- * Path for the parent
- * <ul>
- * <li>The maximum length for this attribute is <b>4000</b>.
- * </ul>
- *
- */
- @Column(name="PARENT_PATH" , length=4000)
- protected String parentPath;
-
- /**
- * Whether to encrypt this resource
- * <ul>
- * <li>This attribute is of type enum CommonEnums::BooleanValue
- * </ul>
- *
- */
- @Column(name="IS_ENCRYPT" , nullable=false )
- protected int isEncrypt = XAConstants.BOOL_FALSE;
-
- /**
- * Is recursive
- * <ul>
- * <li>This attribute is of type enum CommonEnums::BooleanValue
- * </ul>
- *
- */
- @Column(name="IS_RECURSIVE" , nullable=false )
- protected int isRecursive = XAConstants.BOOL_NONE;
-
- /**
- * Group to which this resource belongs to
- * <ul>
- * <li>The maximum length for this attribute is <b>1024</b>.
- * </ul>
- *
- */
- @Column(name="RES_GROUP" , length=1024)
- protected String resourceGroup;
-
- /**
- * Databases
- * <ul>
- * <li>The maximum length for this attribute is <b>10000</b>.
- * </ul>
- *
- */
- @Column(name="RES_DBS" , length=10000)
- protected String databases;
-
- /**
- * Tables
- * <ul>
- * <li>The maximum length for this attribute is <b>10000</b>.
- * </ul>
- *
- */
- @Column(name="RES_TABLES" , length=10000)
- protected String tables;
-
- /**
- * Column families
- * <ul>
- * <li>The maximum length for this attribute is <b>10000</b>.
- * </ul>
- *
- */
- @Column(name="RES_COL_FAMS" , length=10000)
- protected String columnFamilies;
-
- /**
- * Columns
- * <ul>
- * <li>The maximum length for this attribute is <b>10000</b>.
- * </ul>
- *
- */
- @Column(name="RES_COLS" , length=10000)
- protected String columns;
-
- /**
- * UDFs
- * <ul>
- * <li>The maximum length for this attribute is <b>10000</b>.
- * </ul>
- *
- */
- @Column(name="RES_UDFS" , length=10000)
- protected String udfs;
-
- /**
- * Resource Status
- * <ul>
- * <li>This attribute is of type enum CommonEnums::ActiveStatus
- * </ul>
- *
- */
- @Column(name="RES_STATUS" , nullable=false )
- protected int resourceStatus = XAConstants.STATUS_ENABLED;
-
- /**
- * Table Type
- * <ul>
- * <li>This attribute is of type enum CommonEnums::PolicyType
- * </ul>
- *
- */
- @Column(name="TABLE_TYPE" , nullable=false )
- protected int tableType = AppConstants.POLICY_INCLUSION;
-
- /**
- * Resource Status
- * <ul>
- * <li>This attribute is of type enum CommonEnums::PolicyType
- * </ul>
- *
- */
- @Column(name="COL_TYPE" , nullable=false )
- protected int columnType = AppConstants.POLICY_INCLUSION;
- /**
- * Topologoies
- * <ul>
- * <li>The maximum length for this attribute is <b>10000</b>.
- * </ul>
- *
- */
- @Column(name="RES_TOPOLOGIES" , length=10000)
- protected String topologies;
- /**
- * SERVICENAMES
- * <ul>
- * <li>The maximum length for this attribute is <b>10000</b>.
- * </ul>
- *
- */
- @Column(name="RES_SERVICES" , length=10000)
- protected String services;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public XXResource ( ) {
- resourceType = AppConstants.RESOURCE_PATH;
- isEncrypt = XAConstants.BOOL_FALSE;
- isRecursive = XAConstants.BOOL_NONE;
- resourceStatus = XAConstants.STATUS_ENABLED;
- tableType = AppConstants.POLICY_INCLUSION;
- columnType = AppConstants.POLICY_INCLUSION;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_XA_RESOURCE;
- }
-
- @Override
- public String getMyDisplayValue() {
- return getDescription( );
- }
-
- /**
- * This method sets the value to the member attribute <b>name</b>.
- * You cannot set null to the attribute.
- * @param name Value to set member attribute <b>name</b>
- */
- public void setName( String name ) {
- this.name = name;
- }
-
- public String getPolicyName() {
- return policyName;
- }
-
- public void setPolicyName(String policyName) {
- this.policyName = policyName;
- }
-
- /**
- * Returns the value for the member attribute <b>name</b>
- * @return String - value of member attribute <b>name</b>.
- */
- public String getName( ) {
- return this.name;
- }
-
- /**
- * This method sets the value to the member attribute <b>description</b>.
- * You cannot set null to the attribute.
- * @param description Value to set member attribute <b>description</b>
- */
- public void setDescription( String description ) {
- this.description = description;
- }
-
- /**
- * Returns the value for the member attribute <b>description</b>
- * @return String - value of member attribute <b>description</b>.
- */
- public String getDescription( ) {
- return this.description;
- }
-
- /**
- * This method sets the value to the member attribute <b>resourceType</b>.
- * You cannot set null to the attribute.
- * @param resourceType Value to set member attribute <b>resourceType</b>
- */
- public void setResourceType( int resourceType ) {
- this.resourceType = resourceType;
- }
-
- /**
- * Returns the value for the member attribute <b>resourceType</b>
- * @return int - value of member attribute <b>resourceType</b>.
- */
- public int getResourceType( ) {
- return this.resourceType;
- }
-
- /**
- * This method sets the value to the member attribute <b>assetId</b>.
- * You cannot set null to the attribute.
- * @param assetId Value to set member attribute <b>assetId</b>
- */
- public void setAssetId( Long assetId ) {
- this.assetId = assetId;
- }
-
- /**
- * Returns the value for the member attribute <b>assetId</b>
- * @return Long - value of member attribute <b>assetId</b>.
- */
- public Long getAssetId( ) {
- return this.assetId;
- }
-
-
- /**
- * This method sets the value to the member attribute <b>parentId</b>.
- * You cannot set null to the attribute.
- * @param parentId Value to set member attribute <b>parentId</b>
- */
- public void setParentId( Long parentId ) {
- this.parentId = parentId;
- }
-
- /**
- * Returns the value for the member attribute <b>parentId</b>
- * @return Long - value of member attribute <b>parentId</b>.
- */
- public Long getParentId( ) {
- return this.parentId;
- }
-
-
- /**
- * This method sets the value to the member attribute <b>parentPath</b>.
- * You cannot set null to the attribute.
- * @param parentPath Value to set member attribute <b>parentPath</b>
- */
- public void setParentPath( String parentPath ) {
- this.parentPath = parentPath;
- }
-
- /**
- * Returns the value for the member attribute <b>parentPath</b>
- * @return String - value of member attribute <b>parentPath</b>.
- */
- public String getParentPath( ) {
- return this.parentPath;
- }
-
- /**
- * This method sets the value to the member attribute <b>isEncrypt</b>.
- * You cannot set null to the attribute.
- * @param isEncrypt Value to set member attribute <b>isEncrypt</b>
- */
- public void setIsEncrypt( int isEncrypt ) {
- this.isEncrypt = isEncrypt;
- }
-
- /**
- * Returns the value for the member attribute <b>isEncrypt</b>
- * @return int - value of member attribute <b>isEncrypt</b>.
- */
- public int getIsEncrypt( ) {
- return this.isEncrypt;
- }
-
- /**
- * This method sets the value to the member attribute <b>isRecursive</b>.
- * You cannot set null to the attribute.
- * @param isRecursive Value to set member attribute <b>isRecursive</b>
- */
- public void setIsRecursive( int isRecursive ) {
- this.isRecursive = isRecursive;
- }
-
- /**
- * Returns the value for the member attribute <b>isRecursive</b>
- * @return int - value of member attribute <b>isRecursive</b>.
- */
- public int getIsRecursive( ) {
- return this.isRecursive;
- }
-
- /**
- * This method sets the value to the member attribute <b>resourceGroup</b>.
- * You cannot set null to the attribute.
- * @param resourceGroup Value to set member attribute <b>resourceGroup</b>
- */
- public void setResourceGroup( String resourceGroup ) {
- this.resourceGroup = resourceGroup;
- }
-
- /**
- * Returns the value for the member attribute <b>resourceGroup</b>
- * @return String - value of member attribute <b>resourceGroup</b>.
- */
- public String getResourceGroup( ) {
- return this.resourceGroup;
- }
-
- /**
- * This method sets the value to the member attribute <b>databases</b>.
- * You cannot set null to the attribute.
- * @param databases Value to set member attribute <b>databases</b>
- */
- public void setDatabases( String databases ) {
- this.databases = databases;
- }
-
- /**
- * Returns the value for the member attribute <b>databases</b>
- * @return String - value of member attribute <b>databases</b>.
- */
- public String getDatabases( ) {
- return this.databases;
- }
-
- /**
- * This method sets the value to the member attribute <b>tables</b>.
- * You cannot set null to the attribute.
- * @param tables Value to set member attribute <b>tables</b>
- */
- public void setTables( String tables ) {
- this.tables = tables;
- }
-
- /**
- * Returns the value for the member attribute <b>tables</b>
- * @return String - value of member attribute <b>tables</b>.
- */
- public String getTables( ) {
- return this.tables;
- }
-
- /**
- * This method sets the value to the member attribute <b>columnFamilies</b>.
- * You cannot set null to the attribute.
- * @param columnFamilies Value to set member attribute <b>columnFamilies</b>
- */
- public void setColumnFamilies( String columnFamilies ) {
- this.columnFamilies = columnFamilies;
- }
-
- /**
- * Returns the value for the member attribute <b>columnFamilies</b>
- * @return String - value of member attribute <b>columnFamilies</b>.
- */
- public String getColumnFamilies( ) {
- return this.columnFamilies;
- }
-
- /**
- * This method sets the value to the member attribute <b>columns</b>.
- * You cannot set null to the attribute.
- * @param columns Value to set member attribute <b>columns</b>
- */
- public void setColumns( String columns ) {
- this.columns = columns;
- }
-
- /**
- * Returns the value for the member attribute <b>columns</b>
- * @return String - value of member attribute <b>columns</b>.
- */
- public String getColumns( ) {
- return this.columns;
- }
-
- /**
- * This method sets the value to the member attribute <b>udfs</b>.
- * You cannot set null to the attribute.
- * @param udfs Value to set member attribute <b>udfs</b>
- */
- public void setUdfs( String udfs ) {
- this.udfs = udfs;
- }
-
- /**
- * Returns the value for the member attribute <b>udfs</b>
- * @return String - value of member attribute <b>udfs</b>.
- */
- public String getUdfs( ) {
- return this.udfs;
- }
-
- /**
- * This method sets the value to the member attribute <b>resourceStatus</b>.
- * You cannot set null to the attribute.
- * @param resourceStatus Value to set member attribute <b>resourceStatus</b>
- */
- public void setResourceStatus( int resourceStatus ) {
- this.resourceStatus = resourceStatus;
- }
-
- /**
- * Returns the value for the member attribute <b>resourceStatus</b>
- * @return int - value of member attribute <b>resourceStatus</b>.
- */
- public int getResourceStatus( ) {
- return this.resourceStatus;
- }
-
- /**
- * This method sets the value to the member attribute <b>tableType</b>.
- * You cannot set null to the attribute.
- * @param tableType Value to set member attribute <b>tableType</b>
- */
- public void setTableType( int tableType ) {
- this.tableType = tableType;
- }
-
- /**
- * Returns the value for the member attribute <b>tableType</b>
- * @return int - value of member attribute <b>tableType</b>.
- */
- public int getTableType( ) {
- return this.tableType;
- }
-
- /**
- * This method sets the value to the member attribute <b>columnType</b>.
- * You cannot set null to the attribute.
- * @param columnType Value to set member attribute <b>columnType</b>
- */
- public void setColumnType( int columnType ) {
- this.columnType = columnType;
- }
-
- /**
- * Returns the value for the member attribute <b>columnType</b>
- * @return int - value of member attribute <b>columnType</b>.
- */
- public int getColumnType( ) {
- return this.columnType;
- }
-
- /**
- * Returns the value for the member attribute <b>topologies</b>
- * @return String - value of member attribute <b>topologies</b>.
- */
- public String getTopologies() {
- return topologies;
- }
-
- /**
- * This method sets the value to the member attribute <b>topologies</b>.
- * You cannot set null to the attribute.
- * @param topologies Value to set member attribute <b>topologies</b>
- */
- public void setTopologies(String topologies) {
- this.topologies = topologies;
- }
-
- /**
- * Returns the value for the member attribute <b>services</b>
- * @return String - value of member attribute <b>services</b>.
- */
- public String getServices() {
- return services;
- }
-
- /**
- * This method sets the value to the member attribute <b>services</b>.
- * You cannot set null to the attribute.
- * @param services Value to set member attribute <b>services</b>
- */
- public void setServices(String services) {
- this.services = services;
- }
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- @Override
- public String toString( ) {
- String str = "XXResource={";
- str += super.toString();
- str += "name={" + name + "} ";
- str += "policyName={" + policyName + "} ";
- str += "description={" + description + "} ";
- str += "resourceType={" + resourceType + "} ";
- str += "assetId={" + assetId + "} ";
- str += "parentId={" + parentId + "} ";
- str += "parentPath={" + parentPath + "} ";
- str += "isEncrypt={" + isEncrypt + "} ";
- str += "isRecursive={" + isRecursive + "} ";
- str += "resourceGroup={" + resourceGroup + "} ";
- str += "databases={" + databases + "} ";
- str += "tables={" + tables + "} ";
- str += "columnFamilies={" + columnFamilies + "} ";
- str += "columns={" + columns + "} ";
- str += "udfs={" + udfs + "} ";
- str += "resourceStatus={" + resourceStatus + "} ";
- str += "tableType={" + tableType + "} ";
- str += "columnType={" + columnType + "} ";
- str += "topologies={" + topologies + "} ";
- str += "services={" + services + "} ";
- str += "}";
- return str;
- }
-
- /**
- * Checks for all attributes except referenced db objects
- * @return true if all attributes match
- */
- @Override
- public boolean equals( Object obj) {
- if ( !super.equals(obj) ) {
- return false;
- }
- XXResource other = (XXResource) obj;
- if ((this.name == null && other.name != null) || (this.name != null && !this.name.equals(other.name))) {
- return false;
- }
- if ((this.description == null && other.description != null) || (this.description != null && !this.description.equals(other.description))) {
- return false;
- }
- if( this.resourceType != other.resourceType ) return false;
- if ((this.assetId == null && other.assetId != null) || (this.assetId != null && !this.assetId.equals(other.assetId))) {
- return false;
- }
- if ((this.parentId == null && other.parentId != null) || (this.parentId != null && !this.parentId.equals(other.parentId))) {
- return false;
- }
- if ((this.parentPath == null && other.parentPath != null) || (this.parentPath != null && !this.parentPath.equals(other.parentPath))) {
- return false;
- }
- if( this.isEncrypt != other.isEncrypt ) return false;
- if( this.isRecursive != other.isRecursive ) return false;
- if ((this.resourceGroup == null && other.resourceGroup != null) || (this.resourceGroup != null && !this.resourceGroup.equals(other.resourceGroup))) {
- return false;
- }
- if ((this.databases == null && other.databases != null) || (this.databases != null && !this.databases.equals(other.databases))) {
- return false;
- }
- if ((this.tables == null && other.tables != null) || (this.tables != null && !this.tables.equals(other.tables))) {
- return false;
- }
- if ((this.columnFamilies == null && other.columnFamilies != null) || (this.columnFamilies != null && !this.columnFamilies.equals(other.columnFamilies))) {
- return false;
- }
- if ((this.columns == null && other.columns != null) || (this.columns != null && !this.columns.equals(other.columns))) {
- return false;
- }
- if ((this.udfs == null && other.udfs != null) || (this.udfs != null && !this.udfs.equals(other.udfs))) {
- return false;
- }
- if( this.resourceStatus != other.resourceStatus ) return false;
- if( this.tableType != other.tableType ) return false;
- if( this.columnType != other.columnType ) return false;
-
- if ((this.topologies == null && other.topologies != null)
- || (this.topologies != null && !this.topologies.equals(other.topologies))) {
- return false;
- }
- if ((this.services == null && other.services != null)
- || (this.services != null && !this.services.equals(other.services))) {
- return false;
- }
- return true;
- }
- public static String getEnumName(String fieldName ) {
- if( fieldName.equals("resourceType") ) {
- return "CommonEnums.ResourceType";
- }
- if( fieldName.equals("isEncrypt") ) {
- return "CommonEnums.BooleanValue";
- }
- if( fieldName.equals("isRecursive") ) {
- return "CommonEnums.BooleanValue";
- }
- if( fieldName.equals("resourceStatus") ) {
- return "CommonEnums.ActiveStatus";
- }
- if( fieldName.equals("tableType") ) {
- return "CommonEnums.PolicyType";
- }
- if( fieldName.equals("columnType") ) {
- return "CommonEnums.PolicyType";
- }
- if( fieldName.equals("assetType") ) {
- return "CommonEnums.AssetType";
- }
- //Later TODO
- //return super.getEnumName(fieldName);
- return null;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/entity/XXTrxLog.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/entity/XXTrxLog.java b/security-admin/src/main/java/com/xasecure/entity/XXTrxLog.java
deleted file mode 100644
index c91e803..0000000
--- a/security-admin/src/main/java/com/xasecure/entity/XXTrxLog.java
+++ /dev/null
@@ -1,523 +0,0 @@
-/*
- * 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 com.xasecure.entity;
-
-/**
- * Logging table for all DB create and update queries
- *
- */
-
-import java.util.*;
-import javax.persistence.*;
-import javax.xml.bind.annotation.*;
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-
-
-@Entity
-@Table(name="x_trx_log")
-@XmlRootElement
-public class XXTrxLog extends XXDBBase implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
- @Id
- @SequenceGenerator(name="X_TRX_LOG_SEQ",sequenceName="X_TRX_LOG_SEQ",allocationSize=1)
- @GeneratedValue(strategy=GenerationType.AUTO,generator="X_TRX_LOG_SEQ")
- @Column(name="ID")
- protected Long id;
- @Override
- public void setId(Long id) {
- this.id=id;
- }
- @Override
- public Long getId() {
- return id;
- }
- /**
- * Name of the class to which the object id belongs to
- * <ul>
- * <li>This attribute is of type enum CommonEnums::ClassTypes
- * </ul>
- *
- */
- @Column(name="CLASS_TYPE" , nullable=false )
- protected int objectClassType = XAConstants.CLASS_TYPE_NONE;
-
- /**
- * Id of the object to which this notes refers to
- * <ul>
- * </ul>
- *
- */
- @Column(name="OBJECT_ID" )
- protected Long objectId;
-
- /**
- * Object Id of the parent object
- * <ul>
- * </ul>
- *
- */
- @Column(name="PARENT_OBJECT_ID" )
- protected Long parentObjectId;
-
- /**
- * Object Class Type of the parent object
- * <ul>
- * </ul>
- *
- */
- @Column(name="PARENT_OBJECT_CLASS_TYPE" , nullable=false )
- protected int parentObjectClassType;
-
- /**
- * Name of the attribute that was changed
- * <ul>
- * <li>The maximum length for this attribute is <b>1024</b>.
- * </ul>
- *
- */
- @Column(name="PARENT_OBJECT_NAME" , length=1024)
- protected String parentObjectName;
-
- /**
- * Name of the attribute that was changed
- * <ul>
- * <li>The maximum length for this attribute is <b>1024</b>.
- * </ul>
- *
- */
- @Column(name="OBJECT_NAME" , length=1024)
- protected String objectName;
-
- /**
- * Name of the attribute that was changed
- * <ul>
- * <li>The maximum length for this attribute is <b>255</b>.
- * </ul>
- *
- */
- @Column(name="ATTR_NAME" , length=255)
- protected String attributeName;
-
- /**
- * Previous value
- * <ul>
- * <li>The maximum length for this attribute is <b>1024</b>.
- * </ul>
- *
- */
- @Column(name="PREV_VAL" , length=1024)
- protected String previousValue;
-
- /**
- * New value
- * <ul>
- * <li>The maximum length for this attribute is <b>1024</b>.
- * </ul>
- *
- */
- @Column(name="NEW_VAL" , length=1024)
- protected String newValue;
-
- /**
- * Transaction id
- * <ul>
- * <li>The maximum length for this attribute is <b>1024</b>.
- * </ul>
- *
- */
- @Column(name="TRX_ID" , length=1024)
- protected String transactionId;
-
- /**
- * Action of the transaction
- * <ul>
- * <li>The maximum length for this attribute is <b>255</b>.
- * </ul>
- *
- */
- @Column(name="ACTION" , length=255)
- protected String action;
-
- /**
- * Session Id
- * <ul>
- * <li>The maximum length for this attribute is <b>512</b>.
- * </ul>
- *
- */
- @Column(name="SESS_ID" , length=512)
- protected String sessionId;
-
- /**
- * Request Id
- * <ul>
- * </ul>
- *
- */
- @Column(name="REQ_ID" )
- protected String requestId;
-
- /**
- * Session Type
- * <ul>
- * </ul>
- *
- */
- @Column(name="SESS_TYPE" )
- protected String sessionType;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public XXTrxLog ( ) {
- objectClassType = XAConstants.CLASS_TYPE_NONE;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_TRX_LOG;
- }
-
- /**
- * This method sets the value to the member attribute <b>objectClassType</b>.
- * You cannot set null to the attribute.
- * @param objectClassType Value to set member attribute <b>objectClassType</b>
- */
- public void setObjectClassType( int objectClassType ) {
- this.objectClassType = objectClassType;
- }
-
- /**
- * Returns the value for the member attribute <b>objectClassType</b>
- * @return int - value of member attribute <b>objectClassType</b>.
- */
- public int getObjectClassType( ) {
- return this.objectClassType;
- }
-
- /**
- * This method sets the value to the member attribute <b>objectId</b>.
- * You cannot set null to the attribute.
- * @param objectId Value to set member attribute <b>objectId</b>
- */
- public void setObjectId( Long objectId ) {
- this.objectId = objectId;
- }
-
- /**
- * Returns the value for the member attribute <b>objectId</b>
- * @return Long - value of member attribute <b>objectId</b>.
- */
- public Long getObjectId( ) {
- return this.objectId;
- }
-
- /**
- * This method sets the value to the member attribute <b>parentObjectId</b>.
- * You cannot set null to the attribute.
- * @param parentObjectId Value to set member attribute <b>parentObjectId</b>
- */
- public void setParentObjectId( Long parentObjectId ) {
- this.parentObjectId = parentObjectId;
- }
-
- /**
- * Returns the value for the member attribute <b>parentObjectId</b>
- * @return Long - value of member attribute <b>parentObjectId</b>.
- */
- public Long getParentObjectId( ) {
- return this.parentObjectId;
- }
-
- /**
- * This method sets the value to the member attribute <b>parentObjectClassType</b>.
- * You cannot set null to the attribute.
- * @param parentObjectClassType Value to set member attribute <b>parentObjectClassType</b>
- */
- public void setParentObjectClassType( int parentObjectClassType ) {
- this.parentObjectClassType = parentObjectClassType;
- }
-
- /**
- * Returns the value for the member attribute <b>parentObjectClassType</b>
- * @return int - value of member attribute <b>parentObjectClassType</b>.
- */
- public int getParentObjectClassType( ) {
- return this.parentObjectClassType;
- }
-
- /**
- * This method sets the value to the member attribute <b>parentObjectName</b>.
- * You cannot set null to the attribute.
- * @param parentObjectName Value to set member attribute <b>parentObjectName</b>
- */
- public void setParentObjectName( String parentObjectName ) {
- this.parentObjectName = parentObjectName;
- }
-
- /**
- * Returns the value for the member attribute <b>parentObjectName</b>
- * @return String - value of member attribute <b>parentObjectName</b>.
- */
- public String getParentObjectName( ) {
- return this.parentObjectName;
- }
-
- /**
- * This method sets the value to the member attribute <b>objectName</b>.
- * You cannot set null to the attribute.
- * @param objectName Value to set member attribute <b>objectName</b>
- */
- public void setObjectName( String objectName ) {
- this.objectName = objectName;
- }
-
- /**
- * Returns the value for the member attribute <b>objectName</b>
- * @return String - value of member attribute <b>objectName</b>.
- */
- public String getObjectName( ) {
- return this.objectName;
- }
-
- /**
- * This method sets the value to the member attribute <b>attributeName</b>.
- * You cannot set null to the attribute.
- * @param attributeName Value to set member attribute <b>attributeName</b>
- */
- public void setAttributeName( String attributeName ) {
- this.attributeName = attributeName;
- }
-
- /**
- * Returns the value for the member attribute <b>attributeName</b>
- * @return String - value of member attribute <b>attributeName</b>.
- */
- public String getAttributeName( ) {
- return this.attributeName;
- }
-
- /**
- * This method sets the value to the member attribute <b>previousValue</b>.
- * You cannot set null to the attribute.
- * @param previousValue Value to set member attribute <b>previousValue</b>
- */
- public void setPreviousValue( String previousValue ) {
- this.previousValue = previousValue;
- }
-
- /**
- * Returns the value for the member attribute <b>previousValue</b>
- * @return String - value of member attribute <b>previousValue</b>.
- */
- public String getPreviousValue( ) {
- return this.previousValue;
- }
-
- /**
- * This method sets the value to the member attribute <b>newValue</b>.
- * You cannot set null to the attribute.
- * @param newValue Value to set member attribute <b>newValue</b>
- */
- public void setNewValue( String newValue ) {
- this.newValue = newValue;
- }
-
- /**
- * Returns the value for the member attribute <b>newValue</b>
- * @return String - value of member attribute <b>newValue</b>.
- */
- public String getNewValue( ) {
- return this.newValue;
- }
-
- /**
- * This method sets the value to the member attribute <b>transactionId</b>.
- * You cannot set null to the attribute.
- * @param transactionId Value to set member attribute <b>transactionId</b>
- */
- public void setTransactionId( String transactionId ) {
- this.transactionId = transactionId;
- }
-
- /**
- * Returns the value for the member attribute <b>transactionId</b>
- * @return String - value of member attribute <b>transactionId</b>.
- */
- public String getTransactionId( ) {
- return this.transactionId;
- }
-
- /**
- * This method sets the value to the member attribute <b>action</b>.
- * You cannot set null to the attribute.
- * @param action Value to set member attribute <b>action</b>
- */
- public void setAction( String action ) {
- this.action = action;
- }
-
- /**
- * Returns the value for the member attribute <b>action</b>
- * @return String - value of member attribute <b>action</b>.
- */
- public String getAction( ) {
- return this.action;
- }
-
- /**
- * This method sets the value to the member attribute <b>sessionId</b>.
- * You cannot set null to the attribute.
- * @param sessionId Value to set member attribute <b>sessionId</b>
- */
- public void setSessionId( String sessionId ) {
- this.sessionId = sessionId;
- }
-
- /**
- * Returns the value for the member attribute <b>sessionId</b>
- * @return String - value of member attribute <b>sessionId</b>.
- */
- public String getSessionId( ) {
- return this.sessionId;
- }
-
- /**
- * This method sets the value to the member attribute <b>requestId</b>.
- * You cannot set null to the attribute.
- * @param requestId Value to set member attribute <b>requestId</b>
- */
- public void setRequestId( String requestId ) {
- this.requestId = requestId;
- }
-
- /**
- * Returns the value for the member attribute <b>requestId</b>
- * @return String - value of member attribute <b>requestId</b>.
- */
- public String getRequestId( ) {
- return this.requestId;
- }
-
- /**
- * This method sets the value to the member attribute <b>sessionType</b>.
- * You cannot set null to the attribute.
- * @param sessionType Value to set member attribute <b>sessionType</b>
- */
- public void setSessionType( String sessionType ) {
- this.sessionType = sessionType;
- }
-
- /**
- * Returns the value for the member attribute <b>sessionType</b>
- * @return String - value of member attribute <b>sessionType</b>.
- */
- public String getSessionType( ) {
- return this.sessionType;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- @Override
- public String toString( ) {
- String str = "XXTrxLog={";
- str += super.toString();
- str += "objectClassType={" + objectClassType + "} ";
- str += "objectId={" + objectId + "} ";
- str += "parentObjectId={" + parentObjectId + "} ";
- str += "parentObjectClassType={" + parentObjectClassType + "} ";
- str += "parentObjectName={" + parentObjectName + "} ";
- str += "objectName={" + objectName + "} ";
- str += "attributeName={" + attributeName + "} ";
- str += "previousValue={" + previousValue + "} ";
- str += "newValue={" + newValue + "} ";
- str += "transactionId={" + transactionId + "} ";
- str += "action={" + action + "} ";
- str += "sessionId={" + sessionId + "} ";
- str += "requestId={" + requestId + "} ";
- str += "sessionType={" + sessionType + "} ";
- str += "}";
- return str;
- }
-
- /**
- * Checks for all attributes except referenced db objects
- * @return true if all attributes match
- */
- @Override
- public boolean equals( Object obj) {
- if ( !super.equals(obj) ) {
- return false;
- }
- XXTrxLog other = (XXTrxLog) obj;
- if( this.objectClassType != other.objectClassType ) return false;
- if ((this.objectId == null && other.objectId != null) || (this.objectId != null && !this.objectId.equals(other.objectId))) {
- return false;
- }
- if ((this.parentObjectId == null && other.parentObjectId != null) || (this.parentObjectId != null && !this.parentObjectId.equals(other.parentObjectId))) {
- return false;
- }
- if( this.parentObjectClassType != other.parentObjectClassType ) return false;
- if ((this.parentObjectName == null && other.parentObjectName != null) || (this.parentObjectName != null && !this.parentObjectName.equals(other.parentObjectName))) {
- return false;
- }
- if ((this.objectName == null && other.objectName != null) || (this.objectName != null && !this.objectName.equals(other.objectName))) {
- return false;
- }
- if ((this.attributeName == null && other.attributeName != null) || (this.attributeName != null && !this.attributeName.equals(other.attributeName))) {
- return false;
- }
- if ((this.previousValue == null && other.previousValue != null) || (this.previousValue != null && !this.previousValue.equals(other.previousValue))) {
- return false;
- }
- if ((this.newValue == null && other.newValue != null) || (this.newValue != null && !this.newValue.equals(other.newValue))) {
- return false;
- }
- if ((this.transactionId == null && other.transactionId != null) || (this.transactionId != null && !this.transactionId.equals(other.transactionId))) {
- return false;
- }
- if ((this.action == null && other.action != null) || (this.action != null && !this.action.equals(other.action))) {
- return false;
- }
- if ((this.sessionId == null && other.sessionId != null) || (this.sessionId != null && !this.sessionId.equals(other.sessionId))) {
- return false;
- }
- if ((this.requestId == null && other.requestId != null) || (this.requestId != null && !this.requestId.equals(other.requestId))) {
- return false;
- }
- if ((this.sessionType == null && other.sessionType != null) || (this.sessionType != null && !this.sessionType.equals(other.sessionType))) {
- return false;
- }
- return true;
- }
- public static String getEnumName(String fieldName ) {
- if( fieldName.equals("objectClassType") ) {
- return "CommonEnums.ClassTypes";
- }
- //Later TODO
- //return super.getEnumName(fieldName);
- return null;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/entity/XXUser.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/entity/XXUser.java b/security-admin/src/main/java/com/xasecure/entity/XXUser.java
deleted file mode 100644
index bc5817a..0000000
--- a/security-admin/src/main/java/com/xasecure/entity/XXUser.java
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
- * 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 com.xasecure.entity;
-
-/**
- * User
- *
- */
-
-import java.util.*;
-import javax.persistence.*;
-import javax.xml.bind.annotation.*;
-import com.xasecure.common.*;
-import com.xasecure.entity.*;
-
-
-@Entity
-@Table(name="x_user")
-@XmlRootElement
-public class XXUser extends XXDBBase implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- @Id
- @SequenceGenerator(name="X_USER_SEQ",sequenceName="X_USER_SEQ",allocationSize=1)
- @GeneratedValue(strategy=GenerationType.AUTO,generator="X_USER_SEQ")
- @Column(name="ID")
- protected Long id;
- @Override
- public void setId(Long id) {
- this.id=id;
- }
- @Override
- public Long getId() {
- return id;
- }
- /**
- * Name
- * <ul>
- * <li>The maximum length for this attribute is <b>1024</b>.
- * </ul>
- *
- */
- @Column(name="USER_NAME" , nullable=false , length=1024)
- protected String name;
-
- /**
- * Description
- * <ul>
- * <li>The maximum length for this attribute is <b>4000</b>.
- * </ul>
- *
- */
- @Column(name="DESCR" , nullable=false , length=4000)
- protected String description;
-
- /**
- * Status
- * <ul>
- * <li>This attribute is of type enum CommonEnums::ActiveStatus
- * </ul>
- *
- */
- @Column(name="STATUS" , nullable=false )
- protected int status = XAConstants.STATUS_DISABLED;
-
- /**
- * Id of the credential store
- * <ul>
- * </ul>
- *
- */
- @Column(name="CRED_STORE_ID" )
- protected Long credStoreId;
-
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public XXUser ( ) {
- status = XAConstants.STATUS_DISABLED;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_XA_USER;
- }
-
- @Override
- public String getMyDisplayValue() {
- return getDescription( );
- }
-
- /**
- * This method sets the value to the member attribute <b>name</b>.
- * You cannot set null to the attribute.
- * @param name Value to set member attribute <b>name</b>
- */
- public void setName( String name ) {
- this.name = name;
- }
-
- /**
- * Returns the value for the member attribute <b>name</b>
- * @return String - value of member attribute <b>name</b>.
- */
- public String getName( ) {
- return this.name;
- }
-
- /**
- * This method sets the value to the member attribute <b>description</b>.
- * You cannot set null to the attribute.
- * @param description Value to set member attribute <b>description</b>
- */
- public void setDescription( String description ) {
- this.description = description;
- }
-
- /**
- * Returns the value for the member attribute <b>description</b>
- * @return String - value of member attribute <b>description</b>.
- */
- public String getDescription( ) {
- return this.description;
- }
-
- /**
- * This method sets the value to the member attribute <b>status</b>.
- * You cannot set null to the attribute.
- * @param status Value to set member attribute <b>status</b>
- */
- public void setStatus( int status ) {
- this.status = status;
- }
-
- /**
- * Returns the value for the member attribute <b>status</b>
- * @return int - value of member attribute <b>status</b>.
- */
- public int getStatus( ) {
- return this.status;
- }
-
- /**
- * This method sets the value to the member attribute <b>credStoreId</b>.
- * You cannot set null to the attribute.
- * @param credStoreId Value to set member attribute <b>credStoreId</b>
- */
- public void setCredStoreId( Long credStoreId ) {
- this.credStoreId = credStoreId;
- }
-
- /**
- * Returns the value for the member attribute <b>credStoreId</b>
- * @return Long - value of member attribute <b>credStoreId</b>.
- */
- public Long getCredStoreId( ) {
- return this.credStoreId;
- }
-
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- @Override
- public String toString( ) {
- String str = "XXUser={";
- str += super.toString();
- str += "name={" + name + "} ";
- str += "description={" + description + "} ";
- str += "status={" + status + "} ";
- str += "credStoreId={" + credStoreId + "} ";
- str += "}";
- return str;
- }
-
- /**
- * Checks for all attributes except referenced db objects
- * @return true if all attributes match
- */
- @Override
- public boolean equals( Object obj) {
- if ( !super.equals(obj) ) {
- return false;
- }
- XXUser other = (XXUser) obj;
- if ((this.name == null && other.name != null) || (this.name != null && !this.name.equals(other.name))) {
- return false;
- }
- if ((this.description == null && other.description != null) || (this.description != null && !this.description.equals(other.description))) {
- return false;
- }
- if( this.status != other.status ) return false;
- if ((this.credStoreId == null && other.credStoreId != null) || (this.credStoreId != null && !this.credStoreId.equals(other.credStoreId))) {
- return false;
- }
- return true;
- }
- public static String getEnumName(String fieldName ) {
- if( fieldName.equals("status") ) {
- return "CommonEnums.ActiveStatus";
- }
- //Later TODO
- //return super.getEnumName(fieldName);
- return null;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/entity/view/VXXTrxLog.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/entity/view/VXXTrxLog.java b/security-admin/src/main/java/com/xasecure/entity/view/VXXTrxLog.java
deleted file mode 100644
index 5865f5b..0000000
--- a/security-admin/src/main/java/com/xasecure/entity/view/VXXTrxLog.java
+++ /dev/null
@@ -1,399 +0,0 @@
-/*
- * 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 com.xasecure.entity.view;
-
-
-import java.util.Date;
-
-import javax.persistence.*;
-import javax.xml.bind.annotation.*;
-
-import com.xasecure.common.XAConstants;
-import com.xasecure.common.DateUtil;
-
-@Entity
-@Table(name="vx_trx_log")
-@XmlRootElement
-public class VXXTrxLog implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- public static final int SHARE_PREF_DEFAULT = 0;
-
- @Id
- @SequenceGenerator(name="V_TRX_LOG_SEQ",sequenceName="V_TRX_LOG_SEQ",allocationSize=1)
- @GeneratedValue(strategy=GenerationType.AUTO,generator="V_TRX_LOG_SEQ")
- @Column(name="ID")
- protected Long id;
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name="CREATE_TIME" , nullable=false )
- protected Date createTime = DateUtil.getUTCDate();
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name="UPDATE_TIME" , nullable=false )
- protected Date updateTime = DateUtil.getUTCDate();
-
- @Column(name="ADDED_BY_ID" )
- protected Long addedByUserId;
-
- @Column(name="UPD_BY_ID" )
- protected Long updatedByUserId;
-
- @Column(name="CLASS_TYPE" , nullable=false )
- protected int objectClassType = XAConstants.CLASS_TYPE_NONE;
-
- @Column(name="OBJECT_ID" )
- protected Long objectId;
-
- @Column(name="PARENT_OBJECT_ID" , nullable=false )
- protected Long parentObjectId;
-
- @Column(name="PARENT_OBJECT_CLASS_TYPE" , nullable=false )
- protected int parentObjectClassType;
-
- @Column(name="ATTR_NAME" , nullable=false , length=255)
- protected String attributeName;
-
- @Column(name="PARENT_OBJECT_NAME" , length=1024)
- protected String parentObjectName;
-
- @Column(name="OBJECT_NAME" , length=1024)
- protected String objectName;
-
- @Column(name="PREV_VAL" , length=1024)
- protected String previousValue;
-
- @Column(name="NEW_VAL" , nullable=true , length=1024)
- protected String newValue;
-
- @Column(name="TRX_ID" , nullable=false , length=1024)
- protected String transactionId;
-
- @Column(name="ACTION" , length=255)
- protected String action;
-
- @Column(name="SESS_ID" )
- protected String sessionId;
-
- @Column(name="REQ_ID" , nullable=false )
- protected String requestId;
-
- @Column(name="SESS_TYPE" , nullable=false )
- protected String sessionType;
-
-
- /**
- * This method sets the value to the member attribute <b>parentObjectId</b>.
- * You cannot set null to the attribute.
- * @param parentObjectId Value to set member attribute <b>parentObjectId</b>
- */
- public void setParentObjectId( Long parentObjectId ) {
- this.parentObjectId = parentObjectId;
- }
-
- /**
- * Returns the value for the member attribute <b>parentObjectId</b>
- * @return Long - value of member attribute <b>parentObjectId</b>.
- */
- public Long getParentObjectId( ) {
- return this.parentObjectId;
- }
-
- /**
- * This method sets the value to the member attribute <b>parentObjectClassType</b>.
- * You cannot set null to the attribute.
- * @param parentObjectClassType Value to set member attribute <b>parentObjectClassType</b>
- */
- public void setParentObjectClassType( int parentObjectClassType ) {
- this.parentObjectClassType = parentObjectClassType;
- }
-
- /**
- * Returns the value for the member attribute <b>parentObjectClassType</b>
- * @return int - value of member attribute <b>parentObjectClassType</b>.
- */
- public int getParentObjectClassType( ) {
- return this.parentObjectClassType;
- }
-
- /**
- * This method sets the value to the member attribute <b>attributeName</b>.
- * You cannot set null to the attribute.
- * @param attributeName Value to set member attribute <b>attributeName</b>
- */
- public void setAttributeName( String attributeName ) {
- this.attributeName = attributeName;
- }
-
- /**
- * Returns the value for the member attribute <b>attributeName</b>
- * @return String - value of member attribute <b>attributeName</b>.
- */
- public String getAttributeName( ) {
- return this.attributeName;
- }
-
- /**
- * This method sets the value to the member attribute <b>previousValue</b>.
- * You cannot set null to the attribute.
- * @param previousValue Value to set member attribute <b>previousValue</b>
- */
- public void setPreviousValue( String previousValue ) {
- this.previousValue = previousValue;
- }
-
- /**
- * Returns the value for the member attribute <b>previousValue</b>
- * @return String - value of member attribute <b>previousValue</b>.
- */
- public String getPreviousValue( ) {
- return this.previousValue;
- }
-
- /**
- * This method sets the value to the member attribute <b>newValue</b>.
- * You cannot set null to the attribute.
- * @param newValue Value to set member attribute <b>newValue</b>
- */
- public void setNewValue( String newValue ) {
- this.newValue = newValue;
- }
-
- /**
- * Returns the value for the member attribute <b>newValue</b>
- * @return String - value of member attribute <b>newValue</b>.
- */
- public String getNewValue( ) {
- return this.newValue;
- }
-
- /**
- * This method sets the value to the member attribute <b>transactionId</b>.
- * You cannot set null to the attribute.
- * @param transactionId Value to set member attribute <b>transactionId</b>
- */
- public void setTransactionId( String transactionId ) {
- this.transactionId = transactionId;
- }
-
- /**
- * Returns the value for the member attribute <b>transactionId</b>
- * @return String - value of member attribute <b>transactionId</b>.
- */
- public String getTransactionId( ) {
- return this.transactionId;
- }
-
- /**
- * This method sets the value to the member attribute <b>action</b>.
- * You cannot set null to the attribute.
- * @param action Value to set member attribute <b>action</b>
- */
- public void setAction( String action ) {
- this.action = action;
- }
-
- /**
- * Returns the value for the member attribute <b>action</b>
- * @return String - value of member attribute <b>action</b>.
- */
- public String getAction( ) {
- return this.action;
- }
-
- /**
- * This method sets the value to the member attribute <b>sessionId</b>.
- * You cannot set null to the attribute.
- * @param sessionId Value to set member attribute <b>sessionId</b>
- */
- public void setSessionId( String sessionId ) {
- this.sessionId = sessionId;
- }
-
- /**
- * Returns the value for the member attribute <b>sessionId</b>
- * @return String - value of member attribute <b>sessionId</b>.
- */
- public String getSessionId( ) {
- return this.sessionId;
- }
-
- /**
- * This method sets the value to the member attribute <b>requestId</b>.
- * You cannot set null to the attribute.
- * @param requestId Value to set member attribute <b>requestId</b>
- */
- public void setRequestId( String requestId ) {
- this.requestId = requestId;
- }
-
- /**
- * Returns the value for the member attribute <b>requestId</b>
- * @return String - value of member attribute <b>requestId</b>.
- */
- public String getRequestId( ) {
- return this.requestId;
- }
-
- /**
- * This method sets the value to the member attribute <b>sessionType</b>.
- * You cannot set null to the attribute.
- * @param sessionType Value to set member attribute <b>sessionType</b>
- */
- public void setSessionType( String sessionType ) {
- this.sessionType = sessionType;
- }
-
- /**
- * Returns the value for the member attribute <b>sessionType</b>
- * @return String - value of member attribute <b>sessionType</b>.
- */
- public String getSessionType( ) {
- return this.sessionType;
- }
-
- /**
- * @return the parentObjectName
- */
- public String getParentObjectName() {
- return parentObjectName;
- }
-
- /**
- * @param parentObjectName the parentObjectName to set
- */
- public void setParentObjectName(String parentObjectName) {
- this.parentObjectName = parentObjectName;
- }
-
- /**
- * @return the objectName
- */
- public String getObjectName() {
- return objectName;
- }
-
- /**
- * @param objectName the objectName to set
- */
- public void setObjectName(String objectName) {
- this.objectName = objectName;
- }
-
- /**
- * @return the id
- */
- public Long getId() {
- return id;
- }
-
- /**
- * @param id the id to set
- */
- public void setId(Long id) {
- this.id = id;
- }
-
- /**
- * @return the createTime
- */
- public Date getCreateTime() {
- return createTime;
- }
-
- /**
- * @param createTime the createTime to set
- */
- public void setCreateTime(Date createTime) {
- this.createTime = createTime;
- }
-
- /**
- * @return the updateTime
- */
- public Date getUpdateTime() {
- return updateTime;
- }
-
- /**
- * @param updateTime the updateTime to set
- */
- public void setUpdateTime(Date updateTime) {
- this.updateTime = updateTime;
- }
-
- /**
- * @return the addedByUserId
- */
- public Long getAddedByUserId() {
- return addedByUserId;
- }
-
- /**
- * @param addedByUserId the addedByUserId to set
- */
- public void setAddedByUserId(Long addedByUserId) {
- this.addedByUserId = addedByUserId;
- }
-
-
- /**
- * @return the updatedByUserId
- */
- public Long getUpdatedByUserId() {
- return updatedByUserId;
- }
-
- /**
- * @param updatedByUserId the updatedByUserId to set
- */
- public void setUpdatedByUserId(Long updatedByUserId) {
- this.updatedByUserId = updatedByUserId;
- }
-
- /**
- * @return the objectClassType
- */
- public int getObjectClassType() {
- return objectClassType;
- }
-
- /**
- * @param objectClassType the objectClassType to set
- */
- public void setObjectClassType(int objectClassType) {
- this.objectClassType = objectClassType;
- }
-
- /**
- * @return the objectId
- */
- public Long getObjectId() {
- return objectId;
- }
-
- /**
- * @param objectId the objectId to set
- */
- public void setObjectId(Long objectId) {
- this.objectId = objectId;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/json/Folder.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/json/Folder.java b/security-admin/src/main/java/com/xasecure/json/Folder.java
deleted file mode 100644
index 87ce55c..0000000
--- a/security-admin/src/main/java/com/xasecure/json/Folder.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * 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 com.xasecure.json;
-
-import java.util.List;
-
-public class Folder {
-
- String name;
- List<Folder> folders;
-
-
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public List<Folder> getFolders() {
- return folders;
- }
- public void setFolders(List<Folder> folders) {
- this.folders = folders;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/json/JsonDateSerializer.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/json/JsonDateSerializer.java b/security-admin/src/main/java/com/xasecure/json/JsonDateSerializer.java
deleted file mode 100644
index ebbac08..0000000
--- a/security-admin/src/main/java/com/xasecure/json/JsonDateSerializer.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * 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 com.xasecure.json;
-
-import java.io.IOException;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-
-import org.codehaus.jackson.JsonGenerator;
-import org.codehaus.jackson.JsonProcessingException;
-import org.codehaus.jackson.map.JsonSerializer;
-import org.codehaus.jackson.map.SerializerProvider;
-import org.springframework.stereotype.Component;
-
-/**
- * Used to serialize Java.util.Date, which is not a common JSON type, so we have
- * to create a custom serialize method;.
- *
- */
-@Component
-public class JsonDateSerializer extends JsonSerializer<Date> {
-
- private static final SimpleDateFormat dateFormat = new SimpleDateFormat
- ("yyyy-MM-dd'T'HH:mm:ss'Z'");
- @Override
- public void serialize(Date date, JsonGenerator gen,
- SerializerProvider provider) throws IOException,
- JsonProcessingException {
-
- String formattedDate = dateFormat.format(date);
- gen.writeString(formattedDate);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/patch/BaseLoader.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/patch/BaseLoader.java b/security-admin/src/main/java/com/xasecure/patch/BaseLoader.java
deleted file mode 100644
index 0418e21..0000000
--- a/security-admin/src/main/java/com/xasecure/patch/BaseLoader.java
+++ /dev/null
@@ -1,206 +0,0 @@
-/*
- * 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 com.xasecure.patch;
-
-import java.text.DecimalFormat;
-import java.util.Date;
-
-import com.xasecure.common.DateUtil;
-
-import org.apache.log4j.Logger;
-import org.springframework.transaction.annotation.Propagation;
-import org.springframework.transaction.annotation.Transactional;
-
-import com.xasecure.util.CLIUtil;
-
-/**
- *
- *
- */
-public abstract class BaseLoader {
- static Logger logger = Logger.getLogger(BaseLoader.class);
-
- long startTime = DateUtil.getUTCDate().getTime();
- long lastTime = startTime;
- int countSoFar = 0;
- int countFromLastTime = 0;
- boolean moreToProcess = true;
- boolean firstCall = true;
- int batchSize = -1;
- DecimalFormat twoDForm = new DecimalFormat("#.00");
-
- public BaseLoader() {
- }
-
- public void init(int batchSize) throws Exception {
- this.batchSize = batchSize;
- CLIUtil cliUtil = (CLIUtil) CLIUtil.getBean(CLIUtil.class);
- cliUtil.authenticate();
- }
-
- public void init() throws Exception {
- init(-1);
- }
-
- abstract public void printStats();
-
- public abstract void execLoad();
-
- public void onExit() {
- logger.info("onExit()");
- }
-
- /**
- * @return the moreToProcess
- */
- public boolean isMoreToProcess() {
- return moreToProcess;
- }
-
- /**
- * @param moreToProcess
- * the moreToProcess to set
- */
- public void setMoreToProcess(boolean moreToProcess) {
- this.moreToProcess = moreToProcess;
- }
-
- @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
- public void load() {
- if (firstCall) {
- startTime = DateUtil.getUTCDate().getTime();
- startProgressMonitor();
- firstCall = false;
- }
- try {
- execLoad();
- if (batchSize < 0) {
- moreToProcess = false;
- }
- } catch (Throwable t) {
- logger.error("Error while loading data.", t);
- moreToProcess = false;
- }
- if (!moreToProcess) {
- long endTime = DateUtil.getUTCDate().getTime();
-
- logger.info("###############################################");
- printStats();
- logger.info("Loading completed!!!. Time taken="
- + formatTimeTaken(endTime - startTime) + " for "
- + countSoFar);
- logger.info("###############################################");
- synchronized (twoDForm) {
- twoDForm.notifyAll();
- }
-
- }
- }
-
- public void startProgressMonitor() {
- Thread monitorThread = new Thread("Loader Monitor") {
- @Override
- public void run() {
- while (isMoreToProcess()) {
- printStats();
- try {
- synchronized (twoDForm) {
- if (!isMoreToProcess()) {
- break;
- }
- twoDForm.wait(30 * 1000);
- }
- // Thread.sleep(60 * 1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- logger.info("Monitor Thread exiting!!!");
- }
- };
- monitorThread.setDaemon(true);
- monitorThread.start();
-
- }
-
- public String timeTakenSoFar(int lineCount) {
- countSoFar = lineCount;
- long currTime = DateUtil.getUTCDate().getTime();
- String retStr = formatTimeTaken(currTime - startTime);
- if (currTime - startTime > 0 && countSoFar > 0) {
- double rateSoFar = countSoFar * 1000 / (currTime - startTime);
- retStr = retStr + " " + ". Rate so far for " + countSoFar + " is "
- + twoDForm.format(rateSoFar);
-
- if (currTime - lastTime > 0 && lineCount - countFromLastTime > 0) {
- double rateFromLastCall = (lineCount - countFromLastTime)
- * 1000.0 / (currTime - lastTime);
- retStr = retStr + ", Last "
- + formatTimeTaken(currTime - lastTime) + " for "
- + (lineCount - countFromLastTime) + " is "
- + twoDForm.format(rateFromLastCall);
- }
-
- }
-
- lastTime = currTime;
- countFromLastTime = countSoFar;
- return retStr;
- }
-
- String formatTimeTaken(long totalTime) {
- if (totalTime <= 0) {
- return "0ms";
- }
- long ms = totalTime % 1000;
- String retValue = ms + "ms";
-
- totalTime = totalTime / 1000;
- if (totalTime > 0) {
- long secs = totalTime % 60;
- retValue = secs + "secs, " + retValue;
-
- totalTime = totalTime / 60;
- if (totalTime > 0) {
- long mins = totalTime % 60;
- retValue = mins + "mins, " + retValue;
-
- totalTime = totalTime / 60;
- if (totalTime > 0) {
- long hrs = totalTime % 60;
- retValue = hrs + "hrs, " + retValue;
- }
- }
- }
-
- return retValue;
-
- }
-
- protected void print(int count, String message) {
- if (count > 0) {
- logger.info(message.trim() + " : " + count);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/patch/PatchPasswordEncryption_J10001.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/patch/PatchPasswordEncryption_J10001.java b/security-admin/src/main/java/com/xasecure/patch/PatchPasswordEncryption_J10001.java
deleted file mode 100644
index e8c4370..0000000
--- a/security-admin/src/main/java/com/xasecure/patch/PatchPasswordEncryption_J10001.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * 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 com.xasecure.patch;
-
-import java.util.List;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import com.xasecure.common.StringUtil;
-import com.xasecure.db.XADaoManager;
-import com.xasecure.entity.XXAsset;
-import com.xasecure.service.XAssetService;
-import com.xasecure.util.CLIUtil;
-
-@Component
-public class PatchPasswordEncryption_J10001 extends BaseLoader {
- static Logger logger = Logger.getLogger(PatchPasswordEncryption_J10001.class);
- int lineCount = 0;
-
- @Autowired
- XADaoManager xaDaoManager;
-
- @Autowired
- StringUtil stringUtil;
-
- @Autowired
- XAssetService xAssetService;
-
- public PatchPasswordEncryption_J10001() {
- }
-
-
- @Override
- public void printStats() {
- logger.info("Time taken so far:" + timeTakenSoFar(lineCount)
- + ", moreToProcess=" + isMoreToProcess());
- print(lineCount, "Processed lines");
- }
-
- @Override
- public void execLoad() {
- encryptLookupUserPassword();
- }
-
- private void encryptLookupUserPassword() {
- List<XXAsset> xAssetList = xaDaoManager.getXXAsset().getAll();
- String oldConfig=null;
- String newConfig=null;
- for (XXAsset xAsset : xAssetList) {
- oldConfig=null;
- newConfig=null;
- oldConfig=xAsset.getConfig();
- if(!stringUtil.isEmpty(oldConfig)){
- newConfig=xAssetService.getConfigWithEncryptedPassword(oldConfig,false);
- xAsset.setConfig(newConfig);
- xaDaoManager.getXXAsset().update(xAsset);
- }
- lineCount++;
- logger.info("Lookup Password updated for Asset : "
- + xAsset.getName());
- logger.info("oldconfig : "+ oldConfig);
- logger.info("newConfig : "+ newConfig);
- print(lineCount, "Total updated assets count : ");
- }
- }
-
- public static void main(String[] args) {
- logger.info("main()");
- try {
- PatchPasswordEncryption_J10001 loader = (PatchPasswordEncryption_J10001) CLIUtil
- .getBean(PatchPasswordEncryption_J10001.class);
- //loader.init();
- while (loader.isMoreToProcess()) {
- loader.load();
- }
- logger.info("Load complete. Exiting!!!");
- System.exit(0);
- }catch (Exception e) {
- logger.error("Error loading", e);
- System.exit(1);
- }
- }
-
-}
[11/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXGroupUser.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXGroupUser.java b/security-admin/src/main/java/com/xasecure/view/VXGroupUser.java
deleted file mode 100644
index fa58f61..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXGroupUser.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * Group of users
- *
- */
-
-import java.util.*;
-
-import com.xasecure.common.*;
-import com.xasecure.common.view.*;
-
-import com.xasecure.common.*;
-import com.xasecure.json.JsonDateSerializer;
-
-import com.xasecure.view.*;
-
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@JsonIgnoreProperties(ignoreUnknown=true)
-@XmlRootElement
-public class VXGroupUser extends VXDataObject implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- /**
- * Name
- */
- protected String name;
- /**
- * Id of the group
- */
- protected Long parentGroupId;
- /**
- * Id of the user
- */
- protected Long userId;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VXGroupUser ( ) {
- }
-
- /**
- * This method sets the value to the member attribute <b>name</b>.
- * You cannot set null to the attribute.
- * @param name Value to set member attribute <b>name</b>
- */
- public void setName( String name ) {
- this.name = name;
- }
-
- /**
- * Returns the value for the member attribute <b>name</b>
- * @return String - value of member attribute <b>name</b>.
- */
- public String getName( ) {
- return this.name;
- }
-
- /**
- * This method sets the value to the member attribute <b>parentGroupId</b>.
- * You cannot set null to the attribute.
- * @param parentGroupId Value to set member attribute <b>parentGroupId</b>
- */
- public void setParentGroupId( Long parentGroupId ) {
- this.parentGroupId = parentGroupId;
- }
-
- /**
- * Returns the value for the member attribute <b>parentGroupId</b>
- * @return Long - value of member attribute <b>parentGroupId</b>.
- */
- public Long getParentGroupId( ) {
- return this.parentGroupId;
- }
-
- /**
- * This method sets the value to the member attribute <b>userId</b>.
- * You cannot set null to the attribute.
- * @param userId Value to set member attribute <b>userId</b>
- */
- public void setUserId( Long userId ) {
- this.userId = userId;
- }
-
- /**
- * Returns the value for the member attribute <b>userId</b>
- * @return Long - value of member attribute <b>userId</b>.
- */
- public Long getUserId( ) {
- return this.userId;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_XA_GROUP_USER;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- public String toString( ) {
- String str = "VXGroupUser={";
- str += super.toString();
- str += "name={" + name + "} ";
- str += "parentGroupId={" + parentGroupId + "} ";
- str += "userId={" + userId + "} ";
- str += "}";
- return str;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXGroupUserList.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXGroupUserList.java b/security-admin/src/main/java/com/xasecure/view/VXGroupUserList.java
deleted file mode 100644
index 75858ed..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXGroupUserList.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * List wrapper class for VXGroupUser
- *
- */
-
-import java.util.*;
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-import com.xasecure.common.view.*;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.FIELD)
-public class VXGroupUserList extends VList {
- private static final long serialVersionUID = 1L;
- List<VXGroupUser> vXGroupUsers = new ArrayList<VXGroupUser>();
-
- public VXGroupUserList() {
- super();
- }
-
- public VXGroupUserList(List<VXGroupUser> objList) {
- super(objList);
- this.vXGroupUsers = objList;
- }
-
- /**
- * @return the vXGroupUsers
- */
- public List<VXGroupUser> getVXGroupUsers() {
- return vXGroupUsers;
- }
-
- /**
- * @param vXGroupUsers
- * the vXGroupUsers to set
- */
- public void setVXGroupUsers(List<VXGroupUser> vXGroupUsers) {
- this.vXGroupUsers = vXGroupUsers;
- }
-
- @Override
- public int getListSize() {
- if (vXGroupUsers != null) {
- return vXGroupUsers.size();
- }
- return 0;
- }
-
- @Override
- public List<VXGroupUser> getList() {
- return vXGroupUsers;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXLong.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXLong.java b/security-admin/src/main/java/com/xasecure/view/VXLong.java
deleted file mode 100644
index a7abab7..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXLong.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * Long
- *
- */
-
-import java.util.*;
-
-import com.xasecure.common.*;
-import com.xasecure.common.view.*;
-
-import com.xasecure.common.*;
-import com.xasecure.json.JsonDateSerializer;
-
-import com.xasecure.view.*;
-
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@JsonIgnoreProperties(ignoreUnknown=true)
-@XmlRootElement
-public class VXLong extends ViewBaseBean implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- /**
- * Value
- */
- protected long value;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VXLong ( ) {
- }
-
- /**
- * This method sets the value to the member attribute <b>value</b>.
- * You cannot set null to the attribute.
- * @param value Value to set member attribute <b>value</b>
- */
- public void setValue( long value ) {
- this.value = value;
- }
-
- /**
- * Returns the value for the member attribute <b>value</b>
- * @return long - value of member attribute <b>value</b>.
- */
- public long getValue( ) {
- return this.value;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_LONG;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- public String toString( ) {
- String str = "VXLong={";
- str += super.toString();
- str += "value={" + value + "} ";
- str += "}";
- return str;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXMessage.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXMessage.java b/security-admin/src/main/java/com/xasecure/view/VXMessage.java
deleted file mode 100644
index c53f5c8..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXMessage.java
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * Message class
- *
- */
-
-import java.util.*;
-
-import com.xasecure.common.*;
-import com.xasecure.common.view.*;
-
-import com.xasecure.common.*;
-import com.xasecure.json.JsonDateSerializer;
-
-import com.xasecure.view.*;
-
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@JsonIgnoreProperties(ignoreUnknown=true)
-@XmlRootElement
-public class VXMessage extends ViewBaseBean implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- /**
- * Message key
- */
- protected String name;
- /**
- * Resource bundle key
- */
- protected String rbKey;
- /**
- * Message description. Use rbKey for doing localized lookup
- */
- protected String message;
- /**
- * Id of the object to which this message is related to
- */
- protected Long objectId;
- /**
- * Name of the field or attribute to which this message is related to
- */
- protected String fieldName;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VXMessage ( ) {
- }
-
- /**
- * This method sets the value to the member attribute <b>name</b>.
- * You cannot set null to the attribute.
- * @param name Value to set member attribute <b>name</b>
- */
- public void setName( String name ) {
- this.name = name;
- }
-
- /**
- * Returns the value for the member attribute <b>name</b>
- * @return String - value of member attribute <b>name</b>.
- */
- public String getName( ) {
- return this.name;
- }
-
- /**
- * This method sets the value to the member attribute <b>rbKey</b>.
- * You cannot set null to the attribute.
- * @param rbKey Value to set member attribute <b>rbKey</b>
- */
- public void setRbKey( String rbKey ) {
- this.rbKey = rbKey;
- }
-
- /**
- * Returns the value for the member attribute <b>rbKey</b>
- * @return String - value of member attribute <b>rbKey</b>.
- */
- public String getRbKey( ) {
- return this.rbKey;
- }
-
- /**
- * This method sets the value to the member attribute <b>message</b>.
- * You cannot set null to the attribute.
- * @param message Value to set member attribute <b>message</b>
- */
- public void setMessage( String message ) {
- this.message = message;
- }
-
- /**
- * Returns the value for the member attribute <b>message</b>
- * @return String - value of member attribute <b>message</b>.
- */
- public String getMessage( ) {
- return this.message;
- }
-
- /**
- * This method sets the value to the member attribute <b>objectId</b>.
- * You cannot set null to the attribute.
- * @param objectId Value to set member attribute <b>objectId</b>
- */
- public void setObjectId( Long objectId ) {
- this.objectId = objectId;
- }
-
- /**
- * Returns the value for the member attribute <b>objectId</b>
- * @return Long - value of member attribute <b>objectId</b>.
- */
- public Long getObjectId( ) {
- return this.objectId;
- }
-
- /**
- * This method sets the value to the member attribute <b>fieldName</b>.
- * You cannot set null to the attribute.
- * @param fieldName Value to set member attribute <b>fieldName</b>
- */
- public void setFieldName( String fieldName ) {
- this.fieldName = fieldName;
- }
-
- /**
- * Returns the value for the member attribute <b>fieldName</b>
- * @return String - value of member attribute <b>fieldName</b>.
- */
- public String getFieldName( ) {
- return this.fieldName;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_MESSAGE;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- public String toString( ) {
- String str = "VXMessage={";
- str += super.toString();
- str += "name={" + name + "} ";
- str += "rbKey={" + rbKey + "} ";
- str += "message={" + message + "} ";
- str += "objectId={" + objectId + "} ";
- str += "fieldName={" + fieldName + "} ";
- str += "}";
- return str;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXPasswordChange.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXPasswordChange.java b/security-admin/src/main/java/com/xasecure/view/VXPasswordChange.java
deleted file mode 100644
index df1d0db..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXPasswordChange.java
+++ /dev/null
@@ -1,206 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * Change password structure
- *
- */
-
-import java.util.*;
-
-import com.xasecure.common.*;
-import com.xasecure.common.view.*;
-
-import com.xasecure.common.*;
-import com.xasecure.json.JsonDateSerializer;
-
-import com.xasecure.view.*;
-
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@JsonIgnoreProperties(ignoreUnknown=true)
-@XmlRootElement
-public class VXPasswordChange extends ViewBaseBean implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- /**
- * Id of the user
- */
- protected Long id;
- /**
- * Login ID of the user
- */
- protected String loginId;
- /**
- * Email address of the user
- */
- protected String emailAddress;
- /**
- * Reset Code
- */
- protected String resetCode;
- /**
- * Old Password
- */
- protected String oldPassword;
- /**
- * Updated Password
- */
- protected String updPassword;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VXPasswordChange ( ) {
- }
-
- /**
- * This method sets the value to the member attribute <b>id</b>.
- * You cannot set null to the attribute.
- * @param id Value to set member attribute <b>id</b>
- */
- public void setId( Long id ) {
- this.id = id;
- }
-
- /**
- * Returns the value for the member attribute <b>id</b>
- * @return Long - value of member attribute <b>id</b>.
- */
- public Long getId( ) {
- return this.id;
- }
-
- /**
- * This method sets the value to the member attribute <b>loginId</b>.
- * You cannot set null to the attribute.
- * @param loginId Value to set member attribute <b>loginId</b>
- */
- public void setLoginId( String loginId ) {
- this.loginId = loginId;
- }
-
- /**
- * Returns the value for the member attribute <b>loginId</b>
- * @return String - value of member attribute <b>loginId</b>.
- */
- public String getLoginId( ) {
- return this.loginId;
- }
-
- /**
- * This method sets the value to the member attribute <b>emailAddress</b>.
- * You cannot set null to the attribute.
- * @param emailAddress Value to set member attribute <b>emailAddress</b>
- */
- public void setEmailAddress( String emailAddress ) {
- this.emailAddress = emailAddress;
- }
-
- /**
- * Returns the value for the member attribute <b>emailAddress</b>
- * @return String - value of member attribute <b>emailAddress</b>.
- */
- public String getEmailAddress( ) {
- return this.emailAddress;
- }
-
- /**
- * This method sets the value to the member attribute <b>resetCode</b>.
- * You cannot set null to the attribute.
- * @param resetCode Value to set member attribute <b>resetCode</b>
- */
- public void setResetCode( String resetCode ) {
- this.resetCode = resetCode;
- }
-
- /**
- * Returns the value for the member attribute <b>resetCode</b>
- * @return String - value of member attribute <b>resetCode</b>.
- */
- public String getResetCode( ) {
- return this.resetCode;
- }
-
- /**
- * This method sets the value to the member attribute <b>oldPassword</b>.
- * You cannot set null to the attribute.
- * @param oldPassword Value to set member attribute <b>oldPassword</b>
- */
- public void setOldPassword( String oldPassword ) {
- this.oldPassword = oldPassword;
- }
-
- /**
- * Returns the value for the member attribute <b>oldPassword</b>
- * @return String - value of member attribute <b>oldPassword</b>.
- */
- public String getOldPassword( ) {
- return this.oldPassword;
- }
-
- /**
- * This method sets the value to the member attribute <b>updPassword</b>.
- * You cannot set null to the attribute.
- * @param updPassword Value to set member attribute <b>updPassword</b>
- */
- public void setUpdPassword( String updPassword ) {
- this.updPassword = updPassword;
- }
-
- /**
- * Returns the value for the member attribute <b>updPassword</b>
- * @return String - value of member attribute <b>updPassword</b>.
- */
- public String getUpdPassword( ) {
- return this.updPassword;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_PASSWORD_CHANGE;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- public String toString( ) {
- String str = "VXPasswordChange={";
- str += super.toString();
- str += "id={" + id + "} ";
- str += "loginId={" + loginId + "} ";
- str += "emailAddress={" + emailAddress + "} ";
- str += "resetCode={" + resetCode + "} ";
- str += "oldPassword={***length=" + (oldPassword == null? 0 : oldPassword.length()) + "***} ";
- str += "updPassword={***length=" + (updPassword == null? 0 : updPassword.length()) + "***} ";
- str += "}";
- return str;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXPermMap.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXPermMap.java b/security-admin/src/main/java/com/xasecure/view/VXPermMap.java
deleted file mode 100644
index 7730719..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXPermMap.java
+++ /dev/null
@@ -1,334 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * Permission map
- *
- */
-
-import java.util.*;
-
-import com.xasecure.common.*;
-import com.xasecure.common.view.*;
-
-import com.xasecure.common.*;
-import com.xasecure.json.JsonDateSerializer;
-
-import com.xasecure.view.*;
-
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@JsonIgnoreProperties(ignoreUnknown=true)
-@XmlRootElement
-public class VXPermMap extends VXDataObject implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- /**
- * Group to which the permission belongs to
- */
- protected String permGroup;
- /**
- * Id of the resource
- */
- protected Long resourceId;
- /**
- * Id of the group
- */
- protected Long groupId;
- /**
- * Id of the user
- */
- protected Long userId;
- /**
- * Permission for user or group
- * This attribute is of type enum CommonEnums::XAPermForType
- */
- protected int permFor = AppConstants.XA_PERM_FOR_UNKNOWN;
- /**
- * Type of permission
- * This attribute is of type enum CommonEnums::XAPermType
- */
- protected int permType = AppConstants.XA_PERM_TYPE_UNKNOWN;
- /**
- * Grant is true and revoke is false
- */
- protected boolean grantOrRevoke = true;
- /**
- * Name of the group
- */
- protected String groupName;
- /**
- * Name of the user
- */
- protected String userName;
- /**
- * Is recursive
- * This attribute is of type enum CommonEnums::BooleanValue
- */
- protected int isRecursive = XAConstants.BOOL_NONE;
- /**
- * Is wild card
- */
- protected boolean isWildCard = true;
- /**
- * IP address for groups
- */
- protected String ipAddress;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VXPermMap ( ) {
- permFor = AppConstants.XA_PERM_FOR_UNKNOWN;
- permType = AppConstants.XA_PERM_TYPE_UNKNOWN;
- isRecursive = XAConstants.BOOL_NONE;
- }
-
- /**
- * This method sets the value to the member attribute <b>permGroup</b>.
- * You cannot set null to the attribute.
- * @param permGroup Value to set member attribute <b>permGroup</b>
- */
- public void setPermGroup( String permGroup ) {
- this.permGroup = permGroup;
- }
-
- /**
- * Returns the value for the member attribute <b>permGroup</b>
- * @return String - value of member attribute <b>permGroup</b>.
- */
- public String getPermGroup( ) {
- return this.permGroup;
- }
-
- /**
- * This method sets the value to the member attribute <b>resourceId</b>.
- * You cannot set null to the attribute.
- * @param resourceId Value to set member attribute <b>resourceId</b>
- */
- public void setResourceId( Long resourceId ) {
- this.resourceId = resourceId;
- }
-
- /**
- * Returns the value for the member attribute <b>resourceId</b>
- * @return Long - value of member attribute <b>resourceId</b>.
- */
- public Long getResourceId( ) {
- return this.resourceId;
- }
-
- /**
- * This method sets the value to the member attribute <b>groupId</b>.
- * You cannot set null to the attribute.
- * @param groupId Value to set member attribute <b>groupId</b>
- */
- public void setGroupId( Long groupId ) {
- this.groupId = groupId;
- }
-
- /**
- * Returns the value for the member attribute <b>groupId</b>
- * @return Long - value of member attribute <b>groupId</b>.
- */
- public Long getGroupId( ) {
- return this.groupId;
- }
-
- /**
- * This method sets the value to the member attribute <b>userId</b>.
- * You cannot set null to the attribute.
- * @param userId Value to set member attribute <b>userId</b>
- */
- public void setUserId( Long userId ) {
- this.userId = userId;
- }
-
- /**
- * Returns the value for the member attribute <b>userId</b>
- * @return Long - value of member attribute <b>userId</b>.
- */
- public Long getUserId( ) {
- return this.userId;
- }
-
- /**
- * This method sets the value to the member attribute <b>permFor</b>.
- * You cannot set null to the attribute.
- * @param permFor Value to set member attribute <b>permFor</b>
- */
- public void setPermFor( int permFor ) {
- this.permFor = permFor;
- }
-
- /**
- * Returns the value for the member attribute <b>permFor</b>
- * @return int - value of member attribute <b>permFor</b>.
- */
- public int getPermFor( ) {
- return this.permFor;
- }
-
- /**
- * This method sets the value to the member attribute <b>permType</b>.
- * You cannot set null to the attribute.
- * @param permType Value to set member attribute <b>permType</b>
- */
- public void setPermType( int permType ) {
- this.permType = permType;
- }
-
- /**
- * Returns the value for the member attribute <b>permType</b>
- * @return int - value of member attribute <b>permType</b>.
- */
- public int getPermType( ) {
- return this.permType;
- }
-
- /**
- * This method sets the value to the member attribute <b>grantOrRevoke</b>.
- * You cannot set null to the attribute.
- * @param grantOrRevoke Value to set member attribute <b>grantOrRevoke</b>
- */
- public void setGrantOrRevoke( boolean grantOrRevoke ) {
- this.grantOrRevoke = grantOrRevoke;
- }
-
- /**
- * Returns the value for the member attribute <b>grantOrRevoke</b>
- * @return boolean - value of member attribute <b>grantOrRevoke</b>.
- */
- public boolean isGrantOrRevoke( ) {
- return this.grantOrRevoke;
- }
-
- /**
- * This method sets the value to the member attribute <b>groupName</b>.
- * You cannot set null to the attribute.
- * @param groupName Value to set member attribute <b>groupName</b>
- */
- public void setGroupName( String groupName ) {
- this.groupName = groupName;
- }
-
- /**
- * Returns the value for the member attribute <b>groupName</b>
- * @return String - value of member attribute <b>groupName</b>.
- */
- public String getGroupName( ) {
- return this.groupName;
- }
-
- /**
- * This method sets the value to the member attribute <b>userName</b>.
- * You cannot set null to the attribute.
- * @param userName Value to set member attribute <b>userName</b>
- */
- public void setUserName( String userName ) {
- this.userName = userName;
- }
-
- /**
- * Returns the value for the member attribute <b>userName</b>
- * @return String - value of member attribute <b>userName</b>.
- */
- public String getUserName( ) {
- return this.userName;
- }
-
- /**
- * This method sets the value to the member attribute <b>isRecursive</b>.
- * You cannot set null to the attribute.
- * @param isRecursive Value to set member attribute <b>isRecursive</b>
- */
- public void setIsRecursive( int isRecursive ) {
- this.isRecursive = isRecursive;
- }
-
- /**
- * Returns the value for the member attribute <b>isRecursive</b>
- * @return int - value of member attribute <b>isRecursive</b>.
- */
- public int getIsRecursive( ) {
- return this.isRecursive;
- }
-
- /**
- * This method sets the value to the member attribute <b>isWildCard</b>.
- * You cannot set null to the attribute.
- * @param isWildCard Value to set member attribute <b>isWildCard</b>
- */
- public void setIsWildCard( boolean isWildCard ) {
- this.isWildCard = isWildCard;
- }
-
- /**
- * Returns the value for the member attribute <b>isWildCard</b>
- * @return boolean - value of member attribute <b>isWildCard</b>.
- */
- public boolean isIsWildCard( ) {
- return this.isWildCard;
- }
-
- public String getIpAddress() {
- return ipAddress;
- }
-
- public void setIpAddress(String ipAddress) {
- this.ipAddress = ipAddress;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_XA_PERM_MAP;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- public String toString( ) {
- String str = "VXPermMap={";
- str += super.toString();
- str += "permGroup={" + permGroup + "} ";
- str += "resourceId={" + resourceId + "} ";
- str += "groupId={" + groupId + "} ";
- str += "userId={" + userId + "} ";
- str += "permFor={" + permFor + "} ";
- str += "permType={" + permType + "} ";
- str += "grantOrRevoke={" + grantOrRevoke + "} ";
- str += "groupName={" + groupName + "} ";
- str += "userName={" + userName + "} ";
- str += "isRecursive={" + isRecursive + "} ";
- str += "isWildCard={" + isWildCard + "} ";
- str += "}";
- return str;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXPermMapList.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXPermMapList.java b/security-admin/src/main/java/com/xasecure/view/VXPermMapList.java
deleted file mode 100644
index 22d5ea1..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXPermMapList.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * List wrapper class for VXPermMap
- *
- */
-
-import java.util.*;
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-import com.xasecure.common.view.*;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.FIELD)
-public class VXPermMapList extends VList {
- private static final long serialVersionUID = 1L;
- List<VXPermMap> vXPermMaps = new ArrayList<VXPermMap>();
-
- public VXPermMapList() {
- super();
- }
-
- public VXPermMapList(List<VXPermMap> objList) {
- super(objList);
- this.vXPermMaps = objList;
- }
-
- /**
- * @return the vXPermMaps
- */
- public List<VXPermMap> getVXPermMaps() {
- return vXPermMaps;
- }
-
- /**
- * @param vXPermMaps
- * the vXPermMaps to set
- */
- public void setVXPermMaps(List<VXPermMap> vXPermMaps) {
- this.vXPermMaps = vXPermMaps;
- }
-
- @Override
- public int getListSize() {
- if (vXPermMaps != null) {
- return vXPermMaps.size();
- }
- return 0;
- }
-
- @Override
- public List<VXPermMap> getList() {
- return vXPermMaps;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXPermObj.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXPermObj.java b/security-admin/src/main/java/com/xasecure/view/VXPermObj.java
deleted file mode 100644
index 03b9d2f..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXPermObj.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-
-/**
- * Permission map
- */
-
-import java.util.List;
-
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY)
-@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
-@JsonIgnoreProperties(ignoreUnknown = true)
-@XmlRootElement
-public class VXPermObj implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
- /**
- * List of userName
- */
- protected List<String> userList;
- /**
- * List of groupName
- */
- protected List<String> groupList;
- /**
- * List of permission
- */
- protected List<String> permList;
- /**
- * IP address for groups
- */
- protected String ipAddress;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VXPermObj() {
-
- }
-
- /**
- * @return the userList
- */
- public List<String> getUserList() {
- return userList;
- }
-
- /**
- * @param userList
- * the userList to set
- */
- public void setUserList(List<String> userList) {
- this.userList = userList;
- }
-
- /**
- * @return the groupList
- */
- public List<String> getGroupList() {
- return groupList;
- }
-
- /**
- * @param groupList
- * the groupList to set
- */
- public void setGroupList(List<String> groupList) {
- this.groupList = groupList;
- }
-
- /**
- * @return the permList
- */
- public List<String> getPermList() {
- return permList;
- }
-
- /**
- * @param permList
- * the permList to set
- */
- public void setPermList(List<String> permList) {
- this.permList = permList;
- }
-
- /**
- * @return the ipAddress
- */
- public String getIpAddress() {
- return ipAddress;
- }
-
- /**
- * @param ipAddress
- * the ipAddress to set
- */
- public void setIpAddress(String ipAddress) {
- this.ipAddress = ipAddress;
- }
-
- /**
- * This return the bean content in string format
- *
- * @return formatedStr
- */
- public String toString() {
- String str = "VXPermMap={";
- str += super.toString();
- str += "userList={" + userList + "} ";
- str += "groupList={" + groupList + "} ";
- str += "permList={" + permList + "} ";
- str += "ipAddress={" + ipAddress + "} ";
- str += "}";
- return str;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXPermObjList.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXPermObjList.java b/security-admin/src/main/java/com/xasecure/view/VXPermObjList.java
deleted file mode 100644
index 5fa82dc..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXPermObjList.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-
-/**
- * List wrapper class for VXPermObj
- */
-
-import java.util.*;
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-import com.xasecure.common.view.*;
-
-@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY)
-@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.FIELD)
-public class VXPermObjList extends VList {
- private static final long serialVersionUID = 1L;
- List<VXPermObj> vXPermObjs = new ArrayList<VXPermObj>();
-
- public VXPermObjList() {
- super();
- }
-
- public VXPermObjList(List<VXPermObj> objList) {
- super(objList);
- this.vXPermObjs = objList;
- }
-
- /**
- * @return the vXPermObjs
- */
- public List<VXPermObj> getVXPermObjs() {
- return vXPermObjs;
- }
-
- /**
- * @param vXPermObjs
- * the vXPermObjs to set
- */
- public void setVXPermObjs(List<VXPermObj> vXPermObjs) {
- this.vXPermObjs = vXPermObjs;
- }
-
- @Override
- public int getListSize() {
- if (vXPermObjs != null) {
- return vXPermObjs.size();
- }
- return 0;
- }
-
- @Override
- public List<VXPermObj> getList() {
- return vXPermObjs;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXPolicy.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXPolicy.java b/security-admin/src/main/java/com/xasecure/view/VXPolicy.java
deleted file mode 100644
index 21e78c2..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXPolicy.java
+++ /dev/null
@@ -1,577 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-
-/**
- * Policy
- */
-
-import java.util.*;
-
-import com.xasecure.common.*;
-
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY)
-@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
-@JsonIgnoreProperties(ignoreUnknown = true)
-@XmlRootElement
-public class VXPolicy extends VXDataObject implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
- /**
- * PolicyName
- */
- protected String policyName;
- /**
- * resourceName
- */
- protected String resourceName;
- /**
- * Description
- */
- protected String description;
- /**
- * Repository Name
- */
- protected String repositoryName;
- /**
- * Repository Type
- */
- protected String repositoryType;
- /**
- * List of permissions maps
- */
- protected List<VXPermObj> permMapList;
- /**
- * Tables
- */
- protected String tables;
- /**
- * Column families
- */
- protected String columnFamilies;
- /**
- * Columns
- */
- protected String columns;
- /**
- * Databases
- */
- protected String databases;
- /**
- * UDFs
- */
- protected String udfs;
- /**
- * Table Type
- */
- protected String tableType;
- /**
- * Resource Status
- */
- protected String columnType;
- /**
- * Topologoies
- */
- protected String topologies;
- /**
- * Services
- */
- protected String services;
- /**
- * Resource/Policy Status, boolean values : true/false
- *
- */
- protected boolean isEnabled;
- /**
- * Is recursive This attribute is of type enum CommonEnums::BooleanValue
- */
- protected Boolean isRecursive;
- /**
- * Audit is enable or not.
- */
- protected boolean isAuditEnabled;
- /**
- * Version No of Project
- */
- protected String version;
-
- protected String grantor;
- protected boolean replacePerm;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VXPolicy() {
- isRecursive = false;
- replacePerm=false;
- }
-
- /**
- * Returns the value for the member attribute <b>policyName</b>
- *
- * @return String - value of member attribute <b>policyName</b>.
- */
- public String getPolicyName() {
- return policyName;
- }
-
- /**
- * This method sets the value to the member attribute <b>policyName</b>. You
- * cannot set null to the attribute.
- *
- * @param policyName
- * Value to set member attribute <b>policyName</b>
- */
- public void setPolicyName(String policyName) {
- this.policyName = policyName;
- }
-
- /**
- * This method sets the value to the member attribute <b>resourceName</b>.
- * You cannot set null to the attribute.
- *
- * @param name
- * Value to set member attribute <b>resourceName</b>
- */
- public void setResourceName(String resourceName) {
- this.resourceName = resourceName;
- }
-
- /**
- * Returns the value for the member attribute <b>resourceName</b>
- *
- * @return String - value of member attribute <b>resourceName</b>.
- */
- public String getResourceName() {
- return this.resourceName;
- }
-
- /**
- * This method sets the value to the member attribute <b>description</b>.
- * You cannot set null to the attribute.
- *
- * @param description
- * Value to set member attribute <b>description</b>
- */
- public void setDescription(String description) {
- this.description = description;
- }
-
- /**
- * Returns the value for the member attribute <b>description</b>
- *
- * @return String - value of member attribute <b>description</b>.
- */
- public String getDescription() {
- return this.description;
- }
-
- /**
- * This method sets the value to the member attribute <b>assetName</b>. You
- * cannot set null to the attribute.
- *
- * @param assetName
- * Value to set member attribute <b>assetName</b>
- */
- public void setRepositoryName(String repositoryName) {
- this.repositoryName = repositoryName;
- }
-
- /**
- * Returns the value for the member attribute <b>repositoryName</b>
- *
- * @return String - value of member attribute <b>repositoryName</b>.
- */
- public String getRepositoryName() {
- return this.repositoryName;
- }
-
- /**
- * This method sets the value to the member attribute <b>assetType</b>. You
- * cannot set null to the attribute.
- *
- * @param assetType
- * Value to set member attribute <b>assetType</b>
- */
- public void setRepositoryType(String repositoryType) {
- this.repositoryType = repositoryType;
- }
-
- /**
- * Returns the value for the member attribute <b>repositoryType</b>
- *
- * @return String - value of member attribute <b>repositoryType</b>.
- */
- public String getRepositoryType() {
- return this.repositoryType;
- }
-
- /**
- * This method sets the value to the member attribute <b>permMapList</b>.
- * You cannot set null to the attribute.
- *
- * @param permMapList
- * Value to set member attribute <b>permMapList</b>
- */
- public void setPermMapList(List<VXPermObj> permMapList) {
- this.permMapList = permMapList;
- }
-
- /**
- * Returns the value for the member attribute <b>userPermList</b>
- *
- * @return List<VXPermObj> - value of member attribute <b>permMapList</b>.
- */
- public List<VXPermObj> getPermMapList() {
- return this.permMapList;
- }
-
- /**
- * This method sets the value to the member attribute <b>tables</b>. You
- * cannot set null to the attribute.
- *
- * @param tables
- * Value to set member attribute <b>tables</b>
- */
- public void setTables(String tables) {
- this.tables = tables;
- }
-
- /**
- * Returns the value for the member attribute <b>tables</b>
- *
- * @return String - value of member attribute <b>tables</b>.
- */
- public String getTables() {
- return this.tables;
- }
-
- /**
- * This method sets the value to the member attribute <b>columnFamilies</b>.
- * You cannot set null to the attribute.
- *
- * @param columnFamilies
- * Value to set member attribute <b>columnFamilies</b>
- */
- public void setColumnFamilies(String columnFamilies) {
- this.columnFamilies = columnFamilies;
- }
-
- /**
- * Returns the value for the member attribute <b>columnFamilies</b>
- *
- * @return String - value of member attribute <b>columnFamilies</b>.
- */
- public String getColumnFamilies() {
- return this.columnFamilies;
- }
-
- /**
- * This method sets the value to the member attribute <b>columns</b>. You
- * cannot set null to the attribute.
- *
- * @param columns
- * Value to set member attribute <b>columns</b>
- */
- public void setColumns(String columns) {
- this.columns = columns;
- }
-
- /**
- * Returns the value for the member attribute <b>columns</b>
- *
- * @return String - value of member attribute <b>columns</b>.
- */
- public String getColumns() {
- return this.columns;
- }
-
- /**
- * This method sets the value to the member attribute <b>databases</b>. You
- * cannot set null to the attribute.
- *
- * @param databases
- * Value to set member attribute <b>databases</b>
- */
- public void setDatabases(String databases) {
- this.databases = databases;
- }
-
- /**
- * Returns the value for the member attribute <b>databases</b>
- *
- * @return String - value of member attribute <b>databases</b>.
- */
- public String getDatabases() {
- return this.databases;
- }
-
- /**
- * This method sets the value to the member attribute <b>udfs</b>. You
- * cannot set null to the attribute.
- *
- * @param udfs
- * Value to set member attribute <b>udfs</b>
- */
- public void setUdfs(String udfs) {
- this.udfs = udfs;
- }
-
- /**
- * Returns the value for the member attribute <b>udfs</b>
- *
- * @return String - value of member attribute <b>udfs</b>.
- */
- public String getUdfs() {
- return this.udfs;
- }
-
- /**
- * Returns the value for the member attribute <b>tableType</b>
- *
- * @return String - value of member attribute <b>tableType</b>.
- */
- public String getTableType() {
- return tableType;
- }
-
- /**
- * This method sets the value to the member attribute <b>tableType</b>. You
- * cannot set null to the attribute.
- *
- * @param tableType
- * Value to set member attribute <b>tableType</b>
- */
- public void setTableType(String tableType) {
- this.tableType = tableType;
- }
-
- /**
- * Returns the value for the member attribute <b>columnType</b>
- *
- * @return String - value of member attribute <b>columnType</b>.
- */
- public String getColumnType() {
- return columnType;
- }
-
- /**
- * This method sets the value to the member attribute <b>columnType</b>. You
- * cannot set null to the attribute.
- *
- * @param columnType
- * Value to set member attribute <b>columnType</b>
- */
- public void setColumnType(String columnType) {
- this.columnType = columnType;
- }
-
- /**
- * Returns the value for the member attribute <b>topologies</b>
- *
- * @return String - value of member attribute <b>topologies</b>.
- */
- public String getTopologies() {
- return topologies;
- }
-
- /**
- * This method sets the value to the member attribute <b>topologies</b>. You
- * cannot set null to the attribute.
- *
- * @param topologies
- * Value to set member attribute <b>topologies</b>
- */
- public void setTopologies(String topologies) {
- this.topologies = topologies;
- }
-
- /**
- * Returns the value for the member attribute <b>services</b>
- *
- * @return String - value of member attribute <b>services</b>.
- */
- public String getServices() {
- return services;
- }
-
- /**
- * This method sets the value to the member attribute <b>services</b>. You
- * cannot set null to the attribute.
- *
- * @param services
- * Value to set member attribute <b>services</b>
- */
- public void setServices(String services) {
- this.services = services;
- }
-
- /**
- * This method sets the value to the member attribute <b>resourceStatus</b>.
- * You cannot set null to the attribute.
- *
- * @param isEnabled
- * Value to set member attribute <b>isEnable</b>
- */
- public void setIsEnabled(boolean isEnabled) {
- this.isEnabled = isEnabled;
- }
-
- /**
- * Returns the value for the member attribute <b>isEnable</b>
- *
- * @return boolean - value of member attribute <b>isEnable</b>.
- */
- public boolean getIsEnabled() {
- return this.isEnabled;
- }
-
- /**
- * This method sets the value to the member attribute <b>isRecursive</b>.
- * You cannot set null to the attribute.
- *
- * @param isRecursive
- * Value to set member attribute <b>isRecursive</b>
- */
- public void setIsRecursive(Boolean isRecursive) {
- this.isRecursive = isRecursive;
- }
-
- /**
- * Returns the value for the member attribute <b>isRecursive</b>
- *
- * @return boolean - value of member attribute <b>isRecursive</b>.
- */
- public Boolean getIsRecursive() {
- return this.isRecursive;
- }
-
- /**
- * This method sets the value to the member attribute <b>isAuditEnabled</b>.
- * You cannot set null to the attribute.
- *
- * @param isAuditEnabled
- * Value to set member attribute <b>isAuditEnabled</b>
- */
- public void setIsAuditEnabled(boolean isAuditEnabled) {
- this.isAuditEnabled = isAuditEnabled;
- }
-
- /**
- * Returns the value for the member attribute <b>isAuditEnabled</b>
- *
- * @return boolean - value of member attribute <b>isAuditEnabled</b>.
- */
- public boolean getIsAuditEnabled() {
- return this.isAuditEnabled;
- }
-
- /**
- * Returns the value for the member attribute <b>version</b>
- *
- * @return String - value of member attribute <b>version</b>.
- */
- public String getVersion() {
- return version;
- }
-
- /**
- * This method sets the value to the member attribute <b>version</b>. You
- * cannot set null to the attribute.
- *
- * @param version
- * Value to set member attribute <b>version</b>
- */
- public void setVersion(String version) {
- this.version = version;
- }
-
- public String getGrantor() {
- return grantor;
- }
-
- public void setGrantor(String grantor) {
- this.grantor = grantor;
- }
-
- public boolean isReplacePerm() {
- return replacePerm;
- }
-
- public void setReplacePerm(boolean replacePerm) {
- this.replacePerm = replacePerm;
- }
-
- @Override
- public int getMyClassType() {
- return AppConstants.CLASS_TYPE_XA_RESOURCE;
- }
-
- /**
- * This return the bean content in string format
- *
- * @return formatedStr
- */
- public String toString() {
- String str = "VXResource={";
- str += super.toString();
- str += "policyName={" + policyName + "} ";
- str += "resourceName={" + resourceName + "} ";
- str += "description={" + description + "} ";
- str += "repositoryName={" + repositoryName + "} ";
- str += "repositoryType={" + repositoryType + "} ";
- str += "tables={" + tables + "} ";
- str += "columnFamilies={" + columnFamilies + "} ";
- str += "columns={" + columns + "} ";
- str += "databases={" + databases + "} ";
- str += "udfs={" + udfs + "} ";
- str += "tableType={" + tableType + "} ";
- str += "columnType={" + columnType + "} ";
- str += "topologies={" + topologies + "} ";
- str += "services={" + services + "} ";
- str += "isEnable={" + isEnabled + "} ";
- str += "isRecursive={" + isRecursive + "} ";
- str += "isAuditEnabled={" + isAuditEnabled + "} ";
- str += "version={" + version + "} ";
- str += "}";
- return str;
- }
-
- //function should be used from grant/revoke rest call only
- public void syncResponseWithJsonRequest() {
- this.setGrantor(this.getOwner());
- this.setOwner(null);
- this.setId(null);
- this.setUpdatedBy(null);
- this.setPolicyName(null);
- this.setResourceName(null);
- this.setRepositoryType(null);
- this.setVersion(null);
- this.setIsRecursive(new Boolean(null));
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXPolicyExportAudit.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXPolicyExportAudit.java b/security-admin/src/main/java/com/xasecure/view/VXPolicyExportAudit.java
deleted file mode 100644
index 9be5f4f..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXPolicyExportAudit.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * Audit Log for Policy Export
- *
- */
-
-import java.util.*;
-
-import com.xasecure.common.*;
-import com.xasecure.common.view.*;
-
-import com.xasecure.common.*;
-import com.xasecure.json.JsonDateSerializer;
-
-import com.xasecure.view.*;
-
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@JsonIgnoreProperties(ignoreUnknown=true)
-@XmlRootElement
-public class VXPolicyExportAudit extends VXDataObject implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- /**
- * XA Agent IP Address
- */
- protected String clientIP;
- /**
- * XA Agent Id
- */
- protected String agentId;
- /**
- * Last update timestamp in request
- */
- protected Long requestedEpoch;
- /**
- * Date and time of the last policy update
- */
- @JsonSerialize(using=JsonDateSerializer.class)
- protected Date lastUpdated;
- /**
- * Id of the Asset
- */
- protected String repositoryName;
- /**
- * JSON of the policies exported
- */
- protected String exportedJson;
- /**
- * HTTP Response Code
- */
- protected int httpRetCode;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VXPolicyExportAudit ( ) {
- }
-
- /**
- * This method sets the value to the member attribute <b>clientIP</b>.
- * You cannot set null to the attribute.
- * @param clientIP Value to set member attribute <b>clientIP</b>
- */
- public void setClientIP( String clientIP ) {
- this.clientIP = clientIP;
- }
-
- /**
- * Returns the value for the member attribute <b>clientIP</b>
- * @return String - value of member attribute <b>clientIP</b>.
- */
- public String getClientIP( ) {
- return this.clientIP;
- }
-
- /**
- * This method sets the value to the member attribute <b>agentId</b>.
- * You cannot set null to the attribute.
- * @param agentId Value to set member attribute <b>agentId</b>
- */
- public void setAgentId( String agentId ) {
- this.agentId = agentId;
- }
-
- /**
- * Returns the value for the member attribute <b>agentId</b>
- * @return String - value of member attribute <b>agentId</b>.
- */
- public String getAgentId( ) {
- return this.agentId;
- }
-
- /**
- * This method sets the value to the member attribute <b>requestedEpoch</b>.
- * You cannot set null to the attribute.
- * @param requestedEpoch Value to set member attribute <b>requestedEpoch</b>
- */
- public void setRequestedEpoch( Long requestedEpoch ) {
- this.requestedEpoch = requestedEpoch;
- }
-
- /**
- * Returns the value for the member attribute <b>requestedEpoch</b>
- * @return Long - value of member attribute <b>requestedEpoch</b>.
- */
- public Long getRequestedEpoch( ) {
- return this.requestedEpoch;
- }
-
- /**
- * This method sets the value to the member attribute <b>lastUpdated</b>.
- * You cannot set null to the attribute.
- * @param lastUpdated Value to set member attribute <b>lastUpdated</b>
- */
- public void setLastUpdated( Date lastUpdated ) {
- this.lastUpdated = lastUpdated;
- }
-
- /**
- * Returns the value for the member attribute <b>lastUpdated</b>
- * @return Date - value of member attribute <b>lastUpdated</b>.
- */
- public Date getLastUpdated( ) {
- return this.lastUpdated;
- }
-
- /**
- * This method sets the value to the member attribute <b>repositoryName</b>.
- * You cannot set null to the attribute.
- * @param repositoryName Value to set member attribute <b>repositoryName</b>
- */
- public void setRepositoryName( String repositoryName ) {
- this.repositoryName = repositoryName;
- }
-
- /**
- * Returns the value for the member attribute <b>repositoryName</b>
- * @return String - value of member attribute <b>repositoryName</b>.
- */
- public String getRepositoryName( ) {
- return this.repositoryName;
- }
-
- /**
- * This method sets the value to the member attribute <b>exportedJson</b>.
- * You cannot set null to the attribute.
- * @param exportedJson Value to set member attribute <b>exportedJson</b>
- */
- public void setExportedJson( String exportedJson ) {
- this.exportedJson = exportedJson;
- }
-
- /**
- * Returns the value for the member attribute <b>exportedJson</b>
- * @return String - value of member attribute <b>exportedJson</b>.
- */
- public String getExportedJson( ) {
- return this.exportedJson;
- }
-
- /**
- * This method sets the value to the member attribute <b>httpRetCode</b>.
- * You cannot set null to the attribute.
- * @param httpRetCode Value to set member attribute <b>httpRetCode</b>
- */
- public void setHttpRetCode( int httpRetCode ) {
- this.httpRetCode = httpRetCode;
- }
-
- /**
- * Returns the value for the member attribute <b>httpRetCode</b>
- * @return int - value of member attribute <b>httpRetCode</b>.
- */
- public int getHttpRetCode( ) {
- return this.httpRetCode;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_XA_POLICY_EXPORT_AUDIT;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- public String toString( ) {
- String str = "VXPolicyExportAudit={";
- str += super.toString();
- str += "clientIP={" + clientIP + "} ";
- str += "agentId={" + agentId + "} ";
- str += "requestedEpoch={" + requestedEpoch + "} ";
- str += "lastUpdated={" + lastUpdated + "} ";
- str += "repositoryName={" + repositoryName + "} ";
- str += "exportedJson={" + exportedJson + "} ";
- str += "httpRetCode={" + httpRetCode + "} ";
- str += "}";
- return str;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXPolicyExportAuditList.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXPolicyExportAuditList.java b/security-admin/src/main/java/com/xasecure/view/VXPolicyExportAuditList.java
deleted file mode 100644
index 3ccd95c..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXPolicyExportAuditList.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * List wrapper class for VXPolicyExportAudit
- *
- */
-
-import java.util.*;
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-import com.xasecure.common.view.*;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.FIELD)
-public class VXPolicyExportAuditList extends VList {
- private static final long serialVersionUID = 1L;
- List<VXPolicyExportAudit> vXPolicyExportAudits = new ArrayList<VXPolicyExportAudit>();
-
- public VXPolicyExportAuditList() {
- super();
- }
-
- public VXPolicyExportAuditList(List<VXPolicyExportAudit> objList) {
- super(objList);
- this.vXPolicyExportAudits = objList;
- }
-
- /**
- * @return the vXPolicyExportAudits
- */
- public List<VXPolicyExportAudit> getVXPolicyExportAudits() {
- return vXPolicyExportAudits;
- }
-
- /**
- * @param vXPolicyExportAudits
- * the vXPolicyExportAudits to set
- */
- public void setVXPolicyExportAudits(List<VXPolicyExportAudit> vXPolicyExportAudits) {
- this.vXPolicyExportAudits = vXPolicyExportAudits;
- }
-
- @Override
- public int getListSize() {
- if (vXPolicyExportAudits != null) {
- return vXPolicyExportAudits.size();
- }
- return 0;
- }
-
- @Override
- public List<VXPolicyExportAudit> getList() {
- return vXPolicyExportAudits;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXPolicyList.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXPolicyList.java b/security-admin/src/main/java/com/xasecure/view/VXPolicyList.java
deleted file mode 100644
index 4f189eb..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXPolicyList.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-
-/**
- * List wrapper class for VXPolicy
- */
-
-import java.util.*;
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-import com.xasecure.common.view.*;
-
-@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY)
-@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.FIELD)
-public class VXPolicyList extends VList {
- private static final long serialVersionUID = 1L;
- List<VXPolicy> vXPolicies = new ArrayList<VXPolicy>();
-
- public VXPolicyList() {
- super();
- }
-
- public VXPolicyList(List<VXPolicy> objList) {
- super(objList);
- this.vXPolicies = objList;
- }
-
- /**
- * @return the vXPolicies
- */
- public List<VXPolicy> getVXPolicies() {
- return vXPolicies;
- }
-
- /**
- * @param vXPolicies
- * the vXPolicies to set
- */
- public void setVXPolicies(List<VXPolicy> vXPolicies) {
- this.vXPolicies = vXPolicies;
- }
-
- @Override
- public int getListSize() {
- if (vXPolicies != null) {
- return vXPolicies.size();
- }
- return 0;
- }
-
- @Override
- public List<VXPolicy> getList() {
- return vXPolicies;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXPortalUser.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXPortalUser.java b/security-admin/src/main/java/com/xasecure/view/VXPortalUser.java
deleted file mode 100644
index afa3267..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXPortalUser.java
+++ /dev/null
@@ -1,293 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-import java.util.*;
-
-import com.xasecure.common.*;
-import com.xasecure.common.view.*;
-
-import com.xasecure.common.*;
-import com.xasecure.json.JsonDateSerializer;
-
-import com.xasecure.view.*;
-
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@JsonIgnoreProperties(ignoreUnknown=true)
-@XmlRootElement
-public class VXPortalUser extends VXDataObject implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
-
- /**
- * Login Id for the user
- */
- protected String loginId;
- /**
- * Password
- */
- protected String password;
- /**
- * Status
- * This attribute is of type enum CommonEnums::ActivationStatus
- */
- protected int status;
- /**
- * Email address of the user
- */
- protected String emailAddress;
- /**
- * First name of the user
- */
- protected String firstName;
- /**
- * Last name of the user
- */
- protected String lastName;
- /**
- * Public name of the user
- */
- protected String publicScreenName;
- /**
- * Source of the user
- * This attribute is of type enum CommonEnums::UserSource
- */
- protected int userSource;
- /**
- * Notes for the user
- */
- protected String notes;
- /**
- * List of roles for this user
- */
- protected Collection<String> userRoleList;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VXPortalUser ( ) {
- status = 0;
- userSource = 0;
- }
-
- /**
- * This method sets the value to the member attribute <b>loginId</b>.
- * You cannot set null to the attribute.
- * @param loginId Value to set member attribute <b>loginId</b>
- */
- public void setLoginId( String loginId ) {
- this.loginId = loginId;
- }
-
- /**
- * Returns the value for the member attribute <b>loginId</b>
- * @return String - value of member attribute <b>loginId</b>.
- */
- public String getLoginId( ) {
- return this.loginId;
- }
-
- /**
- * This method sets the value to the member attribute <b>password</b>.
- * You cannot set null to the attribute.
- * @param password Value to set member attribute <b>password</b>
- */
- public void setPassword( String password ) {
- this.password = password;
- }
-
- /**
- * Returns the value for the member attribute <b>password</b>
- * @return String - value of member attribute <b>password</b>.
- */
- public String getPassword( ) {
- return this.password;
- }
-
- /**
- * This method sets the value to the member attribute <b>status</b>.
- * You cannot set null to the attribute.
- * @param status Value to set member attribute <b>status</b>
- */
- public void setStatus( int status ) {
- this.status = status;
- }
-
- /**
- * Returns the value for the member attribute <b>status</b>
- * @return int - value of member attribute <b>status</b>.
- */
- public int getStatus( ) {
- return this.status;
- }
-
- /**
- * This method sets the value to the member attribute <b>emailAddress</b>.
- * You cannot set null to the attribute.
- * @param emailAddress Value to set member attribute <b>emailAddress</b>
- */
- public void setEmailAddress( String emailAddress ) {
- this.emailAddress = emailAddress;
- }
-
- /**
- * Returns the value for the member attribute <b>emailAddress</b>
- * @return String - value of member attribute <b>emailAddress</b>.
- */
- public String getEmailAddress( ) {
- return this.emailAddress;
- }
-
- /**
- * This method sets the value to the member attribute <b>firstName</b>.
- * You cannot set null to the attribute.
- * @param firstName Value to set member attribute <b>firstName</b>
- */
- public void setFirstName( String firstName ) {
- this.firstName = firstName;
- }
-
- /**
- * Returns the value for the member attribute <b>firstName</b>
- * @return String - value of member attribute <b>firstName</b>.
- */
- public String getFirstName( ) {
- return this.firstName;
- }
-
- /**
- * This method sets the value to the member attribute <b>lastName</b>.
- * You cannot set null to the attribute.
- * @param lastName Value to set member attribute <b>lastName</b>
- */
- public void setLastName( String lastName ) {
- this.lastName = lastName;
- }
-
- /**
- * Returns the value for the member attribute <b>lastName</b>
- * @return String - value of member attribute <b>lastName</b>.
- */
- public String getLastName( ) {
- return this.lastName;
- }
-
- /**
- * This method sets the value to the member attribute <b>publicScreenName</b>.
- * You cannot set null to the attribute.
- * @param publicScreenName Value to set member attribute <b>publicScreenName</b>
- */
- public void setPublicScreenName( String publicScreenName ) {
- this.publicScreenName = publicScreenName;
- }
-
- /**
- * Returns the value for the member attribute <b>publicScreenName</b>
- * @return String - value of member attribute <b>publicScreenName</b>.
- */
- public String getPublicScreenName( ) {
- return this.publicScreenName;
- }
-
- /**
- * This method sets the value to the member attribute <b>userSource</b>.
- * You cannot set null to the attribute.
- * @param userSource Value to set member attribute <b>userSource</b>
- */
- public void setUserSource( int userSource ) {
- this.userSource = userSource;
- }
-
- /**
- * Returns the value for the member attribute <b>userSource</b>
- * @return int - value of member attribute <b>userSource</b>.
- */
- public int getUserSource( ) {
- return this.userSource;
- }
-
- /**
- * This method sets the value to the member attribute <b>notes</b>.
- * You cannot set null to the attribute.
- * @param notes Value to set member attribute <b>notes</b>
- */
- public void setNotes( String notes ) {
- this.notes = notes;
- }
-
- /**
- * Returns the value for the member attribute <b>notes</b>
- * @return String - value of member attribute <b>notes</b>.
- */
- public String getNotes( ) {
- return this.notes;
- }
-
- /**
- * This method sets the value to the member attribute <b>userRoleList</b>.
- * You cannot set null to the attribute.
- * @param userRoleList Value to set member attribute <b>userRoleList</b>
- */
- public void setUserRoleList( Collection<String> userRoleList ) {
- this.userRoleList = userRoleList;
- }
-
- /**
- * Returns the value for the member attribute <b>userRoleList</b>
- * @return Collection<String> - value of member attribute <b>userRoleList</b>.
- */
- public Collection<String> getUserRoleList( ) {
- return this.userRoleList;
- }
-
- @Override
- public int getMyClassType( ) {
- return AppConstants.CLASS_TYPE_USER_PROFILE;
- }
-
- /**
- * This return the bean content in string format
- * @return formatedStr
- */
- public String toString( ) {
- String str = "VXPortalUser={";
- str += super.toString();
- str += "loginId={" + loginId + "} ";
- str += "password={***length=" + (password == null? 0 : password.length()) + "***} ";
- str += "status={" + status + "} ";
- str += "emailAddress={" + emailAddress + "} ";
- str += "firstName={" + firstName + "} ";
- str += "lastName={" + lastName + "} ";
- str += "publicScreenName={" + publicScreenName + "} ";
- str += "userSource={" + userSource + "} ";
- str += "notes={" + notes + "} ";
- str += "userRoleList={" + userRoleList + "} ";
- str += "}";
- return str;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXPortalUserList.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXPortalUserList.java b/security-admin/src/main/java/com/xasecure/view/VXPortalUserList.java
deleted file mode 100644
index c21d22d..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXPortalUserList.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-/**
- * List wrapper class for VXPortalUser
- *
- */
-
-import java.util.*;
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-import com.xasecure.common.view.*;
-
-@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY)
-@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL )
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.FIELD)
-public class VXPortalUserList extends VList {
- private static final long serialVersionUID = 1L;
- List<VXPortalUser> vXPortalUsers = new ArrayList<VXPortalUser>();
-
- public VXPortalUserList() {
- super();
- }
-
- public VXPortalUserList(List<VXPortalUser> objList) {
- super(objList);
- this.vXPortalUsers = objList;
- }
-
- /**
- * @return the vXPortalUsers
- */
- public List<VXPortalUser> getVXPortalUsers() {
- return vXPortalUsers;
- }
-
- /**
- * @param vXPortalUsers
- * the vXPortalUsers to set
- */
- public void setVXPortalUsers(List<VXPortalUser> vXPortalUsers) {
- this.vXPortalUsers = vXPortalUsers;
- }
-
- @Override
- public int getListSize() {
- if (vXPortalUsers != null) {
- return vXPortalUsers.size();
- }
- return 0;
- }
-
- @Override
- public List<VXPortalUser> getList() {
- return vXPortalUsers;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/view/VXRepository.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/view/VXRepository.java b/security-admin/src/main/java/com/xasecure/view/VXRepository.java
deleted file mode 100644
index 04f0d24..0000000
--- a/security-admin/src/main/java/com/xasecure/view/VXRepository.java
+++ /dev/null
@@ -1,219 +0,0 @@
-/*
- * 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 com.xasecure.view;
-
-
-/**
- * Repository
- */
-
-import com.xasecure.common.*;
-
-import javax.xml.bind.annotation.*;
-
-import org.codehaus.jackson.annotate.JsonAutoDetect;
-import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
-import org.codehaus.jackson.annotate.JsonIgnoreProperties;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-
-@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY)
-@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
-@JsonIgnoreProperties(ignoreUnknown = true)
-@XmlRootElement
-public class VXRepository extends VXDataObject implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
-
- /**
- * Name
- */
- protected String name;
- /**
- * Description
- */
- protected String description;
- /**
- * Type of asset. i.e HDFS, HIVE, HBASE, KNOX
- */
- protected String repositoryType;
- /**
- * Config in json format
- */
- protected String config;
- /**
- * Status This attribute is of type boolean : true/false
- */
- protected boolean isActive;
- /**
- * Version No of Project
- */
- protected String version;
-
- /**
- * Default constructor. This will set all the attributes to default value.
- */
- public VXRepository() {
- isActive = false;
- repositoryType = "";
-
- }
-
- /**
- * This method sets the value to the member attribute <b>name</b>. You
- * cannot set null to the attribute.
- *
- * @param name
- * Value to set member attribute <b>name</b>
- */
- public void setName(String name) {
- this.name = name;
- }
-
- /**
- * Returns the value for the member attribute <b>name</b>
- *
- * @return String - value of member attribute <b>name</b>.
- */
- public String getName() {
- return this.name;
- }
-
- /**
- * This method sets the value to the member attribute <b>description</b>.
- * You cannot set null to the attribute.
- *
- * @param description
- * Value to set member attribute <b>description</b>
- */
- public void setDescription(String description) {
- this.description = description;
- }
-
- /**
- * Returns the value for the member attribute <b>description</b>
- *
- * @return String - value of member attribute <b>description</b>.
- */
- public String getDescription() {
- return this.description;
- }
-
- /**
- * This method sets the value to the member attribute <b>repositoryType</b>.
- * You cannot set null to the attribute.
- *
- * @param repositoryType
- * Value to set member attribute <b>repositoryType</b>
- */
- public void setRepositoryType(String repositoryType) {
- this.repositoryType = repositoryType;
- }
-
- /**
- * Returns the value for the member attribute <b>repositoryType</b>
- *
- * @return String - value of member attribute <b>repositoryType</b>.
- */
- public String getRepositoryType() {
- return this.repositoryType;
- }
-
- /**
- * This method sets the value to the member attribute <b>config</b>. You
- * cannot set null to the attribute.
- *
- * @param config
- * Value to set member attribute <b>config</b>
- */
- public void setConfig(String config) {
- this.config = config;
- }
-
- /**
- * Returns the value for the member attribute <b>config</b>
- *
- * @return String - value of member attribute <b>config</b>.
- */
- public String getConfig() {
- return this.config;
- }
-
- /**
- * This method sets the value to the member attribute <b>isActive</b>. You
- * cannot set null to the attribute.
- *
- * @param isActive
- * Value to set member attribute <b>isActive</b>
- */
- public void setIsActive(boolean isActive) {
- this.isActive = isActive;
- }
-
- /**
- * Returns the value for the member attribute <b>isActive</b>
- *
- * @return boolean - value of member attribute <b>isActive</b>.
- */
- public boolean getIsActive() {
- return this.isActive;
- }
-
- /**
- * Returns the value for the member attribute <b>version</b>
- *
- * @return String - value of member attribute <b>version</b>.
- */
- public String getVersion() {
- return version;
- }
-
- /**
- * This method sets the value to the member attribute <b>version</b>. You
- * cannot set null to the attribute.
- *
- * @param version
- * Value to set member attribute <b>version</b>
- */
- public void setVersion(String version) {
- this.version = version;
- }
-
- @Override
- public int getMyClassType() {
- return AppConstants.CLASS_TYPE_XA_ASSET;
- }
-
- /**
- * This return the bean content in string format
- *
- * @return formatedStr
- */
- public String toString() {
- String str = "VXAsset={";
- str += super.toString();
- str += "name={" + name + "} ";
- str += "description={" + description + "} ";
- str += "isActive={" + isActive + "} ";
- str += "repositoryType={" + repositoryType + "} ";
- str += "config={" + config + "} ";
- str += "version={" + version + "} ";
- str += "}";
- return str;
- }
-}
[17/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/security/standalone/StandaloneSecurityHandler.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/security/standalone/StandaloneSecurityHandler.java b/security-admin/src/main/java/com/xasecure/security/standalone/StandaloneSecurityHandler.java
deleted file mode 100644
index 1e9ffb0..0000000
--- a/security-admin/src/main/java/com/xasecure/security/standalone/StandaloneSecurityHandler.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * 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 com.xasecure.security.standalone;
-
-import java.net.InetAddress;
-import java.util.ArrayList;
-import java.util.Collection;
-
-import com.xasecure.biz.SessionMgr;
-import com.xasecure.common.XAConstants;
-import com.xasecure.entity.XXAuthSession;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.ApplicationContext;
-import org.springframework.security.access.ConfigAttribute;
-import org.springframework.security.access.SecurityConfig;
-import org.springframework.security.access.vote.AffirmativeBased;
-import org.springframework.security.authentication.AuthenticationManager;
-import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.context.SecurityContextHolder;
-import org.springframework.stereotype.Component;
-
-@Component
-public class StandaloneSecurityHandler {
- public static final String AUTH_MANAGER_BEAN_NAME = "authenticationManager";
- public static final String ACCESS_DECISION_MANAGER_BEAN_NAME = "customAccessDecisionManager";
-
- @Autowired
- SessionMgr sessionMgr;
-
- public void login(String userName, String password,
- ApplicationContext context) throws Exception {
- // [1] Create AUTH Token
- Authentication token = new UsernamePasswordAuthenticationToken(
- userName, password);
-
- // [2] Authenticate User
- AuthenticationManager am = (AuthenticationManager) context
- .getBean(AUTH_MANAGER_BEAN_NAME);
- token = am.authenticate(token);
-
- // [3] Check User Access
- AffirmativeBased accessDecisionManager = (AffirmativeBased) context
- .getBean(ACCESS_DECISION_MANAGER_BEAN_NAME);
- Collection<ConfigAttribute> list = new ArrayList<ConfigAttribute>();
- SecurityConfig config = new SecurityConfig(XAConstants.ROLE_SYS_ADMIN);
- list.add(config);
- accessDecisionManager.decide(token, null, list);
-
- // [4] set token in spring context
- SecurityContextHolder.getContext().setAuthentication(token);
-
- // [5] Process Success login
- InetAddress thisIp = InetAddress.getLocalHost();
- sessionMgr.processStandaloneSuccessLogin(
- XXAuthSession.AUTH_TYPE_PASSWORD, thisIp.getHostAddress());
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/security/web/authentication/CustomLogoutSuccessHandler.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/security/web/authentication/CustomLogoutSuccessHandler.java b/security-admin/src/main/java/com/xasecure/security/web/authentication/CustomLogoutSuccessHandler.java
deleted file mode 100644
index e3af85d..0000000
--- a/security-admin/src/main/java/com/xasecure/security/web/authentication/CustomLogoutSuccessHandler.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * 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 com.xasecure.security.web.authentication;
-
-import java.io.IOException;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
-import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
-
-import com.xasecure.common.JSONUtil;
-import com.xasecure.view.VXResponse;
-
-public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler
- implements LogoutSuccessHandler {
-
- @Autowired
- JSONUtil jsonUtil;
-
- @Override
- public void onLogoutSuccess(HttpServletRequest request,
- HttpServletResponse response, Authentication authentication)
- throws IOException, ServletException {
-
- response.setContentType("application/json;charset=UTF-8");
- response.setHeader("Cache-Control", "no-cache");
- String jsonStr = "";
- try {
- VXResponse vXResponse = new VXResponse();
- vXResponse.setStatusCode(HttpServletResponse.SC_OK);
- vXResponse.setMsgDesc("Logout Successful");
- jsonStr = jsonUtil.writeObjectAsString(vXResponse);
-
- response.setStatus(HttpServletResponse.SC_OK);
- response.getWriter().write(jsonStr);
-
- if (logger.isDebugEnabled()) {
- logger.debug("Log-out Successfully done. Returning Json : " +jsonStr);
- }
-
- } catch (IOException e) {
- logger.info("Error while writing JSON in HttpServletResponse");
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthFailureHandler.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthFailureHandler.java b/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthFailureHandler.java
deleted file mode 100644
index 70b3df4..0000000
--- a/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthFailureHandler.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * 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 com.xasecure.security.web.authentication;
-
-import java.io.IOException;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import com.xasecure.common.JSONUtil;
-import com.xasecure.common.PropertiesUtil;
-import com.xasecure.view.VXResponse;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler;
-
-/**
- *
- *
- */
-public class XAAuthFailureHandler extends
-ExceptionMappingAuthenticationFailureHandler {
- static Logger logger = Logger.getLogger(XAAuthFailureHandler.class);
-
- String ajaxLoginfailurePage = null;
-
- @Autowired
- JSONUtil jsonUtil;
-
- public XAAuthFailureHandler() {
- super();
- if (ajaxLoginfailurePage == null) {
- ajaxLoginfailurePage = PropertiesUtil.getProperty(
- "xa.ajax.auth.failure.page", "/ajax_failure.jsp");
- }
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.springframework.security.web.authentication.
- * ExceptionMappingAuthenticationFailureHandler
- * #onAuthenticationFailure(javax.servlet.http.HttpServletRequest,
- * javax.servlet.http.HttpServletResponse,
- * org.springframework.security.core.AuthenticationException)
- */
- @Override
- public void onAuthenticationFailure(HttpServletRequest request,
- HttpServletResponse response, AuthenticationException exception)
- throws IOException, ServletException {
- String ajaxRequestHeader = request.getHeader("X-Requested-With");
- if (logger.isDebugEnabled()) {
- logger.debug("commence() X-Requested-With=" + ajaxRequestHeader);
- }
-
- response.setContentType("application/json;charset=UTF-8");
- response.setHeader("Cache-Control", "no-cache");
- String jsonResp = "";
- try {
- VXResponse vXResponse = new VXResponse();
- vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
- vXResponse.setMsgDesc("Bad Credentials");
-
- jsonResp = jsonUtil.writeObjectAsString(vXResponse);
- response.getWriter().write(jsonResp);
- response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
- } catch (IOException e) {
- logger.info("Error while writing JSON in HttpServletResponse");
- }
-
- if (ajaxRequestHeader != null && ajaxRequestHeader.equalsIgnoreCase("XMLHttpRequest")) {
-// if (logger.isDebugEnabled()) {
-// logger.debug("Forwarding AJAX login request failure to "
-// + ajaxLoginfailurePage);
-// }
-// request.getRequestDispatcher(ajaxLoginfailurePage).forward(request,
-// response);
- if (logger.isDebugEnabled()) {
- logger.debug("Sending login failed response : " + jsonResp);
- }
- } else {
-// super.onAuthenticationFailure(request, response, exception);
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthSuccessHandler.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthSuccessHandler.java b/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthSuccessHandler.java
deleted file mode 100644
index 426683d..0000000
--- a/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthSuccessHandler.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * 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 com.xasecure.security.web.authentication;
-
-import java.io.IOException;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import com.xasecure.biz.SessionMgr;
-import com.xasecure.common.JSONUtil;
-import com.xasecure.common.PropertiesUtil;
-import com.xasecure.entity.XXAuthSession;
-import com.xasecure.view.VXResponse;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
-import org.springframework.security.web.authentication.WebAuthenticationDetails;
-
-/**
- *
- *
- */
-public class XAAuthSuccessHandler extends
-SavedRequestAwareAuthenticationSuccessHandler {
- static Logger logger = Logger.getLogger(XAAuthSuccessHandler.class);
-
- String ajaxLoginSuccessPage = null;
-
- @Autowired
- SessionMgr sessionMgr;
-
- @Autowired
- JSONUtil jsonUtil;
-
- public XAAuthSuccessHandler() {
- super();
- if (ajaxLoginSuccessPage == null) {
- ajaxLoginSuccessPage = PropertiesUtil.getProperty(
- "xa.ajax.auth.success.page", "/ajax_success.html");
- }
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.springframework.security.web.authentication.
- * SavedRequestAwareAuthenticationSuccessHandler
- * #onAuthenticationSuccess(javax.servlet.http.HttpServletRequest,
- * javax.servlet.http.HttpServletResponse,
- * org.springframework.security.core.Authentication)
- */
- @Override
- public void onAuthenticationSuccess(HttpServletRequest request,
- HttpServletResponse response, Authentication authentication)
- throws ServletException, IOException {
-
- WebAuthenticationDetails details = (WebAuthenticationDetails) authentication
- .getDetails();
- String remoteAddress = details != null ? details.getRemoteAddress()
- : "";
- String sessionId = details != null ? details.getSessionId() : "";
-
- boolean isValidUser = sessionMgr.isValidXAUser(authentication.getName());
-
- response.setContentType("application/json;charset=UTF-8");
- response.setHeader("Cache-Control", "no-cache");
-
- VXResponse vXResponse = new VXResponse();
-
- if(!isValidUser) {
- sessionMgr.processFailureLogin(
- XXAuthSession.AUTH_STATUS_USER_NOT_FOUND,
- XXAuthSession.AUTH_TYPE_PASSWORD, authentication.getName(),
- remoteAddress, sessionId);
- authentication.setAuthenticated(false);
-
- vXResponse.setStatusCode(HttpServletResponse.SC_PRECONDITION_FAILED);
- vXResponse.setMsgDesc("Auth Succeeded but user is not synced yet for " + authentication.getName());
-
- response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
- response.getWriter().write(jsonUtil.writeObjectAsString(vXResponse));
-
- // response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
- logger.info("Auth Succeeded but user is not synced yet for "
- + authentication.getName());
-
- } else {
-
- String ajaxRequestHeader = request.getHeader("X-Requested-With");
- if (logger.isDebugEnabled()) {
- logger.debug("commence() X-Requested-With=" + ajaxRequestHeader);
- }
- if (ajaxRequestHeader != null && ajaxRequestHeader.equalsIgnoreCase("XMLHttpRequest")) {
- // if (logger.isDebugEnabled()) {
- // logger.debug("Forwarding AJAX login request success to "
- // + ajaxLoginSuccessPage + " for user "
- // + authentication.getName());
- // }
- // request.getRequestDispatcher(ajaxLoginSuccessPage).forward(request,
- // response);
-
- String jsonResp = "";
- try {
- vXResponse.setStatusCode(HttpServletResponse.SC_OK);
- vXResponse.setMsgDesc("Login Successful");
-
- response.setStatus(HttpServletResponse.SC_OK);
- jsonResp = jsonUtil.writeObjectAsString(vXResponse);
- response.getWriter().write(jsonResp);
- } catch (IOException e) {
- logger.info("Error while writing JSON in HttpServletResponse");
- }
- if (logger.isDebugEnabled()) {
- logger.debug("Sending login success response : " + jsonResp);
- }
- clearAuthenticationAttributes(request);
- } else {
- String jsonResp = "";
- try {
- vXResponse.setStatusCode(HttpServletResponse.SC_OK);
- vXResponse.setMsgDesc("Login Successful");
-
- response.setStatus(HttpServletResponse.SC_OK);
- jsonResp = jsonUtil.writeObjectAsString(vXResponse);
- response.getWriter().write(jsonResp);
- } catch (IOException e) {
- logger.info("Error while writing JSON in HttpServletResponse");
- }
- if (logger.isDebugEnabled()) {
- logger.debug("Sending login success response : " + jsonResp);
- }
- // super.onAuthenticationSuccess(request, response,
- // authentication);
- }
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthenticationEntryPoint.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthenticationEntryPoint.java b/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthenticationEntryPoint.java
deleted file mode 100644
index 4c59519..0000000
--- a/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthenticationEntryPoint.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * 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 com.xasecure.security.web.authentication;
-
-import java.io.IOException;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import com.xasecure.common.JSONUtil;
-import com.xasecure.common.PropertiesUtil;
-import com.xasecure.common.XAConfigUtil;
-import com.xasecure.view.VXResponse;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
-
-
-/**
- *
- *
- */
-public class XAAuthenticationEntryPoint extends
-LoginUrlAuthenticationEntryPoint {
- static Logger logger = Logger.getLogger(XAAuthenticationEntryPoint.class);
- static int ajaxReturnCode = -1;
-
- @Autowired
- XAConfigUtil configUtil;
-
- @Autowired
- JSONUtil jsonUtil;
-
- public XAAuthenticationEntryPoint() {
- super();
- if (logger.isDebugEnabled()) {
- logger.debug("AjaxAwareAuthenticationEntryPoint(): constructor");
- }
-
- if (ajaxReturnCode < 0) {
- ajaxReturnCode = PropertiesUtil.getIntProperty(
- "xa.ajax.auth.required.code", 401);
- }
- }
-
- @Override
- public void commence(HttpServletRequest request,
- HttpServletResponse response, AuthenticationException authException)
- throws IOException, ServletException {
- String ajaxRequestHeader = request.getHeader("X-Requested-With");
- if (logger.isDebugEnabled()) {
- logger.debug("commence() X-Requested-With=" + ajaxRequestHeader);
- }
-
- String requestURL = (request.getRequestURL() != null) ? request.getRequestURL().toString() : "";
- String servletPath = PropertiesUtil.getProperty("xa.servlet.mapping.url.pattern", "service");
- String reqServletPath = configUtil.getWebAppRootURL() + "/" + servletPath;
-
- response.setContentType("application/json;charset=UTF-8");
- response.setHeader("Cache-Control", "no-cache");
- try {
-
- VXResponse vXResponse = new VXResponse();
-
- vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
- vXResponse.setMsgDesc("Authentication Failed");
-
- response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
- response.getWriter().write(jsonUtil.writeObjectAsString(vXResponse));
- } catch (IOException e) {
- logger.info("Error while writing JSON in HttpServletResponse");
- }
-
- if (ajaxRequestHeader != null && ajaxRequestHeader.equalsIgnoreCase("XMLHttpRequest")) {
- if (logger.isDebugEnabled()) {
- logger.debug("commence() AJAX request. Authentication required. Returning "
- + ajaxReturnCode + ". URL=" + request.getRequestURI());
- }
- response.sendError(ajaxReturnCode, "");
- } else if(!(requestURL.startsWith(reqServletPath))) {
- super.commence(request, response, authException);
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/security/web/filter/MyRememberMeFilter.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/security/web/filter/MyRememberMeFilter.java b/security-admin/src/main/java/com/xasecure/security/web/filter/MyRememberMeFilter.java
deleted file mode 100644
index ca2b36b..0000000
--- a/security-admin/src/main/java/com/xasecure/security/web/filter/MyRememberMeFilter.java
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * 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 com.xasecure.security.web.filter;
-
-import java.io.IOException;
-
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.log4j.Logger;
-import org.springframework.context.ApplicationEventPublisher;
-import org.springframework.security.authentication.AuthenticationManager;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
-import org.springframework.security.web.authentication.RememberMeServices;
-import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter;
-
-/**
- *
- *
- */
-@SuppressWarnings("deprecation")
-public class MyRememberMeFilter extends RememberMeAuthenticationFilter {
-
- static Logger logger = Logger.getLogger(MyRememberMeFilter.class);
-
- /*
- * (non-Javadoc)
- *
- * @see org.springframework.security.web.authentication.rememberme.
- * RememberMeAuthenticationFilter#afterPropertiesSet()
- */
- @Override
- public void afterPropertiesSet() {
- // TODO Auto-generated method stub
- super.afterPropertiesSet();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.springframework.security.web.authentication.rememberme.
- * RememberMeAuthenticationFilter#doFilter(javax.servlet.ServletRequest,
- * javax.servlet.ServletResponse, javax.servlet.FilterChain)
- */
- @Override
- public void doFilter(ServletRequest arg0, ServletResponse arg1,
- FilterChain arg2) throws IOException, ServletException {
- // TODO Auto-generated method stub
- super.doFilter(arg0, arg1, arg2);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.springframework.security.web.authentication.rememberme.
- * RememberMeAuthenticationFilter#getRememberMeServices()
- */
- @Override
- public RememberMeServices getRememberMeServices() {
- // TODO Auto-generated method stub
- return super.getRememberMeServices();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.springframework.security.web.authentication.rememberme.
- * RememberMeAuthenticationFilter
- * #onSuccessfulAuthentication(javax.servlet.http.HttpServletRequest,
- * javax.servlet.http.HttpServletResponse,
- * org.springframework.security.core.Authentication)
- */
- @Override
- protected void onSuccessfulAuthentication(HttpServletRequest request,
- HttpServletResponse response, Authentication authResult) {
- super.onSuccessfulAuthentication(request, response, authResult);
- // if (logger.isDebugEnabled()) {
- logger.info("onSuccessfulAuthentication() authResult=" + authResult);
- // }
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.springframework.security.web.authentication.rememberme.
- * RememberMeAuthenticationFilter
- * #onUnsuccessfulAuthentication(javax.servlet.http.HttpServletRequest,
- * javax.servlet.http.HttpServletResponse,
- * org.springframework.security.core.AuthenticationException)
- */
- @Override
- protected void onUnsuccessfulAuthentication(HttpServletRequest request,
- HttpServletResponse response, AuthenticationException failed) {
- logger.error("Authentication failure. failed=" + failed,
- new Throwable());
- super.onUnsuccessfulAuthentication(request, response, failed);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.springframework.security.web.authentication.rememberme.
- * RememberMeAuthenticationFilter
- * #setApplicationEventPublisher(org.springframework
- * .context.ApplicationEventPublisher)
- */
- @Override
- public void setApplicationEventPublisher(
- ApplicationEventPublisher eventPublisher) {
- // TODO Auto-generated method stub
- super.setApplicationEventPublisher(eventPublisher);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.springframework.security.web.authentication.rememberme.
- * RememberMeAuthenticationFilter
- * #setAuthenticationManager(org.springframework
- * .security.authentication.AuthenticationManager)
- */
- @Override
- public void setAuthenticationManager(
- AuthenticationManager authenticationManager) {
- // TODO Auto-generated method stub
- super.setAuthenticationManager(authenticationManager);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.springframework.security.web.authentication.rememberme.
- * RememberMeAuthenticationFilter
- * #setAuthenticationSuccessHandler(org.springframework
- * .security.web.authentication.AuthenticationSuccessHandler)
- */
- @Override
- public void setAuthenticationSuccessHandler(
- AuthenticationSuccessHandler successHandler) {
- // TODO Auto-generated method stub
- super.setAuthenticationSuccessHandler(successHandler);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.springframework.security.web.authentication.rememberme.
- * RememberMeAuthenticationFilter
- * #setRememberMeServices(org.springframework.security
- * .web.authentication.RememberMeServices)
- */
- @Override
- public void setRememberMeServices(RememberMeServices rememberMeServices) {
- // TODO Auto-generated method stub
- super.setRememberMeServices(rememberMeServices);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/security/web/filter/XASecurityContextFormationFilter.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/security/web/filter/XASecurityContextFormationFilter.java b/security-admin/src/main/java/com/xasecure/security/web/filter/XASecurityContextFormationFilter.java
deleted file mode 100644
index ea3fd7c..0000000
--- a/security-admin/src/main/java/com/xasecure/security/web/filter/XASecurityContextFormationFilter.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * 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 com.xasecure.security.web.filter;
-
-import java.io.IOException;
-
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import com.xasecure.biz.SessionMgr;
-import com.xasecure.common.GUIDUtil;
-import com.xasecure.common.HTTPUtil;
-import com.xasecure.common.PropertiesUtil;
-import com.xasecure.common.RequestContext;
-import com.xasecure.common.UserSessionBase;
-import com.xasecure.entity.XXAuthSession;
-import com.xasecure.util.RestUtil;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.authentication.AnonymousAuthenticationToken;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.context.SecurityContextHolder;
-import org.springframework.web.filter.GenericFilterBean;
-
-import com.xasecure.security.context.XAContextHolder;
-import com.xasecure.security.context.XASecurityContext;
-
-public class XASecurityContextFormationFilter extends GenericFilterBean {
-
- static Logger logger = Logger
- .getLogger(XASecurityContextFormationFilter.class);
-
- public static final String AKA_SC_SESSION_KEY = "AKA_SECURITY_CONTEXT";
- public static final String USER_AGENT = "User-Agent";
-
- @Autowired
- SessionMgr sessionMgr;
-
- @Autowired
- HTTPUtil httpUtil;
-
- String testIP = null;
-
- public XASecurityContextFormationFilter() {
- testIP = PropertiesUtil.getProperty("xa.env.ip");
- }
-
- /*
- * (non-Javadoc)
- *
- * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
- * javax.servlet.ServletResponse, javax.servlet.FilterChain)
- */
- @Override
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
-
- try {
- Authentication auth = SecurityContextHolder.getContext()
- .getAuthentication();
-
- if (auth instanceof AnonymousAuthenticationToken) {
- // ignore
- } else {
- HttpServletRequest httpRequest = (HttpServletRequest) request;
- HttpSession httpSession = httpRequest.getSession(false);
-
- // [1]get the context from session
- XASecurityContext context = (XASecurityContext) httpSession.getAttribute(AKA_SC_SESSION_KEY);
- int clientTimeOffset = 0;
- if (context == null) {
- context = new XASecurityContext();
- httpSession.setAttribute(AKA_SC_SESSION_KEY, context);
- }
- String userAgent = httpRequest.getHeader(USER_AGENT);
- if(httpRequest!=null){
- clientTimeOffset=RestUtil.getTimeOffset(httpRequest);
-
- }
- // Get the request specific info
- RequestContext requestContext = new RequestContext();
- String reqIP = testIP;
- if (testIP == null) {
- reqIP = httpRequest.getRemoteAddr();
- }
- requestContext.setIpAddress(reqIP);
- requestContext.setUserAgent(userAgent);
- requestContext.setDeviceType(httpUtil
- .getDeviceType(httpRequest));
- requestContext.setServerRequestId(GUIDUtil.genGUI());
- requestContext.setRequestURL(httpRequest.getRequestURI());
-
- requestContext.setClientTimeOffsetInMinute(clientTimeOffset);
- context.setRequestContext(requestContext);
-
- XAContextHolder.setSecurityContext(context);
-
- UserSessionBase userSession = sessionMgr.processSuccessLogin(
- XXAuthSession.AUTH_TYPE_PASSWORD, userAgent);
-
- if(userSession!=null && userSession.getClientTimeOffsetInMinute()==0){
- userSession.setClientTimeOffsetInMinute(clientTimeOffset);
- }
-
- context.setUserSession(userSession);
- }
- chain.doFilter(request, response);
-
- } finally {
- // [4]remove context from thread-local
- XAContextHolder.resetSecurityContext();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/security/web/filter/XAUsernamePasswordAuthenticationFilter.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/security/web/filter/XAUsernamePasswordAuthenticationFilter.java b/security-admin/src/main/java/com/xasecure/security/web/filter/XAUsernamePasswordAuthenticationFilter.java
deleted file mode 100644
index 4d67a33..0000000
--- a/security-admin/src/main/java/com/xasecure/security/web/filter/XAUsernamePasswordAuthenticationFilter.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * 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 com.xasecure.security.web.filter;
-
-import org.apache.log4j.Logger;
-import org.springframework.security.web.authentication.RememberMeServices;
-import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
-
-public class XAUsernamePasswordAuthenticationFilter extends
- UsernamePasswordAuthenticationFilter {
-
- static Logger logger = Logger
- .getLogger(XAUsernamePasswordAuthenticationFilter.class);
-
- /*
- * (non-Javadoc)
- *
- * @see org.springframework.security.web.authentication.
- * AbstractAuthenticationProcessingFilter
- * #setRememberMeServices(org.springframework
- * .security.web.authentication.RememberMeServices)
- */
- @Override
- public void setRememberMeServices(RememberMeServices rememberMeServices) {
- if (logger.isDebugEnabled()) {
- logger.debug("setRememberMeServices() enter: rememberMeServices="
- + rememberMeServices.toString());
- }
- super.setRememberMeServices(rememberMeServices);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/AbstractBaseResourceService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/AbstractBaseResourceService.java b/security-admin/src/main/java/com/xasecure/service/AbstractBaseResourceService.java
deleted file mode 100644
index e5ccaac..0000000
--- a/security-admin/src/main/java/com/xasecure/service/AbstractBaseResourceService.java
+++ /dev/null
@@ -1,872 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.TypeVariable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.persistence.EntityManager;
-import javax.persistence.Query;
-import javax.persistence.TypedQuery;
-import javax.persistence.criteria.CriteriaBuilder;
-import javax.persistence.criteria.CriteriaQuery;
-import javax.persistence.criteria.Expression;
-import javax.persistence.criteria.Path;
-import javax.persistence.criteria.Predicate;
-import javax.persistence.criteria.Root;
-
-import com.xasecure.biz.XABizUtil;
-import com.xasecure.common.ContextUtil;
-import com.xasecure.common.DateUtil;
-import com.xasecure.common.SortField.SORT_ORDER;
-import com.xasecure.common.UserSessionBase;
-import com.xasecure.common.XAConfigUtil;
-import com.xasecure.common.MessageEnums;
-import com.xasecure.common.RESTErrorUtil;
-import com.xasecure.common.SearchCriteria;
-import com.xasecure.common.SearchField;
-import com.xasecure.common.SearchUtil;
-import com.xasecure.common.SortField;
-import com.xasecure.common.StringUtil;
-import com.xasecure.common.db.BaseDao;
-import com.xasecure.common.view.VList;
-import com.xasecure.db.XADaoManager;
-import com.xasecure.entity.XXAuthSession;
-import com.xasecure.entity.XXDBBase;
-import com.xasecure.entity.XXPortalUser;
-import com.xasecure.view.VXDataObject;
-import com.xasecure.view.VXLong;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import com.xasecure.security.handler.XADomainObjectSecurityHandler;
-import com.xasecure.security.handler.Permission;
-
-public abstract class AbstractBaseResourceService<T extends XXDBBase, V extends VXDataObject> {
-
- public static final Logger logger = Logger
- .getLogger(AbstractBaseResourceService.class);
-
- public static final int OPERATION_CREATE_CONTEXT = 1;
- public static final int OPERATION_UPDATE_CONTEXT = 2;
-
- static HashMap<Integer, AbstractBaseResourceService<?, ?>> serviceList = new HashMap<Integer, AbstractBaseResourceService<?, ?>>();
- static List<AbstractBaseResourceService<?, ?>> preServiceList = new ArrayList<AbstractBaseResourceService<?, ?>>();
- protected Class<T> tEntityClass;
- protected Class<V> tViewClass;
-
- protected String className;
- protected String viewClassName;
- protected String countQueryStr;
- protected String queryStr;
- protected final String distinctCountQueryStr;
- protected final String distinctQueryStr;
-
- public List<SortField> sortFields = new ArrayList<SortField>();
- public List<SearchField> searchFields = new ArrayList<SearchField>();
-
- @Autowired
- XADaoManager daoManager;
-
- protected static final HashMap<Class<?>, String> tEntityValueMap = new HashMap<Class<?>, String>();
- static {
- tEntityValueMap.put(XXAuthSession.class, "Auth Session");
- tEntityValueMap.put(XXDBBase.class, "Base");
- }
-
- BaseDao<T> entityDao;
-
- @Autowired
- StringUtil stringUtil;
-
- @Autowired
- protected XADaoManager daoMgr;
-
- @Autowired
- protected SearchUtil searchUtil;
-
- @Autowired
- protected RESTErrorUtil restErrorUtil;
-
- @Autowired
- XADomainObjectSecurityHandler objectSecurityHandler;
-
- @Autowired
- XABizUtil bizUtil;
-
- @Autowired
- XAConfigUtil msConfigUtil;
-
- protected abstract void validateForCreate(V viewBaseBean);
-
- protected abstract void validateForUpdate(V viewBaseBean, T t);
-
- protected abstract T mapViewToEntityBean(V viewBean, T t,
- int OPERATION_CONTEXT);
-
- protected abstract V mapEntityToViewBean(V viewBean, T t);
-
- public static void registerService(
- AbstractBaseResourceService<?, ?> baseService) {
- preServiceList.add(baseService);
- }
-
- static public AbstractBaseResourceService<?, ?> getService(int classType) {
- AbstractBaseResourceService<?, ?> service = serviceList.get(classType);
- if (service == null) {
- for (AbstractBaseResourceService<?, ?> myService : preServiceList) {
- if (myService.getClassType() == classType) {
- serviceList.put(myService.getClassType(), myService);
- service = myService;
- break;
- }
- }
- }
-
- if (service == null) {
- logger.error("Service not found for classType=" + classType,
- new Throwable());
- }
- return service;
- }
-
- protected String getResourceName() {
-
- String resourceName = tEntityValueMap.get(tEntityClass);
- if (resourceName == null || resourceName.isEmpty()) {
- resourceName = "Object";
- }
- return resourceName;
-
- // if (className.startsWith("M")) {
- // return className.substring(1);
- // } else if (className.startsWith("com.xasecure.entity.M")){
- // return className.substring(14);
- // }
- // return className;
- }
-
- @SuppressWarnings("unchecked")
- protected BaseDao<T> getDao() {
- if (entityDao == null) {
- entityDao = (BaseDao<T>) daoMgr.getDaoForClassName(tEntityClass
- .getSimpleName());
-
- }
- return entityDao;
- }
-
- protected T createEntityObject() {
- try {
- return tEntityClass.newInstance();
- } catch (Throwable e) {
- logger.error("Error instantiating entity class. tEntityClass="
- + tEntityClass.toString(), e);
- }
- return null;
- }
-
- protected V createViewObject() {
- try {
- return tViewClass.newInstance();
- } catch (Throwable e) {
- logger.error("Error instantiating view class. tViewClass="
- + tViewClass.toString(), e);
- }
- return null;
- }
-
- protected int getClassType() {
- return bizUtil.getClassType(tEntityClass);
- }
-
- protected int ownerRatingWeight;
-
- /**
- * constructor
- */
- @SuppressWarnings("unchecked")
- public AbstractBaseResourceService() {
-
- Class klass = getClass();
- ParameterizedType genericSuperclass = (ParameterizedType) klass
- .getGenericSuperclass();
- TypeVariable<Class<?>> var[] = klass.getTypeParameters();
-
- if (genericSuperclass.getActualTypeArguments()[0] instanceof Class) {
- tEntityClass = (Class<T>) genericSuperclass
- .getActualTypeArguments()[0];
- tViewClass = (Class<V>) genericSuperclass.getActualTypeArguments()[1];
- } else if (var.length > 0) {
- tEntityClass = (Class<T>) var[0].getBounds()[0];
- tViewClass = (Class<V>) var[1].getBounds()[0];
- } else {
- logger.fatal("Cannot find class for template", new Throwable());
- }
- if (tEntityClass != null) {
- className = tEntityClass.getName();
- }
- if (tViewClass != null) {
- viewClassName = tViewClass.getName();
- }
-
- // Get total count of the rows which meet the search criteria
- countQueryStr = "SELECT COUNT(obj) FROM " + tEntityClass.getName()
- + " obj ";
- queryStr = "SELECT obj FROM " + className + " obj ";
-
- distinctCountQueryStr = "SELECT COUNT(distinct obj.id) FROM "
- + tEntityClass.getName() + " obj ";
- distinctQueryStr = "SELECT distinct obj FROM " + className + " obj ";
- sortFields.add(new SortField("id", "obj.id",true,SORT_ORDER.ASC));
- registerService(this);
- }
-
- // ----------------------------------------------------------------------------------
- // Create Operation
- // ----------------------------------------------------------------------------------
- /**
- * Create Entity object and populate it from view object. Used in create
- * operation
- */
-
- protected void mapBaseAttributesToEntityBean(T resource, V viewBean) {
- if (resource.getCreateTime() == null) {
- resource.setCreateTime(DateUtil.getUTCDate());
- }
-
- resource.setUpdateTime(DateUtil.getUTCDate());
-
- if (resource.getAddedByUserId() == null) {
- resource.setAddedByUserId(ContextUtil.getCurrentUserId());
- }
-
- resource.setUpdatedByUserId(ContextUtil.getCurrentUserId());
- }
-
- protected T populateEntityBeanForCreate(T t, V viewBaseBean) {
- mapBaseAttributesToEntityBean(t, viewBaseBean);
- return mapViewToEntityBean(viewBaseBean, t, OPERATION_CREATE_CONTEXT);
- }
-
- protected T preCreate(V viewBaseBean) {
- validateGenericAttributes(viewBaseBean);
- validateForCreate(viewBaseBean);
-
- T t = createEntityObject();
- t = populateEntityBeanForCreate(t, viewBaseBean);
- return t;
- }
-
- public V createResource(V viewBaseBean) {
- T resource = preCreate(viewBaseBean);
-
- // object security
- if (!objectSecurityHandler.hasAccess(resource,
- Permission.permissionType.CREATE)) {
- throw restErrorUtil.create403RESTException(getResourceName()
- + " access denied. classType=" + resource.getMyClassType()
- + ", className=" + resource.getClass().getName()
- + ", objectId=" + resource.getId());
- }
-
- bizUtil.updateCloneReferences(resource);
-
- resource = getDao().create(resource);
-
- V view = postCreate(resource);
- return view;
- }
-
- protected V postCreate(T resource) {
- V view = populateViewBean(resource);
- return view;
- }
-
- // ----------------------------------------------------------------------------------
- // Read Operation
- // ----------------------------------------------------------------------------------
-
- protected T preRead(Long id) {
- return null;
- }
-
- public V readResource(Long id) {
- // T resource = preRead(id);
-
- T resource = getDao().getById(id);
- if (resource == null) {
- // Returns code 400 with DATA_NOT_FOUND as the error message
- throw restErrorUtil.createRESTException(getResourceName()
- + " not found", MessageEnums.DATA_NOT_FOUND, id, null,
- "preRead: " + id + " not found.");
- }
-
- V viewBean = readResource(resource);
- return viewBean;
- }
-
- /**
- * @param resource
- * @return
- */
- @SuppressWarnings("unchecked")
- private V readResource(T resource) {
- // object security
- if (!objectSecurityHandler.hasAccess(resource,
- Permission.permissionType.READ)) {
-
- throw restErrorUtil.create403RESTException(getResourceName()
- + " access denied. classType=" + resource.getMyClassType()
- + ", className=" + resource.getClass().getName()
- + ", objectId=" + resource.getId() + ", object="
- + resource.toString());
- }
-
- V viewBean = postRead(resource);
- return viewBean;
- }
-
- protected V postRead(T resource) {
- V viewBean = populateViewBean(resource);
- return viewBean;
- }
-
- // ----------------------------------------------------------------------------------
- // Update Operation
- // ----------------------------------------------------------------------------------
-
- /**
- * Populate Entity object from view object. Used in update operation
- */
- protected T populateEntityBeanForUpdate(T t, V viewBaseBean) {
- mapBaseAttributesToEntityBean(t, viewBaseBean);
- return mapViewToEntityBean(viewBaseBean, t, OPERATION_UPDATE_CONTEXT);
- }
-
- protected T preUpdate(V viewBaseBean) {
- T resource = getDao().getById(viewBaseBean.getId());
- if (resource == null) {
- // Returns code 400 with DATA_NOT_FOUND as the error message
- throw restErrorUtil.createRESTException(getResourceName()
- + " not found", MessageEnums.DATA_NOT_FOUND,
- viewBaseBean.getId(), null, "preUpdate: id not found.");
- }
- validateForUpdate(viewBaseBean, resource);
-
- return populateEntityBeanForUpdate(resource, viewBaseBean);
- }
-
- public V updateResource(V viewBaseBean) {
- T resource = preUpdate(viewBaseBean);
-
- // object security
- if (!objectSecurityHandler.hasAccess(resource,
- Permission.permissionType.UPDATE)) {
- throw restErrorUtil.create403RESTException(getResourceName()
- + " access denied. classType=" + resource.getMyClassType()
- + ", className=" + resource.getClass().getName()
- + ", objectId=" + resource.getId());
- }
-
- resource = getDao().update(resource);
- V viewBean = postUpdate(resource);
- return viewBean;
- }
-
- protected V postUpdate(T resource) {
- V view = populateViewBean(resource);
- return view;
- }
-
- // ----------------------------------------------------------------------------------
- // Delete Operation
- // ----------------------------------------------------------------------------------
- protected T preDelete(Long id) {
- T resource = getDao().getById(id);
- if (resource == null) {
- // Return without error
- logger.info("Delete ignored for non-existent " + getResourceName()
- + " id=" + id);
- }
- return resource;
- }
-
- public boolean deleteResource(Long id) {
- boolean result = false;
- T resource = preDelete(id);
- if (resource == null) {
- throw restErrorUtil.createRESTException(getResourceName()
- + " not found", MessageEnums.DATA_NOT_FOUND, id, null,
- getResourceName() + ":" + id);
- }
-
- // object security
- if (!objectSecurityHandler.hasAccess(resource,
- Permission.permissionType.DELETE)) {
- // throw 401
- logger.debug("OBJECT SECURITY");
- }
- // Need to delete all dependent common objects like Notes and
- // UserDataPref
- bizUtil.deleteReferencedObjects(resource);
- try {
- result = getDao().remove(resource);
- } catch (Exception e) {
- logger.error("Error deleting " + getResourceName() + ". Id=" + id,
- e);
-
- throw restErrorUtil.createRESTException(getResourceName()
- + " can't be deleted",
- MessageEnums.OPER_NOT_ALLOWED_FOR_STATE, id, null, "" + id
- + ", error=" + e.getMessage());
- }
-
- postDelete(resource);
-
- return result;
- }
-
- protected void postDelete(T resource) {
-
- }
-
- // ----------------------------------------------------------------------------------
- // Validation
- // ----------------------------------------------------------------------------------
- protected void validateGenericAttributes(V viewBaseBean) {
- }
-
- // ----------------------------------------------------------------------------------
- // mapping view bean attributes
- // ----------------------------------------------------------------------------------
- public V populateViewBean(T resource) {
- V viewBean = createViewObject();
- populateViewBean(resource, viewBean);
- mapEntityToViewBean(viewBean, resource);
- return viewBean;
- }
-
- protected V populateViewBean(T resource, V viewBean) {
- mapBaseAttributesToViewBean(resource, viewBean);
- // TODO:Current:Open: Need to set original and updated
- // content
- return viewBean;
- }
-
- protected void mapBaseAttributesToViewBean(T resource, V viewBean) {
- viewBean.setId(resource.getId());
-
- // TBD: Need to review this change later
- viewBean.setMObj(resource);
- viewBean.setCreateDate(resource.getCreateTime());
- viewBean.setUpdateDate(resource.getUpdateTime());
-
- Long ownerId = resource.getAddedByUserId();
- UserSessionBase currentUserSession = ContextUtil
- .getCurrentUserSession();
-
- if (currentUserSession == null) {
- return;
- }
-
- if (ownerId != null) {
- XXPortalUser tUser = daoManager.getXXPortalUser().getById(
- resource.getAddedByUserId());
- if (tUser != null) {
- if (tUser.getPublicScreenName() != null
- && !tUser.getPublicScreenName().trim().isEmpty()
- && !tUser.getPublicScreenName().trim()
- .equalsIgnoreCase("null")) {
- viewBean.setOwner(tUser.getPublicScreenName());
- } else {
- if (tUser.getFirstName() != null
- && !tUser.getFirstName().trim().isEmpty()
- && !tUser.getFirstName().trim()
- .equalsIgnoreCase("null")) {
- if (tUser.getLastName() != null
- && !tUser.getLastName().trim().isEmpty()
- && !tUser.getLastName().trim()
- .equalsIgnoreCase("null")) {
- viewBean.setOwner(tUser.getFirstName() + " "
- + tUser.getLastName());
- } else {
- viewBean.setOwner(tUser.getFirstName());
- }
- } else {
- viewBean.setOwner(tUser.getLoginId());
- }
- }
- }
- }
- if (resource.getUpdatedByUserId() != null) {
- XXPortalUser tUser = daoManager.getXXPortalUser().getById(
- resource.getUpdatedByUserId());
- if (tUser != null) {
- if (tUser.getPublicScreenName() != null
- && !tUser.getPublicScreenName().trim().isEmpty()
- && !tUser.getPublicScreenName().trim()
- .equalsIgnoreCase("null")) {
- viewBean.setUpdatedBy(tUser.getPublicScreenName());
- } else {
- if (tUser.getFirstName() != null
- && !tUser.getFirstName().trim().isEmpty()
- && !tUser.getFirstName().trim()
- .equalsIgnoreCase("null")) {
- if (tUser.getLastName() != null
- && !tUser.getLastName().trim().isEmpty()
- && !tUser.getLastName().trim()
- .equalsIgnoreCase("null")) {
- viewBean.setUpdatedBy(tUser.getFirstName() + " "
- + tUser.getLastName());
- } else {
- viewBean.setUpdatedBy(tUser.getFirstName());
- }
- } else {
- viewBean.setUpdatedBy(tUser.getLoginId());
- }
- }
- }
- }
-
- }
-
- // ----------------------------------------------------------------------------------
- // Search Operation
- // ----------------------------------------------------------------------------------
-
- protected Query createQuery(String searchString, String sortString,
- SearchCriteria searchCriteria, List<SearchField> searchFieldList,
- boolean isCountQuery) {
-// EntityManager em = entityDao != null ? entityDao.getEntityManager() : daoManager.getEntityManager();
- EntityManager em = getDao().getEntityManager();
-
- Query query = searchUtil.createSearchQuery(em, searchString, sortString,
- searchCriteria, searchFieldList, getClassType(), false,
- isCountQuery);
- return query;
- }
-
- protected long getCountForSearchQuery(SearchCriteria searchCriteria,
- List<SearchField> searchFieldList) {
-
- String q = countQueryStr;
- // Get total count of the rows which meet the search criteria
- if (searchCriteria.isDistinct()) {
- q = distinctCountQueryStr;
- }
-
- // Get total count of the rows which meet the search criteria
- Query query = createQuery(q, null, searchCriteria, searchFieldList,
- true);
-
- // Make the database call to get the total count
- Long count = getDao().executeCountQueryInSecurityContext(tEntityClass,
- query);
- if (count == null) {
- // If no data that meets the criteria, return 0
- return 0;
- }
- return count.longValue();
- }
-
- public VXLong getSearchCount(SearchCriteria searchCriteria,
- List<SearchField> searchFieldList) {
- long count = getCountForSearchQuery(searchCriteria, searchFieldList);
-
- VXLong vXLong = new VXLong();
- vXLong.setValue(count);
- return vXLong;
- }
-
- protected List<T> searchResources(SearchCriteria searchCriteria,
- List<SearchField> searchFieldList, List<SortField> sortFieldList,
- VList vList) {
-
- // Get total count of the rows which meet the search criteria
- long count = -1;
- if (searchCriteria.isGetCount()) {
- count = getCountForSearchQuery(searchCriteria, searchFieldList);
- if (count == 0) {
- return Collections.emptyList();
- }
- }
- // construct the sort clause
- String sortClause = searchUtil.constructSortClause(searchCriteria,
- sortFieldList);
-
- String q = queryStr;
- if (searchCriteria.isDistinct()) {
- q = distinctQueryStr;
- }
- // construct the query object for retrieving the data
- Query query = createQuery(q, sortClause, searchCriteria,
- searchFieldList, false);
-
- List<T> resultList = getDao().executeQueryInSecurityContext(
- tEntityClass, query);
-
- if (vList != null) {
- // Set the meta values for the query result
- vList.setPageSize(query.getMaxResults());
- vList.setSortBy(searchCriteria.getSortBy());
- vList.setSortType(searchCriteria.getSortType());
- vList.setStartIndex(query.getFirstResult());
- vList.setTotalCount(count);
- vList.setResultSize(resultList.size());
- }
- return resultList;
- }
-
- // -------------Criteria Usage--------------------
- // -----------------------------------------------
- public VXLong getSearchCountUsingCriteria(SearchCriteria searchCriteria,
- List<SearchField> searchFieldList) {
- EntityManager em = getDao().getEntityManager();
- CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
- CriteriaQuery<Long> criteria = criteriaBuilder.createQuery(Long.class);
-
- Root<T> from = criteria.from(tEntityClass);
- Expression<Long> countExpression = criteriaBuilder
- .count(from.get("id"));
- criteria.select(countExpression);
-
- Predicate resourceConditions = buildResourceSpecificConditions(
- criteriaBuilder, from, searchCriteria);
- Predicate userConditions = buildUserConditions(
- searchCriteria.getParamList(), searchFieldList,
- criteriaBuilder, from);
-
- if (resourceConditions != null) {
- criteria.where(criteriaBuilder.and(resourceConditions,
- userConditions));
- } else {
- criteria.where(criteriaBuilder.and(userConditions));
- }
-
- TypedQuery<Long> countQuery = em.createQuery(criteria);
- long count = getDao().executeCountQueryInSecurityContext(tEntityClass,
- countQuery);
-
- VXLong vXLong = new VXLong();
- vXLong.setValue(count);
- return vXLong;
- }
-
- protected List<T> searchResourcesUsingCriteria(
- SearchCriteria searchCriteria, List<SearchField> searchFieldList,
- List<SortField> sortFieldList, VList vList) {
- // boolean filterEnabled = getDao().enableVisiblityFilters(tClass,
- // true);
-
- EntityManager em = getDao().getEntityManager();
- CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
- CriteriaQuery criteria = criteriaBuilder.createQuery();
- Root<T> from = criteria.from(tEntityClass);
-
- Predicate resourceConditions = buildResourceSpecificConditions(
- criteriaBuilder, from, searchCriteria);
- Predicate userConditions = buildUserConditions(
- searchCriteria.getParamList(), searchFieldList,
- criteriaBuilder, from);
-
- if (resourceConditions != null) {
- criteria.where(criteriaBuilder.and(resourceConditions,
- userConditions));
- } else {
- criteria.where(criteriaBuilder.and(userConditions));
- }
-
- // Get total count of the rows which meet the search criteria
- long count = -1;
- if (searchCriteria.isGetCount()) {
-
- Expression<Long> countExpression = criteriaBuilder.count(from
- .get("id"));
- criteria.select(countExpression);
- TypedQuery<Long> countQuery = em.createQuery(criteria);
- count = getDao().executeCountQueryInSecurityContext(tEntityClass,
- countQuery);
- if (count == 0) {
- return Collections.emptyList();
- }
- }
-
- // construct the sort clause
- setSortClause(searchCriteria, sortFieldList, criteriaBuilder, criteria,
- from);
-
- criteria.select(from);
- TypedQuery<T> typedQuery = em.createQuery(criteria);
- searchUtil.updateQueryPageSize(typedQuery, searchCriteria);
-
- List<T> resultList = getDao().executeQueryInSecurityContext(
- tEntityClass, typedQuery);
-
- if (vList != null) {
- // Set the meta values for the query result
- vList.setPageSize(typedQuery.getMaxResults());
- vList.setSortBy(searchCriteria.getSortBy());
- vList.setSortType(searchCriteria.getSortType());
- vList.setStartIndex(typedQuery.getFirstResult());
- vList.setTotalCount(count);
- }
-
- // if (filterEnabled) {
- // getDao().disableVisiblityFilters(tClass);
- // }
-
- return resultList;
- }
-
- protected Predicate buildUserConditions(Map<String, Object> paramList,
- List<SearchField> searchFields, CriteriaBuilder cb,
- Root<? extends XXDBBase> from) {
- Predicate userConditions = cb.conjunction();
-
- for (SearchField searchField : searchFields) {
- if (paramList.containsKey(searchField.getClientFieldName())) {
- Path<Object> tableField = null;
- String fieldName = searchField.getFieldName();
-
- // stuff to handle jpql syntax (e.g. obj.id, obj.city.city etc).
- // There has to be better way of dealing with this. Will look
- // again.
- int dotIndex = fieldName.indexOf(".");
- if (dotIndex != -1) {
- fieldName = fieldName.substring(dotIndex + 1);
- }
- dotIndex = fieldName.indexOf(".");
- if (dotIndex == -1) {
- tableField = from.get(fieldName);
- } else {
- String joinTable = fieldName.substring(0, dotIndex);
- fieldName = fieldName.substring(dotIndex + 1);
- tableField = from.join(joinTable).get(fieldName);
- }
-
- Object value = paramList.get(searchField.getClientFieldName());
- if (value == null) {
- userConditions = cb.and(userConditions,
- cb.isNull(tableField));
- continue;
- }
-
- if (searchField.getDataType() == SearchField.DATA_TYPE.INTEGER
- || searchField.getDataType() == SearchField.DATA_TYPE.BOOLEAN) {
- userConditions = cb.and(userConditions,
- cb.equal(tableField, value));
- } else if (searchField.getDataType() == SearchField.DATA_TYPE.STRING) {
- String strFieldValue = (String) value;
- Expression<String> tableFieldWithLowerExpr = cb
- .lower(tableField.as(String.class));
-
- if (searchField.getSearchType() == SearchField.SEARCH_TYPE.FULL) {
- Expression<String> literal = cb.lower(cb
- .literal(strFieldValue));
- userConditions = cb.and(userConditions,
- cb.equal(tableFieldWithLowerExpr, literal));
- } else {
- Expression<String> literal = cb.lower(cb.literal("%"
- + strFieldValue + "%"));
- userConditions = cb.and(userConditions,
- cb.like(tableFieldWithLowerExpr, literal));
- }
- } else if (searchField.getDataType() == SearchField.DATA_TYPE.INT_LIST) {
-
- @SuppressWarnings("unchecked")
- Collection<Number> intValueList = (Collection<Number>) value;
- if (intValueList.size() == 1) {
- userConditions = cb.and(userConditions,
- cb.equal(tableField, value));
- } else if (intValueList.size() > 1) {
- userConditions = cb.and(userConditions,
- tableField.in(intValueList));
- }
- }
-
- }
-
- } // for
-
- return userConditions;
- }
-
- protected Predicate buildResourceSpecificConditions(
- CriteriaBuilder criteriaBuilder, Root<T> from, SearchCriteria sc) {
- return null;
- }
-
- public void setSortClause(SearchCriteria searchCriteria,
- List<SortField> sortFields, CriteriaBuilder criteriaBuilder,
- CriteriaQuery<? extends Object> criteria, Root<? extends XXDBBase> from) {
-
- String sortBy = searchCriteria.getSortBy();
- String sortByField = null;
-
- if (!stringUtil.isEmpty(sortBy)) {
- sortBy = sortBy.trim();
- for (SortField sortField : sortFields) {
- if (sortBy.equalsIgnoreCase(sortField.getParamName())) {
- sortByField = sortField.getFieldName();
- // Override the sortBy using the normalized value
- // searchCriteria.setSortBy(sortByField);
- break;
- }
- }
- }
-
- if (sortByField == null) {
- for (SortField sortField : sortFields) {
- if (sortField.isDefault()) {
- sortByField = sortField.getFieldName();
- // Override the sortBy using the default value
- searchCriteria.setSortBy(sortField.getParamName());
- searchCriteria.setSortType(sortField.getDefaultOrder()
- .name());
- break;
- }
- }
- }
-
- if (sortByField != null) {
- int dotIndex = sortByField.indexOf(".");
- if (dotIndex != -1) {
- sortByField = sortByField.substring(dotIndex + 1);
- }
-
- // Add sort type
- String sortType = searchCriteria.getSortType();
- if (sortType != null && sortType.equalsIgnoreCase("desc")) {
- criteria.orderBy(criteriaBuilder.desc(from.get(sortByField)));
- } else {
- criteria.orderBy(criteriaBuilder.asc(from.get(sortByField)));
- }
-
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/AuthSessionService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/AuthSessionService.java b/security-admin/src/main/java/com/xasecure/service/AuthSessionService.java
deleted file mode 100644
index 63ba034..0000000
--- a/security-admin/src/main/java/com/xasecure/service/AuthSessionService.java
+++ /dev/null
@@ -1,207 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.xasecure.common.XAConstants;
-import com.xasecure.common.SearchCriteria;
-import com.xasecure.common.SearchField;
-import com.xasecure.common.SortField;
-import com.xasecure.common.StringUtil;
-import com.xasecure.common.db.BaseDao;
-import com.xasecure.entity.XXAuthSession;
-import com.xasecure.entity.XXPortalUser;
-import com.xasecure.view.VXAuthSession;
-import com.xasecure.view.VXAuthSessionList;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Service;
-
-@Service
-@Scope("singleton")
-public class AuthSessionService extends
- AbstractBaseResourceService<XXAuthSession, VXAuthSession> {
- @Autowired
- StringUtil stringUtil;
-
- public static final String NAME = "AuthSession";
-
- public static final List<SortField> AUTH_SESSION_SORT_FLDS = new ArrayList<SortField>();
- static {
- AUTH_SESSION_SORT_FLDS.add(new SortField("id", "obj.id"));
- AUTH_SESSION_SORT_FLDS.add(new SortField("authTime", "obj.authTime",
- true, SortField.SORT_ORDER.DESC));
- }
-
- public static List<SearchField> AUTH_SESSION_SEARCH_FLDS = new ArrayList<SearchField>();
- static {
- AUTH_SESSION_SEARCH_FLDS.add(SearchField.createLong("id", "obj.id"));
- AUTH_SESSION_SEARCH_FLDS.add(SearchField.createString("loginId",
- "obj.loginId", SearchField.SEARCH_TYPE.PARTIAL,
- StringUtil.VALIDATION_LOGINID));
- AUTH_SESSION_SEARCH_FLDS.add(SearchField.createLong("userId",
- "obj.userId"));
- AUTH_SESSION_SEARCH_FLDS.add(SearchField.createEnum("authStatus",
- "obj.authStatus", "statusList", XXAuthSession.AuthStatus_MAX));
- AUTH_SESSION_SEARCH_FLDS.add(SearchField.createEnum("authType",
- "obj.authType", "Authentication Type",
- XXAuthSession.AuthType_MAX));
- AUTH_SESSION_SEARCH_FLDS.add(SearchField.createEnum("deviceType",
- "obj.deviceType", "Device Type", XAConstants.DeviceType_MAX));
- AUTH_SESSION_SEARCH_FLDS.add(SearchField.createString("requestIP",
- "obj.requestIP", SearchField.SEARCH_TYPE.PARTIAL,
- StringUtil.VALIDATION_IP_ADDRESS));
- AUTH_SESSION_SEARCH_FLDS.add(SearchField.createString(
- "requestUserAgent", "obj.requestUserAgent",
- SearchField.SEARCH_TYPE.PARTIAL, null));
- AUTH_SESSION_SEARCH_FLDS.add(new SearchField("firstName",
- "obj.user.firstName", SearchField.DATA_TYPE.STRING,
- SearchField.SEARCH_TYPE.PARTIAL));
- AUTH_SESSION_SEARCH_FLDS.add(new SearchField("lastName",
- "obj.user.lastName", SearchField.DATA_TYPE.STRING,
- SearchField.SEARCH_TYPE.PARTIAL));
- AUTH_SESSION_SEARCH_FLDS.add(SearchField.createString("requestIP",
- "obj.requestIP", SearchField.SEARCH_TYPE.PARTIAL,
- StringUtil.VALIDATION_IP_ADDRESS));
- AUTH_SESSION_SEARCH_FLDS.add(new SearchField("startDate", "obj.createTime",
- SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN));
- AUTH_SESSION_SEARCH_FLDS.add(new SearchField("endDate", "obj.createTime",
- SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.LESS_EQUAL_THAN));
- }
-
- @Override
- protected String getResourceName() {
- return NAME;
- }
-
- @Override
- protected int getClassType() {
- return XAConstants.CLASS_TYPE_AUTH_SESS;
- }
-
- /*
- * (non-Javadoc)
- */
- @Override
- protected BaseDao<XXAuthSession> getDao() {
- return daoMgr.getXXAuthSession();
- }
-
- /*
- * (non-Javadoc)
- */
- @Override
- protected XXAuthSession createEntityObject() {
- return new XXAuthSession();
- }
-
- /*
- * (non-Javadoc)
- */
- @Override
- protected VXAuthSession createViewObject() {
- return new VXAuthSession();
- }
-
- /*
- * (non-Javadoc)
- */
- @Override
- protected void validateForCreate(VXAuthSession vXAuthSession) {
- logger.error("This method is not required and shouldn't be called.",
- new Throwable().fillInStackTrace());
- }
-
- /*
- * (non-Javadoc)
- */
- @Override
- protected void validateForUpdate(VXAuthSession vXAuthSession,
- XXAuthSession mObj) {
- logger.error("This method is not required and shouldn't be called.",
- new Throwable().fillInStackTrace());
- }
-
- /*
- * (non-Javadoc)
- */
- @Override
- protected XXAuthSession mapViewToEntityBean(VXAuthSession vXAuthSession,
- XXAuthSession t, int OPERATION_CONTEXT) {
- logger.error("This method is not required and shouldn't be called.",
- new Throwable().fillInStackTrace());
- return null;
- }
-
- /*
- * (non-Javadoc)
- */
- @Override
- protected VXAuthSession mapEntityToViewBean(VXAuthSession viewObj,
- XXAuthSession resource) {
- viewObj.setLoginId(resource.getLoginId());
- viewObj.setAuthTime(resource.getAuthTime());
- viewObj.setAuthStatus(resource.getAuthStatus());
- viewObj.setAuthType(resource.getAuthType());
- viewObj.setDeviceType(resource.getDeviceType());
- viewObj.setExtSessionId(resource.getExtSessionId());
- viewObj.setId(resource.getId());
- viewObj.setRequestIP(resource.getRequestIP());
-
- viewObj.setRequestUserAgent(resource.getRequestUserAgent());
-
- if (resource.getUserId() != null) {
- XXPortalUser gjUser = daoMgr.getXXPortalUser().getById(resource.getUserId());
- viewObj.setEmailAddress(gjUser.getEmailAddress());
- viewObj.setFamilyScreenName(gjUser.getEmailAddress());
- viewObj.setFirstName(gjUser.getFirstName());
- viewObj.setLastName(gjUser.getLastName());
- viewObj.setLastName(gjUser.getLastName());
- viewObj.setPublicScreenName(gjUser.getPublicScreenName());
- viewObj.setUserId(resource.getUserId());
- }
-
- return viewObj;
- }
-
- /**
- * @param searchCriteria
- * @return
- */
- public VXAuthSessionList search(SearchCriteria searchCriteria) {
- VXAuthSessionList returnList = new VXAuthSessionList();
- List<VXAuthSession> viewList = new ArrayList<VXAuthSession>();
-
- List<XXAuthSession> resultList = searchResources(searchCriteria,
- AUTH_SESSION_SEARCH_FLDS, AUTH_SESSION_SORT_FLDS, returnList);
-
- // Iterate over the result list and create the return list
- for (XXAuthSession gjObj : resultList) {
- VXAuthSession viewObj = populateViewBean(gjObj);
- viewList.add(viewObj);
- }
-
- returnList.setVXAuthSessions(viewList);
- return returnList;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/PublicAPIServiceBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/PublicAPIServiceBase.java b/security-admin/src/main/java/com/xasecure/service/PublicAPIServiceBase.java
deleted file mode 100644
index 90917c3..0000000
--- a/security-admin/src/main/java/com/xasecure/service/PublicAPIServiceBase.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-import com.xasecure.view.VXDataObject;
-
-public abstract class PublicAPIServiceBase<VXA extends VXDataObject, VX extends VXDataObject> {
-
- protected VX mapBaseAttributesToPublicObject(VXA vXAObj, VX vPublicObj) {
- vPublicObj.setId(vXAObj.getId());
- vPublicObj.setCreateDate(vXAObj.getCreateDate());
- vPublicObj.setUpdateDate(vXAObj.getUpdateDate());
- vPublicObj.setOwner(vXAObj.getOwner());
- vPublicObj.setUpdatedBy(vXAObj.getUpdatedBy());
- return vPublicObj;
- }
-
- protected VXA mapBaseAttributesToXAObject(VX vPublicObj, VXA vXAObj) {
- vXAObj.setId(vPublicObj.getId());
- vXAObj.setCreateDate(vPublicObj.getCreateDate());
- vXAObj.setUpdateDate(vPublicObj.getUpdateDate());
- vXAObj.setOwner(vPublicObj.getOwner());
- vXAObj.setUpdatedBy(vPublicObj.getUpdatedBy());
-
- return vXAObj;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/com/xasecure/service/UserService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/UserService.java b/security-admin/src/main/java/com/xasecure/service/UserService.java
deleted file mode 100644
index 462a68c..0000000
--- a/security-admin/src/main/java/com/xasecure/service/UserService.java
+++ /dev/null
@@ -1,329 +0,0 @@
-/*
- * 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 com.xasecure.service;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import com.xasecure.common.XAConstants;
-import com.xasecure.common.ContextUtil;
-import com.xasecure.common.XAConfigUtil;
-import com.xasecure.common.MessageEnums;
-import com.xasecure.common.StringUtil;
-import com.xasecure.common.UserSessionBase;
-import com.xasecure.entity.XXPortalUser;
-import com.xasecure.entity.XXPortalUserRole;
-import com.xasecure.view.VXMessage;
-import com.xasecure.view.VXResponse;
-import com.xasecure.view.VXPortalUser;
-
-import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Service;
-
-@Service
-@Scope("singleton")
-public class UserService extends UserServiceBase<XXPortalUser, VXPortalUser> {
- static Logger logger = Logger.getLogger(UserService.class);
-
- public static final String NAME = "User";
-
- @Autowired
- XAConfigUtil configUtil;
-
- private static UserService instance = null;
-
- public UserService() {
- super();
- instance = this;
- }
-
- public static UserService getInstance() {
- if (instance == null) {
- logger.error("Instance is null", new Throwable());
- }
- return instance;
- }
-
- @Override
- protected void validateForCreate(VXPortalUser userProfile) {
- List<VXMessage> messageList = new ArrayList<VXMessage>();
- if (stringUtil.isEmpty(userProfile.getEmailAddress())) {
- logger.info("Empty Email Address." + userProfile);
- messageList.add(MessageEnums.NO_INPUT_DATA.getMessage(null,
- "emailAddress"));
- }
-
- if (stringUtil.isEmpty(userProfile.getFirstName())) {
- logger.info("Empty firstName." + userProfile);
- messageList.add(MessageEnums.NO_INPUT_DATA.getMessage(null,
- "firstName"));
- }
- if (stringUtil.isEmpty(userProfile.getLastName())) {
- logger.info("Empty lastName." + userProfile);
- messageList.add(MessageEnums.NO_INPUT_DATA.getMessage(null,
- "lastName"));
- }
- // firstName
- if (!stringUtil.isValidName(userProfile.getFirstName())) {
- logger.info("Invalid first name." + userProfile);
- messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null,
- "firstName"));
- }
- userProfile.setFirstName(stringUtil.toCamelCaseAllWords(userProfile
- .getFirstName()));
-
- // lastName
- if (!stringUtil.isValidName(userProfile.getLastName())) {
- logger.info("Invalid last name." + userProfile);
- messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null,
- "lastName"));
- }
- userProfile.setLastName(stringUtil.toCamelCaseAllWords(userProfile
- .getLastName()));
-
- if (!stringUtil.validateEmail(userProfile.getEmailAddress())) {
- logger.info("Invalid email address." + userProfile);
- messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null,
- "emailAddress"));
-
- }
-
- // Normalize email. Make it lower case
- userProfile.setEmailAddress(stringUtil.normalizeEmail(userProfile
- .getEmailAddress()));
-
- // loginId
- userProfile.setLoginId(userProfile.getEmailAddress());
-
- // password
- if (!stringUtil.validatePassword(
- userProfile.getPassword(),
- new String[] { userProfile.getFirstName(),
- userProfile.getLastName() })) {
- logger.info("Invalid password." + userProfile);
- messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null,
- "password"));
- }
-
- // firstName
- if (!stringUtil.validateString(StringUtil.VALIDATION_NAME,
- userProfile.getFirstName())) {
- logger.info("Invalid first name." + userProfile);
- messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null,
- "firstName"));
- }
-
- // lastName
- if (!stringUtil.validateString(StringUtil.VALIDATION_NAME,
- userProfile.getLastName())) {
- logger.info("Invalid last name." + userProfile);
- messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null,
- "lastName"));
- }
-
- // create the public screen name
- userProfile.setPublicScreenName(userProfile.getFirstName() + " "
- + userProfile.getLastName());
-
- if (messageList.size() > 0) {
- VXResponse gjResponse = new VXResponse();
- gjResponse.setStatusCode(VXResponse.STATUS_ERROR);
- gjResponse.setMsgDesc("Validation failure");
- gjResponse.setMessageList(messageList);
- logger.info("Validation Error in createUser() userProfile="
- + userProfile + ", error=" + gjResponse);
- throw restErrorUtil.createRESTException(gjResponse);
- }
- }
-
- @Override
- protected void validateForUpdate(VXPortalUser userProfile, XXPortalUser xXPortalUser) {
- List<VXMessage> messageList = new ArrayList<VXMessage>();
-
- if (userProfile.getEmailAddress() != null
- && !userProfile.getEmailAddress().equalsIgnoreCase(
- xXPortalUser.getEmailAddress())) {
- throw restErrorUtil.createRESTException("serverMsg.userEmail",
- MessageEnums.DATA_NOT_UPDATABLE, null, "emailAddress",
- userProfile.getEmailAddress());
- }
-
- // Login Id can't be changed
- if (userProfile.getLoginId() != null
- && !xXPortalUser.getLoginId().equalsIgnoreCase(
- userProfile.getLoginId())) {
- throw restErrorUtil.createRESTException("serverMsg.userUserName",
- MessageEnums.DATA_NOT_UPDATABLE, null, "loginId",
- userProfile.getLoginId());
- }
- // }
-
- userProfile.setFirstName(restErrorUtil.validateStringForUpdate(
- userProfile.getFirstName(), xXPortalUser.getFirstName(),
- StringUtil.VALIDATION_NAME, "serverMsg.userFirstName",
- MessageEnums.INVALID_INPUT_DATA, null, "firstName"));
-
- userProfile.setFirstName(restErrorUtil.validateStringForUpdate(
- userProfile.getFirstName(), xXPortalUser.getFirstName(),
- StringUtil.VALIDATION_NAME, "serverMsg.userFirstName",
- MessageEnums.INVALID_INPUT_DATA, null, "firstName"));
-
- userProfile.setLastName(restErrorUtil.validateStringForUpdate(
- userProfile.getLastName(), xXPortalUser.getLastName(),
- StringUtil.VALIDATION_NAME, "serverMsg.userLastName",
- MessageEnums.INVALID_INPUT_DATA, null, "lastName"));
-
- // firstName
- if (!stringUtil.isValidName(userProfile.getFirstName())) {
- logger.info("Invalid first name." + userProfile);
- messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null,
- "firstName"));
- }
-
- // lastName
- if (!stringUtil.isValidName(userProfile.getLastName())) {
- logger.info("Invalid last name." + userProfile);
- messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null,
- "lastName"));
- }
-
- userProfile.setNotes(restErrorUtil.validateStringForUpdate(
- userProfile.getNotes(), xXPortalUser.getNotes(),
- StringUtil.VALIDATION_NAME, "serverMsg.userNotes",
- MessageEnums.INVALID_INPUT_DATA, null, "notes"));
-
- // validate status
- restErrorUtil.validateMinMax(userProfile.getStatus(), 0,
- XAConstants.ActivationStatus_MAX, "Invalid status", null,
- "status");
-
- // validate user roles
- if (userProfile.getUserRoleList() != null) {
- // First let's normalize it
- splitUserRoleList(userProfile.getUserRoleList());
- for (String userRole : userProfile.getUserRoleList()) {
- restErrorUtil.validateStringList(userRole,
- configUtil.getRoles(), "serverMsg.userRole", null,
- "userRoleList");
- }
-
- }
-
- // TODO: Need to see whether user can set user as internal
-
- if (messageList.size() > 0) {
- VXResponse gjResponse = new VXResponse();
- gjResponse.setStatusCode(VXResponse.STATUS_ERROR);
- gjResponse.setMsgDesc("Validation failure");
- gjResponse.setMessageList(messageList);
- logger.info("Validation Error in updateUser() userProfile="
- + userProfile + ", error=" + gjResponse);
- throw restErrorUtil.createRESTException(gjResponse);
- }
- }
-
- void splitUserRoleList(Collection<String> collection) {
- Collection<String> newCollection = new ArrayList<String>();
- for (String role : collection) {
- String roles[] = role.split(",");
- for (int i = 0; i < roles.length; i++) {
- String str = roles[i];
- newCollection.add(str);
- }
- }
- collection.clear();
- collection.addAll(newCollection);
- }
-
- @Override
- protected XXPortalUser mapViewToEntityBean(VXPortalUser userProfile, XXPortalUser mObj,
- int OPERATION_CONTEXT) {
- mObj.setEmailAddress(userProfile.getEmailAddress());
- mObj.setFirstName(userProfile.getFirstName());
- mObj.setLastName(userProfile.getLastName());
- mObj.setLoginId(userProfile.getLoginId());
- mObj.setPassword(userProfile.getPassword());
- mObj.setPublicScreenName(bizUtil.generatePublicName(userProfile, null));
- mObj.setUserSource(userProfile.getUserSource());
- return mObj;
-
- }
-
- @Override
- protected VXPortalUser mapEntityToViewBean(VXPortalUser userProfile,
- XXPortalUser user) {
- userProfile.setId(user.getId());
- userProfile.setLoginId(user.getLoginId());
- userProfile.setFirstName(user.getFirstName());
- userProfile.setLastName(user.getLastName());
- userProfile.setPublicScreenName(user.getPublicScreenName());
- userProfile.setStatus(user.getStatus());
- userProfile.setUserRoleList(new ArrayList<String>());
- String emailAddress = user.getEmailAddress();
- if (emailAddress != null && stringUtil.validateEmail(emailAddress)) {
- userProfile.setEmailAddress(user.getEmailAddress());
- }
-
- UserSessionBase sess = ContextUtil.getCurrentUserSession();
- if (sess != null) {
- userProfile.setUserSource(sess.getAuthProvider());
- }
-
- List<XXPortalUserRole> gjUserRoleList = daoMgr.getXXPortalUserRole().findByParentId(
- user.getId());
-
- for (XXPortalUserRole gjUserRole : gjUserRoleList) {
- userProfile.getUserRoleList().add(gjUserRole.getUserRole());
- }
- return userProfile;
- }
-
- // TODO: Need to remove this ASAP
- public void gjUserToUserProfile(XXPortalUser user, VXPortalUser userProfile) {
- userProfile.setId(user.getId());
- userProfile.setLoginId(user.getLoginId());
- userProfile.setFirstName(user.getFirstName());
- userProfile.setLastName(user.getLastName());
- userProfile.setPublicScreenName(user.getPublicScreenName());
- userProfile.setStatus(user.getStatus());
- userProfile.setUserRoleList(new ArrayList<String>());
- UserSessionBase sess = ContextUtil.getCurrentUserSession();
-
- String emailAddress = user.getEmailAddress();
- if (emailAddress != null && stringUtil.validateEmail(emailAddress)) {
- userProfile.setEmailAddress(user.getEmailAddress());
- }
-
- if (sess != null) {
- userProfile.setUserSource(sess.getAuthProvider());
- }
-
- List<XXPortalUserRole> gjUserRoleList = daoMgr.getXXPortalUserRole().findByParentId(
- user.getId());
-
- for (XXPortalUserRole gjUserRole : gjUserRoleList) {
- userProfile.getUserRoleList().add(gjUserRole.getUserRole());
- }
- }
-
-}
[31/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAuthorizer.java
----------------------------------------------------------------------
diff --git a/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAuthorizer.java b/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAuthorizer.java
new file mode 100644
index 0000000..d797b1a
--- /dev/null
+++ b/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAuthorizer.java
@@ -0,0 +1,849 @@
+/*
+ * 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.authorization.hive.authorizer;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.permission.FsAction;
+import org.apache.hadoop.hive.common.FileUtils;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.ql.security.HiveAuthenticationProvider;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAccessControlException;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzContext;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzPluginException;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzSessionContext;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveMetastoreClientFactory;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveOperationType;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HivePrincipal;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HivePrivilege;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HivePrivilegeObject;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HivePrivilegeObject.HivePrivObjectActionType;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HivePrivilegeObject.HivePrivilegeObjectType;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.ranger.admin.client.RangerAdminRESTClient;
+import org.apache.ranger.admin.client.datatype.GrantRevokeData;
+import org.apache.ranger.audit.model.EnumRepositoryType;
+import org.apache.ranger.audit.model.HiveAuditEvent;
+import org.apache.ranger.audit.provider.AuditProviderFactory;
+import org.apache.ranger.authorization.hadoop.config.RangerConfiguration;
+import org.apache.ranger.authorization.hadoop.constants.RangerHadoopConstants;
+import org.apache.ranger.authorization.hive.RangerHiveAccessContext;
+import org.apache.ranger.authorization.hive.RangerHiveAccessVerifier;
+import org.apache.ranger.authorization.hive.RangerHiveAccessVerifierFactory;
+import org.apache.ranger.authorization.hive.RangerHiveObjectAccessInfo;
+import org.apache.ranger.authorization.hive.RangerHiveObjectAccessInfo.HiveAccessType;
+import org.apache.ranger.authorization.hive.RangerHiveObjectAccessInfo.HiveObjectType;
+import org.apache.ranger.authorization.utils.StringUtil;
+
+public class RangerHiveAuthorizer extends RangerHiveAuthorizerBase {
+ private static final Log LOG = LogFactory.getLog(RangerHiveAuthorizer.class) ;
+
+ private static final String RangerModuleName = RangerConfiguration.getInstance().get(RangerHadoopConstants.AUDITLOG_RANGER_MODULE_ACL_NAME_PROP , RangerHadoopConstants.DEFAULT_RANGER_MODULE_ACL_NAME) ;
+ private static final String repositoryName = RangerConfiguration.getInstance().get(RangerHadoopConstants.AUDITLOG_REPOSITORY_NAME_PROP);
+ private static final boolean UpdateXaPoliciesOnGrantRevoke = RangerConfiguration.getInstance().getBoolean(RangerHadoopConstants.HIVE_UPDATE_RANGER_POLICIES_ON_GRANT_REVOKE_PROP, RangerHadoopConstants.HIVE_UPDATE_RANGER_POLICIES_ON_GRANT_REVOKE_DEFAULT_VALUE);
+
+ private RangerHiveAccessVerifier mHiveAccessVerifier = null ;
+
+
+ public RangerHiveAuthorizer(HiveMetastoreClientFactory metastoreClientFactory,
+ HiveConf hiveConf,
+ HiveAuthenticationProvider hiveAuthenticator,
+ HiveAuthzSessionContext sessionContext) {
+ super(metastoreClientFactory, hiveConf, hiveAuthenticator, sessionContext);
+
+ LOG.debug("RangerHiveAuthorizer.RangerHiveAuthorizer()");
+
+ mHiveAccessVerifier = RangerHiveAccessVerifierFactory.getInstance() ;
+
+ if(!RangerConfiguration.getInstance().isAuditInitDone()) {
+ if(sessionContext != null) {
+ AuditProviderFactory.ApplicationType appType = AuditProviderFactory.ApplicationType.Unknown;
+
+ switch(sessionContext.getClientType()) {
+ case HIVECLI:
+ appType = AuditProviderFactory.ApplicationType.HiveCLI;
+ break;
+
+ case HIVESERVER2:
+ appType = AuditProviderFactory.ApplicationType.HiveServer2;
+ break;
+ }
+
+ RangerConfiguration.getInstance().initAudit(appType);
+ }
+ }
+ }
+
+
+ /**
+ * Grant privileges for principals on the object
+ * @param hivePrincipals
+ * @param hivePrivileges
+ * @param hivePrivObject
+ * @param grantorPrincipal
+ * @param grantOption
+ * @throws HiveAuthzPluginException
+ * @throws HiveAccessControlException
+ */
+ @Override
+ public void grantPrivileges(List<HivePrincipal> hivePrincipals,
+ List<HivePrivilege> hivePrivileges,
+ HivePrivilegeObject hivePrivObject,
+ HivePrincipal grantorPrincipal,
+ boolean grantOption)
+ throws HiveAuthzPluginException, HiveAccessControlException {
+ if(! UpdateXaPoliciesOnGrantRevoke) {
+ throw new HiveAuthzPluginException("GRANT/REVOKE not supported in Argus HiveAuthorizer. Please use Argus Security Admin to setup access control.");
+ }
+
+ boolean isSuccess = false;
+ RangerHiveObjectAccessInfo objAccessInfo = getObjectAccessInfo(HiveOperationType.GRANT_PRIVILEGE, hivePrivObject, new RangerHiveAccessContext(null, getHiveAuthzSessionContext()), true);
+
+ try {
+ GrantRevokeData grData = createGrantRevokeData(objAccessInfo, hivePrincipals, hivePrivileges, getGrantorUsername(grantorPrincipal), grantOption);
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("grantPrivileges(): " + grData.toJson());
+ }
+
+ RangerAdminRESTClient xaAdmin = new RangerAdminRESTClient();
+
+ xaAdmin.grantPrivilege(grData);
+
+ isSuccess = true;
+ } catch(Exception excp) {
+ throw new HiveAccessControlException(excp);
+ } finally {
+ if(mHiveAccessVerifier.isAudited(objAccessInfo)) {
+ UserGroupInformation ugi = this.getCurrentUserGroupInfo();
+
+ // Note: failed return from REST call will be logged as 'DENIED'
+ logAuditEvent(ugi, objAccessInfo, isSuccess);
+ }
+ }
+ }
+
+ /**
+ * Revoke privileges for principals on the object
+ * @param hivePrincipals
+ * @param hivePrivileges
+ * @param hivePrivObject
+ * @param grantorPrincipal
+ * @param grantOption
+ * @throws HiveAuthzPluginException
+ * @throws HiveAccessControlException
+ */
+ @Override
+ public void revokePrivileges(List<HivePrincipal> hivePrincipals,
+ List<HivePrivilege> hivePrivileges,
+ HivePrivilegeObject hivePrivObject,
+ HivePrincipal grantorPrincipal,
+ boolean grantOption)
+ throws HiveAuthzPluginException, HiveAccessControlException {
+ if(! UpdateXaPoliciesOnGrantRevoke) {
+ throw new HiveAuthzPluginException("GRANT/REVOKE not supported in Argus HiveAuthorizer. Please use Argus Security Admin to setup access control.");
+ }
+
+ boolean isSuccess = false;
+ RangerHiveObjectAccessInfo objAccessInfo = getObjectAccessInfo(HiveOperationType.REVOKE_PRIVILEGE, hivePrivObject, new RangerHiveAccessContext(null, getHiveAuthzSessionContext()), true);
+
+ try {
+ GrantRevokeData grData = createGrantRevokeData(objAccessInfo, hivePrincipals, hivePrivileges, getGrantorUsername(grantorPrincipal), grantOption);
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("revokePrivileges(): " + grData.toJson());
+ }
+
+ RangerAdminRESTClient xaAdmin = new RangerAdminRESTClient();
+
+ xaAdmin.revokePrivilege(grData);
+
+ isSuccess = true;
+ } catch(Exception excp) {
+ throw new HiveAccessControlException(excp);
+ } finally {
+ if(mHiveAccessVerifier.isAudited(objAccessInfo)) {
+ UserGroupInformation ugi = this.getCurrentUserGroupInfo();
+
+ // Note: failed return from REST call will be logged as 'DENIED'
+ logAuditEvent(ugi, objAccessInfo, isSuccess);
+ }
+ }
+ }
+
+ /**
+ * Check if user has privileges to do this action on these objects
+ * @param hiveOpType
+ * @param inputsHObjs
+ * @param outputHObjs
+ * @param context
+ * @throws HiveAuthzPluginException
+ * @throws HiveAccessControlException
+ */
+ @Override
+ public void checkPrivileges(HiveOperationType hiveOpType,
+ List<HivePrivilegeObject> inputHObjs,
+ List<HivePrivilegeObject> outputHObjs,
+ HiveAuthzContext context)
+ throws HiveAuthzPluginException, HiveAccessControlException {
+
+ UserGroupInformation ugi = this.getCurrentUserGroupInfo();
+
+ if(ugi == null) {
+ throw new HiveAccessControlException("Permission denied: user information not available");
+ }
+
+ RangerHiveAccessContext hiveContext = this.getAccessContext(context);
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug(toString(hiveOpType, inputHObjs, outputHObjs, hiveContext));
+ }
+
+ if(hiveOpType == HiveOperationType.DFS) {
+ handleDfsCommand(hiveOpType, inputHObjs, outputHObjs, hiveContext);
+
+ return;
+ }
+
+ List<RangerHiveObjectAccessInfo> objAccessList = getObjectAccessInfo(hiveOpType, inputHObjs, outputHObjs, hiveContext);
+
+ for(RangerHiveObjectAccessInfo objAccessInfo : objAccessList) {
+ boolean ret = false;
+
+ if(objAccessInfo.getObjectType() == HiveObjectType.URI) {
+ ret = isURIAccessAllowed(ugi, objAccessInfo.getAccessType(), objAccessInfo.getUri(), getHiveConf());
+ } else if(objAccessInfo.getAccessType() != HiveAccessType.ADMIN) {
+ ret = mHiveAccessVerifier.isAccessAllowed(ugi, objAccessInfo);
+ }
+
+ if(! ret) {
+ if(mHiveAccessVerifier.isAudited(objAccessInfo)) {
+ logAuditEvent(ugi, objAccessInfo, false);
+ }
+
+ String deniedObjectName = objAccessInfo.getDeinedObjectName();
+
+ if(StringUtil.isEmpty(deniedObjectName)) {
+ deniedObjectName = objAccessInfo.getObjectName();
+ }
+
+ throw new HiveAccessControlException(String.format("Permission denied: user [%s] does not have [%s] privilege on [%s]",
+ ugi.getShortUserName(), objAccessInfo.getAccessType().name(), deniedObjectName));
+ }
+ }
+
+ // access is allowed; audit all accesses
+ for(RangerHiveObjectAccessInfo objAccessInfo : objAccessList) {
+ if(mHiveAccessVerifier.isAudited(objAccessInfo)) {
+ logAuditEvent(ugi, objAccessInfo, true);
+ }
+ }
+ }
+
+ private List<RangerHiveObjectAccessInfo> getObjectAccessInfo(HiveOperationType hiveOpType,
+ List<HivePrivilegeObject> inputsHObjs,
+ List<HivePrivilegeObject> outputHObjs,
+ RangerHiveAccessContext context) {
+ List<RangerHiveObjectAccessInfo> ret = new ArrayList<RangerHiveObjectAccessInfo>();
+
+ if(inputsHObjs != null) {
+ for(HivePrivilegeObject hiveObj : inputsHObjs) {
+ RangerHiveObjectAccessInfo hiveAccessObj = getObjectAccessInfo(hiveOpType, hiveObj, context, true);
+
+ if( hiveAccessObj != null
+ && hiveAccessObj.getAccessType() != HiveAccessType.ADMIN // access check is performed at the Argus policy server, as a part of updating the permissions
+ && !ret.contains(hiveAccessObj)) {
+ ret.add(hiveAccessObj);
+ }
+ }
+ }
+
+ if(outputHObjs != null) {
+ for(HivePrivilegeObject hiveObj : outputHObjs) {
+ RangerHiveObjectAccessInfo hiveAccessObj = getObjectAccessInfo(hiveOpType, hiveObj, context, false);
+
+ if( hiveAccessObj != null
+ && hiveAccessObj.getAccessType() != HiveAccessType.ADMIN // access check is performed at the Argus policy server, as a part of updating the permissions
+ && !ret.contains(hiveAccessObj)) {
+ ret.add(hiveAccessObj);
+ }
+ }
+ }
+
+ if(ret.size() == 0 && LOG.isDebugEnabled()) {
+ LOG.debug("getObjectAccessInfo(): no objects found for access check! " + toString(hiveOpType, inputsHObjs, outputHObjs, context));
+ }
+
+ return ret;
+ }
+
+ private RangerHiveObjectAccessInfo getObjectAccessInfo(HiveOperationType hiveOpType, HivePrivilegeObject hiveObj, RangerHiveAccessContext context, boolean isInput) {
+ RangerHiveObjectAccessInfo ret = null;
+
+ HiveObjectType objectType = getObjectType(hiveObj, hiveOpType);
+ HiveAccessType accessType = getAccessType(hiveObj, hiveOpType, isInput);
+ String operType = hiveOpType.name();
+
+ switch(objectType) {
+ case DATABASE:
+ ret = new RangerHiveObjectAccessInfo(operType, context, accessType, hiveObj.getDbname());
+ break;
+
+ case TABLE:
+ ret = new RangerHiveObjectAccessInfo(operType, context, accessType, hiveObj.getDbname(), HiveObjectType.TABLE, hiveObj.getObjectName());
+ break;
+
+ case VIEW:
+ ret = new RangerHiveObjectAccessInfo(operType, context, accessType, hiveObj.getDbname(), HiveObjectType.VIEW, hiveObj.getObjectName());
+ break;
+
+ case PARTITION:
+ ret = new RangerHiveObjectAccessInfo(operType, context, accessType, hiveObj.getDbname(), HiveObjectType.PARTITION, hiveObj.getObjectName());
+ break;
+
+ case INDEX:
+ String indexName = "?"; // TODO:
+ ret = new RangerHiveObjectAccessInfo(operType, context, accessType, hiveObj.getDbname(), hiveObj.getObjectName(), HiveObjectType.INDEX, indexName);
+ break;
+
+ case COLUMN:
+ ret = new RangerHiveObjectAccessInfo(operType, context, accessType, hiveObj.getDbname(), hiveObj.getObjectName(), hiveObj.getColumns());
+ break;
+
+ case FUNCTION:
+ ret = new RangerHiveObjectAccessInfo(operType, context, accessType, hiveObj.getDbname(), HiveObjectType.FUNCTION, hiveObj.getObjectName());
+ break;
+
+ case URI:
+ ret = new RangerHiveObjectAccessInfo(operType, context, accessType, HiveObjectType.URI, hiveObj.getObjectName());
+ break;
+
+ case NONE:
+ break;
+ }
+
+ return ret;
+ }
+
+ private HiveObjectType getObjectType(HivePrivilegeObject hiveObj, HiveOperationType hiveOpType) {
+ HiveObjectType objType = HiveObjectType.NONE;
+
+ switch(hiveObj.getType()) {
+ case DATABASE:
+ objType = HiveObjectType.DATABASE;
+ break;
+
+ case PARTITION:
+ objType = HiveObjectType.PARTITION;
+ break;
+
+ case TABLE_OR_VIEW:
+ String hiveOpTypeName = hiveOpType.name().toLowerCase();
+ if(hiveOpTypeName.contains("index")) {
+ objType = HiveObjectType.INDEX;
+ } else if(! StringUtil.isEmpty(hiveObj.getColumns())) {
+ objType = HiveObjectType.COLUMN;
+ } else if(hiveOpTypeName.contains("view")) {
+ objType = HiveObjectType.VIEW;
+ } else {
+ objType = HiveObjectType.TABLE;
+ }
+ break;
+
+ case FUNCTION:
+ objType = HiveObjectType.FUNCTION;
+ break;
+
+ case DFS_URI:
+ case LOCAL_URI:
+ objType = HiveObjectType.URI;
+ break;
+
+ case COMMAND_PARAMS:
+ case GLOBAL:
+ break;
+
+ case COLUMN:
+ // Thejas: this value is unused in Hive; the case should not be hit.
+ break;
+ }
+
+ return objType;
+ }
+
+ private HiveAccessType getAccessType(HivePrivilegeObject hiveObj, HiveOperationType hiveOpType, boolean isInput) {
+ HiveAccessType accessType = HiveAccessType.NONE;
+ HivePrivObjectActionType objectActionType = hiveObj.getActionType();
+
+ switch(objectActionType) {
+ case INSERT:
+ case INSERT_OVERWRITE:
+ case UPDATE:
+ case DELETE:
+ accessType = HiveAccessType.UPDATE;
+ break;
+ case OTHER:
+ switch(hiveOpType) {
+ case CREATEDATABASE:
+ if(hiveObj.getType() == HivePrivilegeObjectType.DATABASE) {
+ accessType = HiveAccessType.CREATE;
+ }
+ break;
+
+ case CREATEFUNCTION:
+ if(hiveObj.getType() == HivePrivilegeObjectType.FUNCTION) {
+ accessType = HiveAccessType.CREATE;
+ }
+ break;
+
+ case CREATETABLE:
+ case CREATEVIEW:
+ case CREATETABLE_AS_SELECT:
+ if(hiveObj.getType() == HivePrivilegeObjectType.TABLE_OR_VIEW) {
+ accessType = isInput ? HiveAccessType.SELECT : HiveAccessType.CREATE;
+ }
+ break;
+
+ case ALTERDATABASE:
+ case ALTERDATABASE_OWNER:
+ case ALTERINDEX_PROPS:
+ case ALTERINDEX_REBUILD:
+ case ALTERPARTITION_BUCKETNUM:
+ case ALTERPARTITION_FILEFORMAT:
+ case ALTERPARTITION_LOCATION:
+ case ALTERPARTITION_MERGEFILES:
+ case ALTERPARTITION_PROTECTMODE:
+ case ALTERPARTITION_SERDEPROPERTIES:
+ case ALTERPARTITION_SERIALIZER:
+ case ALTERTABLE_ADDCOLS:
+ case ALTERTABLE_ADDPARTS:
+ case ALTERTABLE_ARCHIVE:
+ case ALTERTABLE_BUCKETNUM:
+ case ALTERTABLE_CLUSTER_SORT:
+ case ALTERTABLE_COMPACT:
+ case ALTERTABLE_DROPPARTS:
+ case ALTERTABLE_FILEFORMAT:
+ case ALTERTABLE_LOCATION:
+ case ALTERTABLE_MERGEFILES:
+ case ALTERTABLE_PARTCOLTYPE:
+ case ALTERTABLE_PROPERTIES:
+ case ALTERTABLE_PROTECTMODE:
+ case ALTERTABLE_RENAME:
+ case ALTERTABLE_RENAMECOL:
+ case ALTERTABLE_RENAMEPART:
+ case ALTERTABLE_REPLACECOLS:
+ case ALTERTABLE_SERDEPROPERTIES:
+ case ALTERTABLE_SERIALIZER:
+ case ALTERTABLE_SKEWED:
+ case ALTERTABLE_TOUCH:
+ case ALTERTABLE_UNARCHIVE:
+ case ALTERTABLE_UPDATEPARTSTATS:
+ case ALTERTABLE_UPDATETABLESTATS:
+ case ALTERTBLPART_SKEWED_LOCATION:
+ case ALTERVIEW_AS:
+ case ALTERVIEW_PROPERTIES:
+ case ALTERVIEW_RENAME:
+ case DROPVIEW_PROPERTIES:
+ accessType = HiveAccessType.ALTER;
+ break;
+
+ case DROPFUNCTION:
+ case DROPINDEX:
+ case DROPTABLE:
+ case DROPVIEW:
+ case DROPDATABASE:
+ accessType = HiveAccessType.DROP;
+ break;
+
+ case CREATEINDEX:
+ accessType = HiveAccessType.INDEX;
+ break;
+
+ case IMPORT:
+ case EXPORT:
+ case LOAD:
+ accessType = isInput ? HiveAccessType.SELECT : HiveAccessType.UPDATE;
+ break;
+
+ case LOCKDB:
+ case LOCKTABLE:
+ case UNLOCKDB:
+ case UNLOCKTABLE:
+ accessType = HiveAccessType.LOCK;
+ break;
+
+ case QUERY:
+ case SHOW_TABLESTATUS:
+ case SHOW_CREATETABLE:
+ case SHOWCOLUMNS:
+ case SHOWINDEXES:
+ case SHOWPARTITIONS:
+ case SHOW_TBLPROPERTIES:
+ case DESCTABLE:
+ case ANALYZE_TABLE:
+ accessType = HiveAccessType.SELECT;
+ break;
+
+ case SWITCHDATABASE:
+ case DESCDATABASE:
+ accessType = HiveAccessType.USE;
+ break;
+
+ case TRUNCATETABLE:
+ accessType = HiveAccessType.UPDATE;
+ break;
+
+ case GRANT_PRIVILEGE:
+ case REVOKE_PRIVILEGE:
+ accessType = HiveAccessType.ADMIN;
+ break;
+
+ case ADD:
+ case DELETE:
+ case COMPILE:
+ case CREATEMACRO:
+ case CREATEROLE:
+ case DESCFUNCTION:
+ case DFS:
+ case DROPMACRO:
+ case DROPROLE:
+ case EXPLAIN:
+ case GRANT_ROLE:
+ case MSCK:
+ case REVOKE_ROLE:
+ case RESET:
+ case SET:
+ case SHOWCONF:
+ case SHOWDATABASES:
+ case SHOWFUNCTIONS:
+ case SHOWLOCKS:
+ case SHOWTABLES:
+ case SHOW_COMPACTIONS:
+ case SHOW_GRANT:
+ case SHOW_ROLES:
+ case SHOW_ROLE_GRANT:
+ case SHOW_ROLE_PRINCIPALS:
+ case SHOW_TRANSACTIONS:
+ break;
+ }
+ break;
+ }
+
+ return accessType;
+ }
+
+ private boolean isURIAccessAllowed(UserGroupInformation ugi, HiveAccessType accessType, String uri, HiveConf conf) {
+ boolean ret = false;
+
+ FsAction action = FsAction.NONE;
+
+ switch(accessType) {
+ case ALTER:
+ case CREATE:
+ case UPDATE:
+ case DROP:
+ case INDEX:
+ case LOCK:
+ case ADMIN:
+ case ALL:
+ action = FsAction.WRITE;
+ break;
+
+ case SELECT:
+ case USE:
+ action = FsAction.READ;
+ break;
+
+ case NONE:
+ break;
+ }
+
+ if(action == FsAction.NONE) {
+ ret = true;
+ } else {
+ try {
+ Path filePath = new Path(uri);
+ FileSystem fs = FileSystem.get(filePath.toUri(), conf);
+ Path path = FileUtils.getPathOrParentThatExists(fs, filePath);
+ FileStatus fileStatus = fs.getFileStatus(path);
+ String userName = ugi.getShortUserName();
+
+ if (FileUtils.isOwnerOfFileHierarchy(fs, fileStatus, userName)) {
+ ret = true;
+ } else {
+ ret = FileUtils.isActionPermittedForFileHierarchy(fs, fileStatus, userName, action);
+ }
+ } catch(Exception excp) {
+ LOG.error("Error getting permissions for " + uri, excp);
+ }
+ }
+
+ return ret;
+ }
+
+ private void handleDfsCommand(HiveOperationType hiveOpType,
+ List<HivePrivilegeObject> inputHObjs,
+ List<HivePrivilegeObject> outputHObjs,
+ RangerHiveAccessContext context)
+ throws HiveAuthzPluginException, HiveAccessControlException {
+
+ String dfsCommandParams = null;
+
+ if(inputHObjs != null) {
+ for(HivePrivilegeObject hiveObj : inputHObjs) {
+ if(hiveObj.getType() == HivePrivilegeObjectType.COMMAND_PARAMS) {
+ dfsCommandParams = StringUtil.toString(hiveObj.getCommandParams());
+
+ if(! StringUtil.isEmpty(dfsCommandParams)) {
+ break;
+ }
+ }
+ }
+ }
+
+ UserGroupInformation ugi = this.getCurrentUserGroupInfo();
+
+ logAuditEventForDfs(ugi, dfsCommandParams, false);
+
+ throw new HiveAccessControlException(String.format("Permission denied: user [%s] does not have privilege for [%s] command",
+ ugi.getShortUserName(), hiveOpType.name()));
+ }
+
+ private String getGrantorUsername(HivePrincipal grantorPrincipal) {
+ String grantor = grantorPrincipal != null ? grantorPrincipal.getName() : null;
+
+ if(StringUtil.isEmpty(grantor)) {
+ UserGroupInformation ugi = this.getCurrentUserGroupInfo();
+
+ grantor = ugi != null ? ugi.getShortUserName() : null;
+ }
+
+ return grantor;
+ }
+
+ private GrantRevokeData createGrantRevokeData(RangerHiveObjectAccessInfo objAccessInfo,
+ List<HivePrincipal> hivePrincipals,
+ List<HivePrivilege> hivePrivileges,
+ String grantor,
+ boolean grantOption)
+ throws HiveAccessControlException {
+ if(objAccessInfo == null ||
+ ! ( objAccessInfo.getObjectType() == HiveObjectType.DATABASE
+ || objAccessInfo.getObjectType() == HiveObjectType.TABLE
+ || objAccessInfo.getObjectType() == HiveObjectType.VIEW
+ || objAccessInfo.getObjectType() == HiveObjectType.COLUMN
+ )
+ ) {
+ throw new HiveAccessControlException("grantPrivileges(): unexpected object type '" + objAccessInfo.getObjectType().name());
+ }
+
+ String database = objAccessInfo.getDatabase();
+ String table = objAccessInfo.getObjectType() == HiveObjectType.VIEW ? objAccessInfo.getView() : objAccessInfo.getTable();
+ String columns = StringUtil.toString(objAccessInfo.getColumns());
+
+ GrantRevokeData.PermMap permMap = new GrantRevokeData.PermMap ();
+
+ for(HivePrivilege privilege : hivePrivileges) {
+ String privName = privilege.getName();
+
+ if(StringUtil.equalsIgnoreCase(privName, HiveAccessType.ALL.name())) {
+ permMap.addPerm(HiveAccessType.ALL.name());
+ } else if(StringUtil.equalsIgnoreCase(privName, HiveAccessType.ALTER.name())) {
+ permMap.addPerm(HiveAccessType.ALTER.name());
+ } else if(StringUtil.equalsIgnoreCase(privName, HiveAccessType.CREATE.name())) {
+ permMap.addPerm(HiveAccessType.CREATE.name());
+ } else if(StringUtil.equalsIgnoreCase(privName, HiveAccessType.DROP.name())) {
+ permMap.addPerm(HiveAccessType.DROP.name());
+ } else if(StringUtil.equalsIgnoreCase(privName, HiveAccessType.INDEX.name())) {
+ permMap.addPerm(HiveAccessType.INDEX.name());
+ } else if(StringUtil.equalsIgnoreCase(privName, HiveAccessType.LOCK.name())) {
+ permMap.addPerm(HiveAccessType.LOCK.name());
+ } else if(StringUtil.equalsIgnoreCase(privName, HiveAccessType.SELECT.name())) {
+ permMap.addPerm(HiveAccessType.SELECT.name());
+ } else if(StringUtil.equalsIgnoreCase(privName, HiveAccessType.UPDATE.name())) {
+ permMap.addPerm(HiveAccessType.UPDATE.name());
+ }
+ }
+
+ if(grantOption) {
+ permMap.addPerm(HiveAccessType.ADMIN.name());
+ }
+
+ for(HivePrincipal principal : hivePrincipals) {
+ switch(principal.getType()) {
+ case USER:
+ permMap.addUser(principal.getName());
+ break;
+
+ case GROUP:
+ case ROLE:
+ permMap.addGroup(principal.getName());
+ break;
+
+ default:
+ break;
+ }
+ }
+
+ GrantRevokeData grData = new GrantRevokeData();
+
+ grData.setHiveData(grantor, repositoryName, database, table, columns, permMap);
+
+ return grData;
+ }
+
+ private void logAuditEventForDfs(UserGroupInformation ugi, String dfsCommand, boolean accessGranted) {
+ HiveAuditEvent auditEvent = new HiveAuditEvent();
+
+ try {
+ auditEvent.setAclEnforcer(RangerModuleName);
+ auditEvent.setResourceType("@dfs"); // to be consistent with earlier release
+ auditEvent.setAccessType("DFS");
+ auditEvent.setAction("DFS");
+ auditEvent.setUser(ugi.getShortUserName());
+ auditEvent.setAccessResult((short)(accessGranted ? 1 : 0));
+ auditEvent.setEventTime(StringUtil.getUTCDate());
+ auditEvent.setRepositoryType(EnumRepositoryType.HIVE);
+ auditEvent.setRepositoryName(repositoryName) ;
+ auditEvent.setRequestData(dfsCommand);
+
+ auditEvent.setResourcePath(dfsCommand);
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("logAuditEvent [" + auditEvent + "] - START");
+ }
+
+ AuditProviderFactory.getAuditProvider().log(auditEvent);
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("logAuditEvent [" + auditEvent + "] - END");
+ }
+ }
+ catch(Throwable t) {
+ LOG.error("ERROR logEvent [" + auditEvent + "]", t);
+ }
+ }
+
+ private void logAuditEvent(UserGroupInformation ugi, RangerHiveObjectAccessInfo objAccessInfo, boolean accessGranted) {
+ HiveAuditEvent auditEvent = new HiveAuditEvent();
+
+ try {
+ auditEvent.setAclEnforcer(RangerModuleName);
+ auditEvent.setSessionId(objAccessInfo.getContext().getSessionString());
+ auditEvent.setResourceType("@" + StringUtil.toLower(objAccessInfo.getObjectType().name())); // to be consistent with earlier release
+ auditEvent.setAccessType(objAccessInfo.getAccessType().toString());
+ auditEvent.setAction(objAccessInfo.getOperType());
+ auditEvent.setUser(ugi.getShortUserName());
+ auditEvent.setAccessResult((short)(accessGranted ? 1 : 0));
+ auditEvent.setClientIP(objAccessInfo.getContext().getClientIpAddress());
+ auditEvent.setClientType(objAccessInfo.getContext().getClientType());
+ auditEvent.setEventTime(StringUtil.getUTCDate());
+ auditEvent.setRepositoryType(EnumRepositoryType.HIVE);
+ auditEvent.setRepositoryName(repositoryName) ;
+ auditEvent.setRequestData(objAccessInfo.getContext().getCommandString());
+
+ if(! accessGranted && !StringUtil.isEmpty(objAccessInfo.getDeinedObjectName())) {
+ auditEvent.setResourcePath(objAccessInfo.getDeinedObjectName());
+ } else {
+ auditEvent.setResourcePath(objAccessInfo.getObjectName());
+ }
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("logAuditEvent [" + auditEvent + "] - START");
+ }
+
+ AuditProviderFactory.getAuditProvider().log(auditEvent);
+
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("logAuditEvent [" + auditEvent + "] - END");
+ }
+ }
+ catch(Throwable t) {
+ LOG.error("ERROR logEvent [" + auditEvent + "]", t);
+ }
+ }
+
+ private String toString(HiveOperationType hiveOpType,
+ List<HivePrivilegeObject> inputHObjs,
+ List<HivePrivilegeObject> outputHObjs,
+ RangerHiveAccessContext context) {
+ StringBuilder sb = new StringBuilder();
+
+ sb.append("'checkPrivileges':{");
+ sb.append("'hiveOpType':").append(hiveOpType);
+
+ sb.append(", 'inputHObjs':[");
+ toString(inputHObjs, sb);
+ sb.append("]");
+
+ sb.append(", 'outputHObjs':[");
+ toString(outputHObjs, sb);
+ sb.append("]");
+
+ sb.append(", 'context':{");
+ if(context != null) {
+ sb.append("'clientType':").append(context.getClientType());
+ sb.append(", 'commandString':").append(context.getCommandString());
+ sb.append(", 'ipAddress':").append(context.getClientIpAddress());
+ sb.append(", 'sessionString':").append(context.getSessionString());
+ }
+ sb.append("}");
+
+ sb.append(", 'user':").append(this.getCurrentUserGroupInfo().getUserName());
+ sb.append(", 'groups':[").append(StringUtil.toString(this.getCurrentUserGroupInfo().getGroupNames())).append("]");
+
+ sb.append("}");
+
+ return sb.toString();
+ }
+
+ private StringBuilder toString(List<HivePrivilegeObject> privObjs, StringBuilder sb) {
+ if(privObjs != null && privObjs.size() > 0) {
+ toString(privObjs.get(0), sb);
+ for(int i = 1; i < privObjs.size(); i++) {
+ sb.append(",");
+ toString(privObjs.get(i), sb);
+ }
+ }
+
+ return sb;
+ }
+
+ private StringBuilder toString(HivePrivilegeObject privObj, StringBuilder sb) {
+ sb.append("'HivePrivilegeObject':{");
+ sb.append("'type':").append(privObj.getType().toString());
+ sb.append(", 'dbName':").append(privObj.getDbname());
+ sb.append(", 'objectType':").append(privObj.getType());
+ sb.append(", 'objectName':").append(privObj.getObjectName());
+ sb.append(", 'columns':[").append(StringUtil.toString(privObj.getColumns())).append("]");
+ sb.append(", 'partKeys':[").append(StringUtil.toString(privObj.getPartKeys())).append("]");
+ sb.append(", 'commandParams':[").append(StringUtil.toString(privObj.getCommandParams())).append("]");
+ sb.append(", 'actionType':").append(privObj.getActionType().toString());
+ sb.append("}");
+
+ return sb;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAuthorizerBase.java
----------------------------------------------------------------------
diff --git a/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAuthorizerBase.java b/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAuthorizerBase.java
new file mode 100644
index 0000000..776646d
--- /dev/null
+++ b/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAuthorizerBase.java
@@ -0,0 +1,230 @@
+/*
+ * 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.authorization.hive.authorizer;
+
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
+import org.apache.hadoop.hive.ql.security.HiveAuthenticationProvider;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.DisallowTransformHook;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAccessControlException;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthorizer;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzContext;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzPluginException;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzSessionContext;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzSessionContext.CLIENT_TYPE;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveMetastoreClientFactory;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HivePrincipal;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HivePrivilegeInfo;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HivePrivilegeObject;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveRoleGrant;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.SettableConfigUpdater;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.ranger.authorization.hive.RangerHiveAccessContext;
+import org.apache.ranger.authorization.utils.StringUtil;
+
+public abstract class RangerHiveAuthorizerBase implements HiveAuthorizer {
+
+ private static final Log LOG = LogFactory.getLog(RangerHiveAuthorizerBase.class);
+
+ private HiveMetastoreClientFactory mMetastoreClientFactory;
+ private HiveConf mHiveConf;
+ private HiveAuthenticationProvider mHiveAuthenticator;
+ private HiveAuthzSessionContext mSessionContext;
+ private UserGroupInformation mUgi;
+
+ public RangerHiveAuthorizerBase(HiveMetastoreClientFactory metastoreClientFactory,
+ HiveConf hiveConf,
+ HiveAuthenticationProvider hiveAuthenticator,
+ HiveAuthzSessionContext context) {
+ mMetastoreClientFactory = metastoreClientFactory;
+ mHiveConf = hiveConf;
+ mHiveAuthenticator = hiveAuthenticator;
+ mSessionContext = context;
+
+ String userName = mHiveAuthenticator == null ? null : mHiveAuthenticator.getUserName();
+
+ mUgi = userName == null ? null : UserGroupInformation.createRemoteUser(userName);
+
+ if(mHiveAuthenticator == null) {
+ LOG.warn("RangerHiveAuthorizerBase.RangerHiveAuthorizerBase(): hiveAuthenticator is null");
+ } else if(StringUtil.isEmpty(userName)) {
+ LOG.warn("RangerHiveAuthorizerBase.RangerHiveAuthorizerBase(): hiveAuthenticator.getUserName() returned null/empty");
+ } else if(mUgi == null) {
+ LOG.warn(String.format("RangerHiveAuthorizerBase.RangerHiveAuthorizerBase(): UserGroupInformation.createRemoteUser(%s) returned null", userName));
+ }
+ }
+
+ public HiveMetastoreClientFactory getMetastoreClientFactory() {
+ return mMetastoreClientFactory;
+ }
+
+ public HiveConf getHiveConf() {
+ return mHiveConf;
+ }
+
+ public HiveAuthenticationProvider getHiveAuthenticator() {
+ return mHiveAuthenticator;
+ }
+
+ public HiveAuthzSessionContext getHiveAuthzSessionContext() {
+ return mSessionContext;
+ }
+
+ public UserGroupInformation getCurrentUserGroupInfo() {
+ return mUgi;
+ }
+
+ public RangerHiveAccessContext getAccessContext(HiveAuthzContext context) {
+ return new RangerHiveAccessContext(context, mSessionContext);
+ }
+
+ @Override
+ public void applyAuthorizationConfigPolicy(HiveConf hiveConf) throws HiveAuthzPluginException {
+ LOG.debug("RangerHiveAuthorizerBase.applyAuthorizationConfigPolicy()");
+
+ // from SQLStdHiveAccessController.applyAuthorizationConfigPolicy()
+ if (mSessionContext != null && mSessionContext.getClientType() == CLIENT_TYPE.HIVESERVER2) {
+ // Configure PREEXECHOOKS with DisallowTransformHook to disallow transform queries
+ String hooks = hiveConf.getVar(ConfVars.PREEXECHOOKS).trim();
+ if (hooks.isEmpty()) {
+ hooks = DisallowTransformHook.class.getName();
+ } else {
+ hooks = hooks + "," + DisallowTransformHook.class.getName();
+ }
+
+ hiveConf.setVar(ConfVars.PREEXECHOOKS, hooks);
+
+ SettableConfigUpdater.setHiveConfWhiteList(hiveConf);
+ }
+ }
+
+ /**
+ * Show privileges for given principal on given object
+ * @param principal
+ * @param privObj
+ * @return
+ * @throws HiveAuthzPluginException
+ * @throws HiveAccessControlException
+ */
+ @Override
+ public List<HivePrivilegeInfo> showPrivileges(HivePrincipal principal, HivePrivilegeObject privObj)
+ throws HiveAuthzPluginException, HiveAccessControlException {
+ LOG.debug("RangerHiveAuthorizerBase.showPrivileges()");
+
+ throwNotImplementedException("showPrivileges");
+
+ return null;
+ }
+
+ @Override
+ public void createRole(String roleName, HivePrincipal adminGrantor)
+ throws HiveAuthzPluginException, HiveAccessControlException {
+ LOG.debug("RangerHiveAuthorizerBase.createRole()");
+
+ throwNotImplementedException("createRole");
+ }
+
+ @Override
+ public void dropRole(String roleName)
+ throws HiveAuthzPluginException, HiveAccessControlException {
+ LOG.debug("RangerHiveAuthorizerBase.dropRole()");
+
+ throwNotImplementedException("dropRole");
+ }
+
+ @Override
+ public List<String> getAllRoles()
+ throws HiveAuthzPluginException, HiveAccessControlException {
+ LOG.debug("RangerHiveAuthorizerBase.getAllRoles()");
+
+ throwNotImplementedException("getAllRoles");
+
+ return null;
+ }
+
+ @Override
+ public List<String> getCurrentRoleNames() throws HiveAuthzPluginException {
+ LOG.debug("RangerHiveAuthorizerBase.getCurrentRoleNames()");
+
+ throwNotImplementedException("getCurrentRoleNames");
+
+ return null;
+ }
+
+ @Override
+ public List<HiveRoleGrant> getPrincipalGrantInfoForRole(String roleName)
+ throws HiveAuthzPluginException, HiveAccessControlException {
+ LOG.debug("RangerHiveAuthorizerBase.getPrincipalGrantInfoForRole()");
+
+ throwNotImplementedException("getPrincipalGrantInfoForRole");
+
+ return null;
+ }
+
+ @Override
+ public List<HiveRoleGrant> getRoleGrantInfoForPrincipal(HivePrincipal principal)
+ throws HiveAuthzPluginException, HiveAccessControlException {
+ LOG.debug("RangerHiveAuthorizerBase.getRoleGrantInfoForPrincipal()");
+
+ throwNotImplementedException("getRoleGrantInfoForPrincipal");
+
+ return null;
+ }
+
+ @Override
+ public VERSION getVersion() {
+ return VERSION.V1;
+ }
+
+ @Override
+ public void grantRole(List<HivePrincipal> hivePrincipals, List<String> roles,
+ boolean grantOption, HivePrincipal grantorPrinc)
+ throws HiveAuthzPluginException, HiveAccessControlException {
+ LOG.debug("RangerHiveAuthorizerBase.grantRole()");
+
+ throwNotImplementedException("grantRole");
+ }
+
+ @Override
+ public void revokeRole(List<HivePrincipal> hivePrincipals, List<String> roles,
+ boolean grantOption, HivePrincipal grantorPrinc)
+ throws HiveAuthzPluginException, HiveAccessControlException {
+ LOG.debug("RangerHiveAuthorizerBase.revokeRole()");
+
+ throwNotImplementedException("revokeRole");
+ }
+
+ @Override
+ public void setCurrentRole(String roleName)
+ throws HiveAccessControlException, HiveAuthzPluginException {
+ LOG.debug("RangerHiveAuthorizerBase.setCurrentRole()");
+
+ throwNotImplementedException("setCurrentRole");
+ }
+
+ private void throwNotImplementedException(String method) throws HiveAuthzPluginException {
+ throw new HiveAuthzPluginException(method + "() not implemented in Argus HiveAuthorizer");
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAuthorizerFactory.java
----------------------------------------------------------------------
diff --git a/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAuthorizerFactory.java b/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAuthorizerFactory.java
new file mode 100644
index 0000000..bd410b7
--- /dev/null
+++ b/hive-agent/src/main/java/org/apache/ranger/authorization/hive/authorizer/RangerHiveAuthorizerFactory.java
@@ -0,0 +1,39 @@
+/*
+ * 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.authorization.hive.authorizer;
+
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.ql.security.HiveAuthenticationProvider;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthorizer;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthorizerFactory;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzPluginException;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveMetastoreClientFactory;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzSessionContext;
+
+public class RangerHiveAuthorizerFactory implements HiveAuthorizerFactory {
+ @Override
+ public HiveAuthorizer createHiveAuthorizer(HiveMetastoreClientFactory metastoreClientFactory,
+ HiveConf conf,
+ HiveAuthenticationProvider hiveAuthenticator,
+ HiveAuthzSessionContext sessionContext)
+ throws HiveAuthzPluginException {
+ return new RangerHiveAuthorizer(metastoreClientFactory, conf, hiveAuthenticator, sessionContext);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hive-agent/src/main/java/org/apache/ranger/authorization/hive/constants/RangerHiveConstants.java
----------------------------------------------------------------------
diff --git a/hive-agent/src/main/java/org/apache/ranger/authorization/hive/constants/RangerHiveConstants.java b/hive-agent/src/main/java/org/apache/ranger/authorization/hive/constants/RangerHiveConstants.java
new file mode 100644
index 0000000..711683e
--- /dev/null
+++ b/hive-agent/src/main/java/org/apache/ranger/authorization/hive/constants/RangerHiveConstants.java
@@ -0,0 +1,28 @@
+/*
+ * 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.authorization.hive.constants;
+
+public final class RangerHiveConstants {
+ public static final String WILDCARD_OBJECT = "*" ;
+ public static final String HAS_ANY_PERMISSION = "any" ;
+ public static final String SHOW_META_INFO_PERMISSION = "show" ;
+ public static final String PUBLIC_ACCESS_ROLE = "public" ;
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/knox-agent/.gitignore
----------------------------------------------------------------------
diff --git a/knox-agent/.gitignore b/knox-agent/.gitignore
index 0f63015..de3a426 100644
--- a/knox-agent/.gitignore
+++ b/knox-agent/.gitignore
@@ -1,2 +1,3 @@
/target/
/bin/
+/bin/
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/knox-agent/conf/xasecure-knox-security-changes.cfg
----------------------------------------------------------------------
diff --git a/knox-agent/conf/xasecure-knox-security-changes.cfg b/knox-agent/conf/xasecure-knox-security-changes.cfg
index c48decc..8431962 100644
--- a/knox-agent/conf/xasecure-knox-security-changes.cfg
+++ b/knox-agent/conf/xasecure-knox-security-changes.cfg
@@ -16,7 +16,7 @@
# Change the original policy parameter to work with policy manager based.
#
#
-knox.authorization.verifier.classname com.xasecure.pdp.knox.XASecureAuthorizer mod create-if-not-exists
+knox.authorization.verifier.classname org.apache.ranger.pdp.knox.RangerAuthorizer mod create-if-not-exists
xasecure.knox.policymgr.url %POLICY_MGR_URL%/service/assets/policyList/%REPOSITORY_NAME% mod create-if-not-exists
xasecure.knox.policymgr.url.saveAsFile /tmp/knox%REPOSITORY_NAME%_json mod create-if-not-exists
xasecure.knox.policymgr.url.reloadIntervalInMillis 30000 mod create-if-not-exists
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/knox-agent/conf/xasecure-knox-security.xml
----------------------------------------------------------------------
diff --git a/knox-agent/conf/xasecure-knox-security.xml b/knox-agent/conf/xasecure-knox-security.xml
index 0307b42..61aa245 100644
--- a/knox-agent/conf/xasecure-knox-security.xml
+++ b/knox-agent/conf/xasecure-knox-security.xml
@@ -22,7 +22,7 @@
<!-- The following property is used to select appropriate XASecure Authorizer Module (filebased, policymanager based) -->
<property>
<name>knox.authorization.verifier.classname</name>
- <value>com.xasecure.pdp.knox.XASecureAuthorizer</value>
+ <value>org.apache.ranger.pdp.knox.RangerAuthorizer</value>
<description>
Class Name of the authorization Module
</description>
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/knox-agent/scripts/install.sh
----------------------------------------------------------------------
diff --git a/knox-agent/scripts/install.sh b/knox-agent/scripts/install.sh
index 6150fba..903ef44 100644
--- a/knox-agent/scripts/install.sh
+++ b/knox-agent/scripts/install.sh
@@ -21,7 +21,7 @@ function create_jceks()
alias=$1
pass=$2
jceksFile=$3
- java -cp "${install_dir}/cred/lib/*" com.hortonworks.credentialapi.buildks create ${alias} -value ${pass} -provider jceks://file${jceksFile}
+ java -cp "${install_dir}/cred/lib/*" org.apache.ranger.credentialapi.buildks create ${alias} -value ${pass} -provider jceks://file${jceksFile}
}
#Update Properties to File
@@ -211,7 +211,7 @@ do
if [ $? -eq 0 ]
then
cp="${install_dir}/cred/lib/*:${install_dir}/installer/lib/*:/usr/lib/hadoop/*:/usr/lib/hadoop/lib/*"
- java -cp "${cp}" com.xasecure.utils.install.XmlConfigChanger -i ${archivefn} -o ${newfn} -c ${f} ${PROP_ARGS}
+ java -cp "${cp}" org.apache.ranger.utils.install.XmlConfigChanger -i ${archivefn} -o ${newfn} -c ${f} ${PROP_ARGS}
if [ $? -eq 0 ]
then
diff -w ${newfn} ${fullpathorgfn} > /dev/null 2>&1
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/knox-agent/src/main/java/com/xasecure/authorization/knox/KnoxAccessVerifier.java
----------------------------------------------------------------------
diff --git a/knox-agent/src/main/java/com/xasecure/authorization/knox/KnoxAccessVerifier.java b/knox-agent/src/main/java/com/xasecure/authorization/knox/KnoxAccessVerifier.java
deleted file mode 100644
index 91f2b90..0000000
--- a/knox-agent/src/main/java/com/xasecure/authorization/knox/KnoxAccessVerifier.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/**
- * 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 com.xasecure.authorization.knox;
-
-import java.util.Set;
-
-public interface KnoxAccessVerifier {
-
-
- public boolean isAccessAllowed(String topologyName, String serviceName, String accessTypes, String userName, Set<String> groups, String requestIp) ;
-
- public boolean isAuditEnabled(String topologyName, String serviceName) ;
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/knox-agent/src/main/java/com/xasecure/authorization/knox/KnoxAccessVerifierFactory.java
----------------------------------------------------------------------
diff --git a/knox-agent/src/main/java/com/xasecure/authorization/knox/KnoxAccessVerifierFactory.java b/knox-agent/src/main/java/com/xasecure/authorization/knox/KnoxAccessVerifierFactory.java
deleted file mode 100644
index 112d94b..0000000
--- a/knox-agent/src/main/java/com/xasecure/authorization/knox/KnoxAccessVerifierFactory.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/**
- * 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 com.xasecure.authorization.knox;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import com.xasecure.authorization.hadoop.config.XaSecureConfiguration;
-import com.xasecure.authorization.hadoop.constants.XaSecureHadoopConstants;
-
-public class KnoxAccessVerifierFactory {
-
- private static final Log LOG = LogFactory.getLog(KnoxAccessVerifierFactory.class) ;
-
- private static KnoxAccessVerifier knoxAccessVerififer = null ;
-
- public static KnoxAccessVerifier getInstance() {
- if (knoxAccessVerififer == null) {
- synchronized(KnoxAccessVerifierFactory.class) {
- KnoxAccessVerifier temp = knoxAccessVerififer ;
- if (temp == null) {
- String knoxAccessVerifierClassName = XaSecureConfiguration.getInstance().get(XaSecureHadoopConstants.KNOX_ACCESS_VERIFIER_CLASS_NAME_PROP, XaSecureHadoopConstants.KNOX_ACCESS_VERIFIER_CLASS_NAME_DEFAULT_VALUE ) ;
-
- if (knoxAccessVerifierClassName != null) {
- LOG.info("Knox Access Verification class [" + knoxAccessVerifierClassName + "] - Being build");
- try {
- knoxAccessVerififer = (KnoxAccessVerifier) (Class.forName(knoxAccessVerifierClassName).newInstance()) ;
- LOG.info("Created a new instance of class: [" + knoxAccessVerifierClassName + "] for Knox Access verification.");
- } catch (InstantiationException e) {
- LOG.error("Unable to create KnoxAccess Verifier: [" + knoxAccessVerifierClassName + "]", e);
- } catch (IllegalAccessException e) {
- LOG.error("Unable to create KnoxAccess Verifier: [" + knoxAccessVerifierClassName + "]", e);
- } catch (ClassNotFoundException e) {
- LOG.error("Unable to create KnoxAccess Verifier: [" + knoxAccessVerifierClassName + "]", e);
- } catch (Throwable t) {
- LOG.error("Unable to create KnoxAccess Verifier: [" + knoxAccessVerifierClassName + "]", t);
- }
- finally {
- LOG.info("Created a new instance of class: [" + knoxAccessVerifierClassName + "] for Knox Access verification. (" + knoxAccessVerififer + ")");
- }
- }
- }
- else {
- LOG.error("Unable to obtain knoxAccessVerifier [" + XaSecureHadoopConstants.KNOX_ACCESS_VERIFIER_CLASS_NAME_PROP + "]");
- }
- }
- }
- return knoxAccessVerififer ;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/knox-agent/src/main/java/org/apache/ranger/authorization/knox/KnoxAccessVerifier.java
----------------------------------------------------------------------
diff --git a/knox-agent/src/main/java/org/apache/ranger/authorization/knox/KnoxAccessVerifier.java b/knox-agent/src/main/java/org/apache/ranger/authorization/knox/KnoxAccessVerifier.java
new file mode 100644
index 0000000..89265cb
--- /dev/null
+++ b/knox-agent/src/main/java/org/apache/ranger/authorization/knox/KnoxAccessVerifier.java
@@ -0,0 +1,30 @@
+/**
+ * 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.authorization.knox;
+
+import java.util.Set;
+
+public interface KnoxAccessVerifier {
+
+
+ public boolean isAccessAllowed(String topologyName, String serviceName, String accessTypes, String userName, Set<String> groups, String requestIp) ;
+
+ public boolean isAuditEnabled(String topologyName, String serviceName) ;
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/knox-agent/src/main/java/org/apache/ranger/authorization/knox/KnoxAccessVerifierFactory.java
----------------------------------------------------------------------
diff --git a/knox-agent/src/main/java/org/apache/ranger/authorization/knox/KnoxAccessVerifierFactory.java b/knox-agent/src/main/java/org/apache/ranger/authorization/knox/KnoxAccessVerifierFactory.java
new file mode 100644
index 0000000..25e1e28
--- /dev/null
+++ b/knox-agent/src/main/java/org/apache/ranger/authorization/knox/KnoxAccessVerifierFactory.java
@@ -0,0 +1,65 @@
+/**
+ * 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.authorization.knox;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.authorization.hadoop.config.RangerConfiguration;
+import org.apache.ranger.authorization.hadoop.constants.RangerHadoopConstants;
+
+public class KnoxAccessVerifierFactory {
+
+ private static final Log LOG = LogFactory.getLog(KnoxAccessVerifierFactory.class) ;
+
+ private static KnoxAccessVerifier knoxAccessVerififer = null ;
+
+ public static KnoxAccessVerifier getInstance() {
+ if (knoxAccessVerififer == null) {
+ synchronized(KnoxAccessVerifierFactory.class) {
+ KnoxAccessVerifier temp = knoxAccessVerififer ;
+ if (temp == null) {
+ String knoxAccessVerifierClassName = RangerConfiguration.getInstance().get(RangerHadoopConstants.KNOX_ACCESS_VERIFIER_CLASS_NAME_PROP, RangerHadoopConstants.KNOX_ACCESS_VERIFIER_CLASS_NAME_DEFAULT_VALUE ) ;
+
+ if (knoxAccessVerifierClassName != null) {
+ LOG.info("Knox Access Verification class [" + knoxAccessVerifierClassName + "] - Being build");
+ try {
+ knoxAccessVerififer = (KnoxAccessVerifier) (Class.forName(knoxAccessVerifierClassName).newInstance()) ;
+ LOG.info("Created a new instance of class: [" + knoxAccessVerifierClassName + "] for Knox Access verification.");
+ } catch (InstantiationException e) {
+ LOG.error("Unable to create KnoxAccess Verifier: [" + knoxAccessVerifierClassName + "]", e);
+ } catch (IllegalAccessException e) {
+ LOG.error("Unable to create KnoxAccess Verifier: [" + knoxAccessVerifierClassName + "]", e);
+ } catch (ClassNotFoundException e) {
+ LOG.error("Unable to create KnoxAccess Verifier: [" + knoxAccessVerifierClassName + "]", e);
+ } catch (Throwable t) {
+ LOG.error("Unable to create KnoxAccess Verifier: [" + knoxAccessVerifierClassName + "]", t);
+ }
+ finally {
+ LOG.info("Created a new instance of class: [" + knoxAccessVerifierClassName + "] for Knox Access verification. (" + knoxAccessVerififer + ")");
+ }
+ }
+ }
+ else {
+ LOG.error("Unable to obtain knoxAccessVerifier [" + RangerHadoopConstants.KNOX_ACCESS_VERIFIER_CLASS_NAME_PROP + "]");
+ }
+ }
+ }
+ return knoxAccessVerififer ;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/com/xasecure/hadoop/client/HadoopFS.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/com/xasecure/hadoop/client/HadoopFS.java b/lookup-client/src/main/java/com/xasecure/hadoop/client/HadoopFS.java
deleted file mode 100644
index 57de18a..0000000
--- a/lookup-client/src/main/java/com/xasecure/hadoop/client/HadoopFS.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * 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 com.xasecure.hadoop.client;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.net.UnknownHostException;
-import java.security.PrivilegedAction;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-import javax.security.auth.Subject;
-
-import org.apache.commons.io.FilenameUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.FileStatus;
-import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.security.UserGroupInformation;
-
-import com.xasecure.hadoop.client.config.BaseClient;
-import com.xasecure.hadoop.client.exceptions.HadoopException;
-
-public class HadoopFS extends BaseClient {
-
- private static final Log LOG = LogFactory.getLog(HadoopFS.class) ;
-
- public HadoopFS(String dataSource) {
- super(dataSource) ;
- }
-
- public HadoopFS(String dataSource, HashMap<String,String> connectionProperties) {
- super(dataSource,connectionProperties) ;
- }
-
- private List<String> listFilesInternal(String baseDir, String fileMatching) {
- List<String> fileList = new ArrayList<String>() ;
- ClassLoader prevCl = Thread.currentThread().getContextClassLoader() ;
- String errMsg = " You can still save the repository and start creating "
- + "policies, but you would not be able to use autocomplete for "
- + "resource names. Check xa_portal.log for more info.";
- try {
- Thread.currentThread().setContextClassLoader(getConfigHolder().getClassLoader());
- String dirPrefix = (baseDir.endsWith("/") ? baseDir : (baseDir + "/")) ;
- String filterRegEx = null;
- if (fileMatching != null && fileMatching.trim().length() > 0) {
- filterRegEx = fileMatching.trim() ;
- }
-
- Configuration conf = new Configuration() ;
- UserGroupInformation.setConfiguration(conf);
-
- FileSystem fs = null ;
- try {
- fs = FileSystem.get(conf) ;
-
- FileStatus[] fileStats = fs.listStatus(new Path(baseDir)) ;
- if (fileStats != null) {
- for(FileStatus stat : fileStats) {
- Path path = stat.getPath() ;
- String pathComponent = path.getName() ;
- if (filterRegEx == null) {
- fileList.add(dirPrefix + pathComponent) ;
- }
- else if (FilenameUtils.wildcardMatch(pathComponent, fileMatching)) {
- fileList.add(dirPrefix + pathComponent) ;
- }
- }
- }
- } catch (UnknownHostException uhe) {
- String msgDesc = "listFilesInternal: Unable to connect using given config parameters"
- + " of Hadoop environment [" + getDataSource() + "].";
- HadoopException hdpException = new HadoopException(msgDesc, uhe);
- hdpException.generateResponseDataMap(false, getMessage(uhe),
- msgDesc + errMsg, null, null);
- throw hdpException;
- } catch (FileNotFoundException fne) {
- String msgDesc = "listFilesInternal: Unable to locate files using given config parameters "
- + "of Hadoop environment [" + getDataSource() + "].";
- HadoopException hdpException = new HadoopException(msgDesc, fne);
- hdpException.generateResponseDataMap(false, getMessage(fne),
- msgDesc + errMsg, null, null);
- throw hdpException;
- }
- finally {
- }
- } catch (IOException ioe) {
- String msgDesc = "listFilesInternal: Unable to get listing of files for directory "
- + baseDir
- + "] from Hadoop environment ["
- + getDataSource()
- + "].";
- HadoopException hdpException = new HadoopException(msgDesc, ioe);
- hdpException.generateResponseDataMap(false, getMessage(ioe),
- msgDesc + errMsg, null, null);
- throw hdpException;
-
- } catch (IllegalArgumentException iae) {
- String msgDesc = "Unable to get listing of files for directory ["
- + baseDir + "] from Hadoop environment [" + getDataSource()
- + "].";
- HadoopException hdpException = new HadoopException(msgDesc, iae);
- hdpException.generateResponseDataMap(false, getMessage(iae),
- msgDesc + errMsg, null, null);
- throw hdpException;
- }
- finally {
- Thread.currentThread().setContextClassLoader(prevCl);
- }
- return fileList ;
- }
-
-
- public List<String> listFiles(final String baseDir, final String fileMatching) {
-
- PrivilegedAction<List<String>> action = new PrivilegedAction<List<String>>() {
- @Override
- public List<String> run() {
- return listFilesInternal(baseDir, fileMatching) ;
- }
-
- };
- return Subject.doAs(getLoginSubject(),action) ;
- }
-
- public static final void main(String[] args) {
-
- if (args.length < 2) {
- System.err.println("USAGE: java " + HadoopFS.class.getName() + " repositoryName basedirectory [filenameToMatch]") ;
- System.exit(1) ;
- }
-
- String repositoryName = args[0] ;
- String baseDir = args[1] ;
- String fileNameToMatch = (args.length == 2 ? null : args[2]) ;
-
- HadoopFS fs = new HadoopFS(repositoryName) ;
- List<String> fsList = fs.listFiles(baseDir, fileNameToMatch) ;
- if (fsList != null && fsList.size() > 0) {
- for(String s : fsList) {
- System.out.println(s) ;
- }
- }
- else {
- System.err.println("Unable to get file listing for [" + baseDir + (baseDir.endsWith("/") ? "" : "/") + fileNameToMatch + "] in repository [" + repositoryName + "]") ;
- }
- }
-
- public static HashMap<String, Object> testConnection(String dataSource,
- HashMap<String, String> connectionProperties) {
-
- HashMap<String, Object> responseData = new HashMap<String, Object>();
- boolean connectivityStatus = false;
- HadoopFS connectionObj = new HadoopFS(dataSource, connectionProperties);
- if (connectionObj != null) {
- List<String> testResult = connectionObj.listFiles("/", null);
- if (testResult != null && testResult.size() != 0) {
- connectivityStatus = true;
- }
- }
- if (connectivityStatus) {
- String successMsg = "TestConnection Successful";
- generateResponseDataMap(connectivityStatus, successMsg, successMsg,
- null, null, responseData);
- } else {
- String failureMsg = "Unable to retrieve any files using given parameters, "
- + "You can still save the repository and start creating policies, "
- + "but you would not be able to use autocomplete for resource names. "
- + "Check xa_portal.log for more info.";
- generateResponseDataMap(connectivityStatus, failureMsg, failureMsg,
- null, null, responseData);
- }
- return responseData;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/com/xasecure/hadoop/client/HadoopFSTester.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/com/xasecure/hadoop/client/HadoopFSTester.java b/lookup-client/src/main/java/com/xasecure/hadoop/client/HadoopFSTester.java
deleted file mode 100644
index 13ba146..0000000
--- a/lookup-client/src/main/java/com/xasecure/hadoop/client/HadoopFSTester.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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 com.xasecure.hadoop.client;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Properties;
-
-public class HadoopFSTester {
-
- public static void main(String[] args) throws Throwable {
- if (args.length < 3) {
- System.err.println("USAGE: java " + HadoopFS.class.getName() + " repositoryName propertyFile basedirectory [filenameToMatch]") ;
- System.exit(1) ;
- }
-
- String repositoryName = args[0] ;
- String propFile = args[1] ;
- String baseDir = args[2] ;
- String fileNameToMatch = (args.length == 3 ? null : args[3]) ;
-
- Properties conf = new Properties() ;
- conf.load(HadoopFSTester.class.getClassLoader().getResourceAsStream(propFile));
-
- HashMap<String,String> prop = new HashMap<String,String>() ;
- for(Object key : conf.keySet()) {
- Object val = conf.get(key) ;
- prop.put((String)key, (String)val) ;
- }
-
- HadoopFS fs = new HadoopFS(repositoryName, prop) ;
- List<String> fsList = fs.listFiles(baseDir, fileNameToMatch) ;
- if (fsList != null && fsList.size() > 0) {
- for(String s : fsList) {
- System.out.println(s) ;
- }
- }
- else {
- System.err.println("Unable to get file listing for [" + baseDir + (baseDir.endsWith("/") ? "" : "/") + fileNameToMatch + "] in repository [" + repositoryName + "]") ;
- }
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/com/xasecure/hadoop/client/config/BaseClient.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/com/xasecure/hadoop/client/config/BaseClient.java b/lookup-client/src/main/java/com/xasecure/hadoop/client/config/BaseClient.java
deleted file mode 100644
index 17acdf7..0000000
--- a/lookup-client/src/main/java/com/xasecure/hadoop/client/config/BaseClient.java
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * 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 com.xasecure.hadoop.client.config;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-import javax.security.auth.Subject;
-
-import org.apache.commons.lang.StringUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.security.SecureClientLogin;
-
-import com.xasecure.hadoop.client.HadoopFS;
-import com.xasecure.hadoop.client.exceptions.HadoopException;
-
-public abstract class BaseClient {
- private static final Log LOG = LogFactory.getLog(HadoopFS.class) ;
-
- private String dataSource ;
- private Subject loginSubject ;
- private HadoopConfigHolder configHolder;
-
- protected HashMap<String,String> connectionProperties ;
-
- public BaseClient(String dataSource) {
- this.dataSource = dataSource ;
- init() ;
- login() ;
- }
-
- public BaseClient(String dataSource, HashMap<String,String> connectionProperties) {
- this.dataSource = dataSource ;
- this.connectionProperties = connectionProperties ;
- init() ;
- login() ;
- }
-
-
- private void init() {
- if (connectionProperties == null) {
- configHolder = HadoopConfigHolder.getInstance(dataSource) ;
- }
- else {
- configHolder = HadoopConfigHolder.getInstance(dataSource,connectionProperties) ;
- }
- }
-
-
- protected void login() {
- ClassLoader prevCl = Thread.currentThread().getContextClassLoader() ;
- String errMsg = " You can still save the repository and start creating "
- + "policies, but you would not be able to use autocomplete for "
- + "resource names. Check xa_portal.log for more info.";
- try {
- Thread.currentThread().setContextClassLoader(configHolder.getClassLoader());
- String userName = configHolder.getUserName() ;
- if (userName == null) {
- String msgDesc = "Unable to find login username for hadoop environment, ["
- + dataSource + "]";
- HadoopException hdpException = new HadoopException(msgDesc);
- hdpException.generateResponseDataMap(false, msgDesc, msgDesc + errMsg,
- null, null);
-
- throw hdpException;
- }
- String keyTabFile = configHolder.getKeyTabFile() ;
- if (keyTabFile != null) {
- if ( configHolder.isKerberosAuthentication() ) {
- LOG.info("Init Login: security enabled, using username/keytab");
- loginSubject = SecureClientLogin.loginUserFromKeytab(userName, keyTabFile) ;
- }
- else {
- LOG.info("Init Login: using username");
- loginSubject = SecureClientLogin.login(userName) ;
- }
- }
- else {
- String password = configHolder.getPassword() ;
- if ( configHolder.isKerberosAuthentication() ) {
- LOG.info("Init Login: using username/password");
- loginSubject = SecureClientLogin.loginUserWithPassword(userName, password) ;
- }
- else {
- LOG.info("Init Login: security not enabled, using username");
- loginSubject = SecureClientLogin.login(userName) ;
- }
- }
- } catch (IOException ioe) {
- String msgDesc = "Unable to login to Hadoop environment ["
- + dataSource + "]";
-
- HadoopException hdpException = new HadoopException(msgDesc, ioe);
- hdpException.generateResponseDataMap(false, getMessage(ioe),
- msgDesc + errMsg, null, null);
- throw hdpException;
- } catch (SecurityException se) {
- String msgDesc = "Unable to login to Hadoop environment ["
- + dataSource + "]";
- HadoopException hdpException = new HadoopException(msgDesc, se);
- hdpException.generateResponseDataMap(false, getMessage(se),
- msgDesc + errMsg, null, null);
- throw hdpException;
- } finally {
- Thread.currentThread().setContextClassLoader(prevCl);
- }
- }
-
- public String getDataSource() {
- return dataSource ;
- }
-
- protected Subject getLoginSubject() {
- return loginSubject;
- }
-
- protected HadoopConfigHolder getConfigHolder() {
- return configHolder;
- }
-
- public static void generateResponseDataMap(boolean connectivityStatus,
- String message, String description, Long objectId,
- String fieldName, HashMap<String, Object> responseData) {
- responseData.put("connectivityStatus", connectivityStatus);
- responseData.put("message", message);
- responseData.put("description", description);
- responseData.put("objectId", objectId);
- responseData.put("fieldName", fieldName);
- }
-
- public static String getMessage(Throwable excp) {
- List<String> errList = new ArrayList<String>();
- while (excp != null) {
- if (!errList.contains(excp.getMessage() + ". \n")) {
- if (excp.getMessage() != null && !(excp.getMessage().equalsIgnoreCase(""))) {
- errList.add(excp.getMessage() + ". \n");
- }
- }
- excp = excp.getCause();
- }
- return StringUtils.join(errList, "");
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/lookup-client/src/main/java/com/xasecure/hadoop/client/config/HadoopClassLoader.java
----------------------------------------------------------------------
diff --git a/lookup-client/src/main/java/com/xasecure/hadoop/client/config/HadoopClassLoader.java b/lookup-client/src/main/java/com/xasecure/hadoop/client/config/HadoopClassLoader.java
deleted file mode 100644
index 214ff4d..0000000
--- a/lookup-client/src/main/java/com/xasecure/hadoop/client/config/HadoopClassLoader.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * 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 com.xasecure.hadoop.client.config;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.net.URL;
-import java.util.Properties;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import com.xasecure.hadoop.client.exceptions.HadoopException;
-
-public class HadoopClassLoader extends ClassLoader {
-
- private static final Log LOG = LogFactory.getLog(HadoopClassLoader.class) ;
-
- private HadoopConfigHolder confHolder ;
-
- public HadoopClassLoader(HadoopConfigHolder confHolder) {
- super(Thread.currentThread().getContextClassLoader()) ;
- this.confHolder = confHolder;
- }
-
-
- @Override
- protected URL findResource(String resourceName) {
- LOG.debug("findResource(" + resourceName + ") is called.") ;
- URL ret = null;
-
- if (confHolder.hasResourceExists(resourceName)) {
- ret = buildResourceFile(resourceName) ;
- }
- else {
- ret = super.findResource(resourceName);
- }
- LOG.debug("findResource(" + resourceName + ") is returning [" + ret + "]") ;
- return ret ;
- }
-
-
- @SuppressWarnings("deprecation")
- private URL buildResourceFile(String aResourceName) {
- URL ret = null ;
- String prefix = aResourceName ;
- String suffix = ".txt" ;
-
- Properties prop = confHolder.getProperties(aResourceName) ;
- LOG.debug("Building XML for: " + prop.toString());
- if (prop != null && prop.size() > 0) {
- if (aResourceName.contains(".")) {
- int lastDotFound = aResourceName.indexOf(".") ;
- prefix = aResourceName.substring(0,lastDotFound) + "-" ;
- suffix = aResourceName.substring(lastDotFound) ;
- }
-
- try {
- File tempFile = File.createTempFile(prefix, suffix) ;
- tempFile.deleteOnExit();
- PrintWriter out = new PrintWriter(new FileWriter(tempFile)) ;
- out.println("<?xml version=\"1.0\"?>") ;
- out.println("<?xml-stylesheet type=\"text/xsl\" href=\"configuration.xsl\"?>") ;
- out.println("<configuration xmlns:xi=\"http://www.w3.org/2001/XInclude\">") ;
- for(Object keyobj : prop.keySet()) {
- String key = (String)keyobj;
- String val = prop.getProperty(key) ;
- if (HadoopConfigHolder.HADOOP_RPC_PROTECTION.equals(key) && (val == null || val.trim().isEmpty())) {
- continue;
- }
- out.println("<property><name>" + key.trim() + "</name><value>" + val + "</value></property>") ;
- }
- out.println("</configuration>") ;
- out.close() ;
- ret = tempFile.toURL() ;
- } catch (IOException e) {
- throw new HadoopException("Unable to load create hadoop configuration file [" + aResourceName + "]", e) ;
- }
-
- }
-
- return ret ;
-
- }
-
-
-}
[36/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/credentialbuilder/src/test/java/org/apache/ranger/credentialapi/Testbuildks.java
----------------------------------------------------------------------
diff --git a/credentialbuilder/src/test/java/org/apache/ranger/credentialapi/Testbuildks.java b/credentialbuilder/src/test/java/org/apache/ranger/credentialapi/Testbuildks.java
new file mode 100644
index 0000000..fe94745
--- /dev/null
+++ b/credentialbuilder/src/test/java/org/apache/ranger/credentialapi/Testbuildks.java
@@ -0,0 +1,79 @@
+/**
+ * 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.credentialapi;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import org.apache.ranger.credentialapi.buildks;
+import org.junit.Test;
+
+public class Testbuildks {
+ private final String keystoreFile =System.getProperty("user.home")+"/testkeystore.jceks";
+ @Test
+ public void testBuildKSsuccess() throws Exception {
+ buildks buildksOBJ=new buildks();
+ String[] argsCreateCommand = {"create", "TestCredential1", "-value", "PassworD123", "-provider", "jceks://file" + keystoreFile};
+ int rc1=buildksOBJ.createCredential(argsCreateCommand);
+ assertEquals( 0, rc1);
+ assertTrue(rc1==0);
+
+ String[] argsListCommand = {"list", "-provider","jceks://file" + keystoreFile};
+ int rc2=buildksOBJ.listCredential(argsListCommand);
+ assertEquals(0, rc2);
+ assertTrue(rc2==0);
+
+ String[] argsGetCommand = {"get", "TestCredential1", "-provider", "jceks://file" +keystoreFile };
+ String pw=buildksOBJ.getCredential(argsGetCommand);
+ assertEquals("PassworD123", pw);
+ assertTrue(pw.equals("PassworD123"));
+ boolean getCredentialPassed = pw.equals("PassworD123");
+
+ String[] argsDeleteCommand = {"delete", "TestCredential1", "-provider", "jceks://file" +keystoreFile };
+ int rc3=buildksOBJ.deleteCredential(argsDeleteCommand);
+ assertEquals(0, rc3);
+ assertTrue(rc3==0);
+
+ if(rc1==rc2 && rc2==rc3 && rc3==0 && getCredentialPassed){
+ System.out.println("Test Case has been completed successfully..");
+ }
+ }
+
+ @Test
+ public void testInvalidProvider() throws Exception {
+ buildks buildksOBJ=new buildks();
+ String[] argsCreateCommand = {"create", "TestCredential1", "-value", "PassworD123", "-provider", "jksp://file"+keystoreFile};
+ int rc1=buildksOBJ.createCredential(argsCreateCommand);
+ assertEquals(-1, rc1);
+ assertTrue(rc1==-1);
+ }
+
+ @Test
+ public void testInvalidCommand() throws Exception {
+ buildks buildksOBJ=new buildks();
+ String[] argsCreateCommand = {"creat", "TestCredential1", "-value", "PassworD123", "-provider", "jksp://file"+keystoreFile};
+ int rc1=buildksOBJ.createCredential(argsCreateCommand);
+ assertEquals(-1, rc1);
+ assertTrue(rc1==-1);
+ }
+ /*public static void main(String args[]) throws Exception{
+ Testbuildks tTestbuildks=new Testbuildks();
+ tTestbuildks.testBuildKSsuccess();
+ }*/
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/embededwebserver/scripts/start-ranger-admin.sh
----------------------------------------------------------------------
diff --git a/embededwebserver/scripts/start-ranger-admin.sh b/embededwebserver/scripts/start-ranger-admin.sh
index b560794..756bba7 100755
--- a/embededwebserver/scripts/start-ranger-admin.sh
+++ b/embededwebserver/scripts/start-ranger-admin.sh
@@ -45,5 +45,5 @@ if [ ! -d logs ]
then
mkdir logs
fi
-java -Dproc_rangeradmin ${JAVA_OPTS} -Dcatalina.base=${XAPOLICYMGR_EWS_DIR} -cp "${XAPOLICYMGR_EWS_DIR}/webapp/WEB-INF/classes/conf:${XAPOLICYMGR_EWS_DIR}/lib/*:${RANGER_JAAS_LIB_DIR}/*:${RANGER_JAAS_CONF_DIR}:${JAVA_HOME}/lib/*" com.xasecure.server.tomcat.EmbededServer > logs/catalina.out 2>&1 &
+java -Dproc_rangeradmin ${JAVA_OPTS} -Dcatalina.base=${XAPOLICYMGR_EWS_DIR} -cp "${XAPOLICYMGR_EWS_DIR}/webapp/WEB-INF/classes/conf:${XAPOLICYMGR_EWS_DIR}/lib/*:${RANGER_JAAS_LIB_DIR}/*:${RANGER_JAAS_CONF_DIR}:${JAVA_HOME}/lib/*" org.apache.ranger.server.tomcat.EmbededServer > logs/catalina.out 2>&1 &
echo "Apache Ranger Admin has started"
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/embededwebserver/scripts/stop-ranger-admin.sh
----------------------------------------------------------------------
diff --git a/embededwebserver/scripts/stop-ranger-admin.sh b/embededwebserver/scripts/stop-ranger-admin.sh
index 9fb9f04..57363a9 100755
--- a/embededwebserver/scripts/stop-ranger-admin.sh
+++ b/embededwebserver/scripts/stop-ranger-admin.sh
@@ -44,5 +44,5 @@ if [ ! -d logs ]
then
mkdir logs
fi
-java ${JAVA_OPTS} -Dcatalina.base=${XAPOLICYMGR_EWS_DIR} -cp "${XAPOLICYMGR_EWS_DIR}/webapp/WEB-INF/classes/conf:${XAPOLICYMGR_EWS_DIR}/lib/*:${RANGER_JAAS_LIB_DIR}/*:${RANGER_JAAS_CONF_DIR}" com.xasecure.server.tomcat.StopEmbededServer > logs/catalina.out 2>&1
+java ${JAVA_OPTS} -Dcatalina.base=${XAPOLICYMGR_EWS_DIR} -cp "${XAPOLICYMGR_EWS_DIR}/webapp/WEB-INF/classes/conf:${XAPOLICYMGR_EWS_DIR}/lib/*:${RANGER_JAAS_LIB_DIR}/*:${RANGER_JAAS_CONF_DIR}" org.apache.ranger.server.tomcat.StopEmbededServer > logs/catalina.out 2>&1
echo "Apache Ranger Admin has been stopped."
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/embededwebserver/src/main/java/com/xasecure/server/tomcat/EmbededServer.java
----------------------------------------------------------------------
diff --git a/embededwebserver/src/main/java/com/xasecure/server/tomcat/EmbededServer.java b/embededwebserver/src/main/java/com/xasecure/server/tomcat/EmbededServer.java
deleted file mode 100644
index 9298a45..0000000
--- a/embededwebserver/src/main/java/com/xasecure/server/tomcat/EmbededServer.java
+++ /dev/null
@@ -1,240 +0,0 @@
-/*
- * 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 com.xasecure.server.tomcat;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.Properties;
-import java.util.logging.Logger;
-
-import javax.servlet.ServletException;
-
-import org.apache.catalina.Context;
-import org.apache.catalina.LifecycleException;
-import org.apache.catalina.connector.Connector;
-import org.apache.catalina.startup.Tomcat;
-import org.apache.catalina.valves.AccessLogValve;
-
-public class EmbededServer {
-
- private static final Logger LOG = Logger.getLogger(EmbededServer.class.getName()) ;
-
- private static final String DEFAULT_CONFIG_FILENAME = "ranger_webserver.properties" ;
-
- private static String configFile = DEFAULT_CONFIG_FILENAME ;
-
- private Properties serverConfigProperties = new Properties() ;
-
- public static void main(String[] args) {
- new EmbededServer(args).start() ;
- }
-
-
- public EmbededServer(String[] args) {
- if (args.length > 0) {
- configFile = args[0] ;
- }
- initConfig() ;
- }
-
-
- private void initConfig() {
-
- String cfgFile = getResourceFileName(configFile) ;
-
- serverConfigProperties.clear() ;
-
- InputStream in = null ;
- try {
-
- in = new FileInputStream(cfgFile) ;
- serverConfigProperties.load(in);
- }
- catch(FileNotFoundException fnf) {
- LOG.severe("Unable to find config file [" + cfgFile + "]");
- fnf.printStackTrace();
- }
- catch(IOException ioe) {
- LOG.severe("Unable to load config file [" + cfgFile + "]");
- ioe.printStackTrace();
- }
- serverConfigProperties.list(System.out);
- }
-
- public static int DEFAULT_SHUTDOWN_PORT = 6185 ;
- public static String DEFAULT_SHUTDOWN_COMMAND = "SHUTDOWN" ;
-
-
- public void start() {
- Tomcat server = new Tomcat();
-
- String hostName = getConfig("service.host") ;
- int serverPort = getIntConfig("http.service.port", 6181) ;
- int sslPort = getIntConfig("https.service.port",-1) ;
- int shutdownPort = getIntConfig("service.shutdownPort", DEFAULT_SHUTDOWN_PORT ) ;
- String shutdownCommand = getConfig("service.shutdownCommand", DEFAULT_SHUTDOWN_COMMAND ) ;
-
- server.setHostname(hostName);
- server.setPort(serverPort);
- server.getServer().setPort(shutdownPort);
- server.getServer().setShutdown(shutdownCommand);
-
- if (sslPort > 0) {
- Connector ssl = new Connector() ;
- ssl.setPort(sslPort) ;
- ssl.setSecure(true);
- ssl.setScheme("https") ;
- ssl.setAttribute("SSLEnabled", getConfig("https.attrib.SSLEnabled", "true"));
- ssl.setAttribute("sslProtocol", getConfig("https.attrib.sslProtocol", "TLS")) ;
- ssl.setAttribute("clientAuth", getConfig("https.attrib.clientAuth", "false"));
- ssl.setAttribute("keyAlias", getConfig("https.attrib.keyAlias") ) ;
- ssl.setAttribute("keystorePass", getConfig("https.attrib.keystorePass"));
- ssl.setAttribute("keystoreFile", getConfig("https.attrib.keystoreFile")) ;
-
- String enabledProtocols = "SSLv2Hello, TLSv1, TLSv1.1, TLSv1.2" ;
- ssl.setAttribute("sslEnabledProtocols", enabledProtocols ) ;
-
- server.getService().addConnector(ssl);
- }
-
-
- File baseDir = new File(".") ;
-
- File logDirectory = new File(baseDir, "logs") ;
- if (! logDirectory.exists()) {
- logDirectory.mkdirs() ;
- }
-
- AccessLogValve valve = new AccessLogValve() ;
- valve.setRotatable(true) ;
- valve.setAsyncSupported(true);
- valve.setBuffered(false);
- valve.setEnabled(true);
- valve.setFileDateFormat(getConfig("accesslog.dateformat","yyyy-MM-dd.HH")) ;
- valve.setDirectory(logDirectory.getAbsolutePath());
- valve.setRotatable(true);
- valve.setSuffix(".log");
-
- String logPattern = getConfig("accesslog.pattern", "%h %l %u %t \"%r\" %s %b") ;
- valve.setPattern(logPattern);
-
- server.getHost().getPipeline().addValve(valve);
-
- try {
- String webapp_dir= getConfig("xa.webapp.dir");
- if( webapp_dir == null || webapp_dir.trim().isEmpty()) {
- //If webapp location property is not set, then let's dervice from catalina_base
- String catalina_base = getConfig("catalina.base");
- if( catalina_base == null || catalina_base.trim().isEmpty()) {
- LOG.severe("Tomcat Server failed to start: catalina.base and/or xa.webapp.dir is not set") ;
- System.exit(1);
- }
- webapp_dir = catalina_base + File.separator + "webapp";
- LOG.info("Deriving webapp folder from catalina.base property. folder=" + webapp_dir);
- }
- LOG.info("Webapp folder=" + webapp_dir);
- Context webappCtx = server.addWebapp("/", new File(webapp_dir).getAbsolutePath()) ;
- webappCtx.init() ;
- } catch (ServletException e1) {
- LOG.severe("Tomcat Server failed to add webapp:" + e1.toString()) ;
- e1.printStackTrace();
- } catch(LifecycleException lce) {
- LOG.severe("Tomcat Server failed to start webapp:" + lce.toString()) ;
- lce.printStackTrace();
- }
-
- try {
- server.start();
- server.getServer().await();
- } catch (LifecycleException e) {
- LOG.severe("Tomcat Server failed to start:" + e.toString()) ;
- e.printStackTrace();
- }
- }
-
-
- protected String getConfig(String key) {
- String value = serverConfigProperties.getProperty(key) ;
- if ( value == null || value.trim().isEmpty()) {
- //Value not found in properties file, let's try to get from System's property
- value = System.getProperty(key);
- }
- return value;
- }
-
- protected String getConfig(String key, String defaultValue) {
- String ret = getConfig(key) ;
- if (key == null) {
- ret = defaultValue ;
- }
- return ret;
- }
-
- protected int getIntConfig(String key, int defaultValue) {
- int ret = 0 ;
- String retStr = getConfig(key) ;
- if (retStr == null) {
- ret = defaultValue ;
- }
- else {
- ret = Integer.parseInt(retStr) ;
- }
- return ret;
- }
-
- private String getResourceFileName(String aResourceName) {
-
- String ret = aResourceName ;
-
- ClassLoader cl = getClass().getClassLoader() ;
-
- for (String path : new String[] { aResourceName, "/" + aResourceName }) {
-
- try {
- URL lurl = cl.getResource(path) ;
-
- if (lurl != null) {
- ret = lurl.getFile() ;
- }
- }
- catch(Throwable t) {
- ret = null;
- }
- if (ret != null) {
- break ;
- }
-
- }
-
- if (ret == null) {
- ret = aResourceName ;
- }
-
- return ret ;
-
-
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/embededwebserver/src/main/java/com/xasecure/server/tomcat/StopEmbededServer.java
----------------------------------------------------------------------
diff --git a/embededwebserver/src/main/java/com/xasecure/server/tomcat/StopEmbededServer.java b/embededwebserver/src/main/java/com/xasecure/server/tomcat/StopEmbededServer.java
deleted file mode 100644
index 0ec2541..0000000
--- a/embededwebserver/src/main/java/com/xasecure/server/tomcat/StopEmbededServer.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * 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 com.xasecure.server.tomcat;
-
-import java.io.PrintWriter;
-import java.net.Socket;
-
-public class StopEmbededServer extends EmbededServer {
-
- private static final String SHUTDOWN_HOSTNAME = "localhost" ;
-
- public static void main(String[] args) {
- new StopEmbededServer(args).stop();
- }
-
- public StopEmbededServer(String[] args) {
- super(args);
- }
-
- public void stop() {
-
- try {
-
- int shutdownPort = getIntConfig("service.shutdownPort", DEFAULT_SHUTDOWN_PORT ) ;
-
- String shutdownCommand = getConfig("service.shutdownCommand", DEFAULT_SHUTDOWN_COMMAND ) ;
-
- Socket sock = new Socket(SHUTDOWN_HOSTNAME,shutdownPort) ;
-
- PrintWriter out = new PrintWriter(sock.getOutputStream(), true) ;
-
- out.println(shutdownCommand) ;
-
- out.flush();
-
- out.close();
- }
- catch(Throwable t) {
- System.err.println("Server could not be shutdown due to exception:" + t) ;
- System.exit(1);
- }
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/embededwebserver/src/main/java/org/apache/ranger/server/tomcat/EmbededServer.java
----------------------------------------------------------------------
diff --git a/embededwebserver/src/main/java/org/apache/ranger/server/tomcat/EmbededServer.java b/embededwebserver/src/main/java/org/apache/ranger/server/tomcat/EmbededServer.java
new file mode 100644
index 0000000..6025235
--- /dev/null
+++ b/embededwebserver/src/main/java/org/apache/ranger/server/tomcat/EmbededServer.java
@@ -0,0 +1,240 @@
+/*
+ * 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.server.tomcat;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.Properties;
+import java.util.logging.Logger;
+
+import javax.servlet.ServletException;
+
+import org.apache.catalina.Context;
+import org.apache.catalina.LifecycleException;
+import org.apache.catalina.connector.Connector;
+import org.apache.catalina.startup.Tomcat;
+import org.apache.catalina.valves.AccessLogValve;
+
+public class EmbededServer {
+
+ private static final Logger LOG = Logger.getLogger(EmbededServer.class.getName()) ;
+
+ private static final String DEFAULT_CONFIG_FILENAME = "ranger_webserver.properties" ;
+
+ private static String configFile = DEFAULT_CONFIG_FILENAME ;
+
+ private Properties serverConfigProperties = new Properties() ;
+
+ public static void main(String[] args) {
+ new EmbededServer(args).start() ;
+ }
+
+
+ public EmbededServer(String[] args) {
+ if (args.length > 0) {
+ configFile = args[0] ;
+ }
+ initConfig() ;
+ }
+
+
+ private void initConfig() {
+
+ String cfgFile = getResourceFileName(configFile) ;
+
+ serverConfigProperties.clear() ;
+
+ InputStream in = null ;
+ try {
+
+ in = new FileInputStream(cfgFile) ;
+ serverConfigProperties.load(in);
+ }
+ catch(FileNotFoundException fnf) {
+ LOG.severe("Unable to find config file [" + cfgFile + "]");
+ fnf.printStackTrace();
+ }
+ catch(IOException ioe) {
+ LOG.severe("Unable to load config file [" + cfgFile + "]");
+ ioe.printStackTrace();
+ }
+ serverConfigProperties.list(System.out);
+ }
+
+ public static int DEFAULT_SHUTDOWN_PORT = 6185 ;
+ public static String DEFAULT_SHUTDOWN_COMMAND = "SHUTDOWN" ;
+
+
+ public void start() {
+ Tomcat server = new Tomcat();
+
+ String hostName = getConfig("service.host") ;
+ int serverPort = getIntConfig("http.service.port", 6181) ;
+ int sslPort = getIntConfig("https.service.port",-1) ;
+ int shutdownPort = getIntConfig("service.shutdownPort", DEFAULT_SHUTDOWN_PORT ) ;
+ String shutdownCommand = getConfig("service.shutdownCommand", DEFAULT_SHUTDOWN_COMMAND ) ;
+
+ server.setHostname(hostName);
+ server.setPort(serverPort);
+ server.getServer().setPort(shutdownPort);
+ server.getServer().setShutdown(shutdownCommand);
+
+ if (sslPort > 0) {
+ Connector ssl = new Connector() ;
+ ssl.setPort(sslPort) ;
+ ssl.setSecure(true);
+ ssl.setScheme("https") ;
+ ssl.setAttribute("SSLEnabled", getConfig("https.attrib.SSLEnabled", "true"));
+ ssl.setAttribute("sslProtocol", getConfig("https.attrib.sslProtocol", "TLS")) ;
+ ssl.setAttribute("clientAuth", getConfig("https.attrib.clientAuth", "false"));
+ ssl.setAttribute("keyAlias", getConfig("https.attrib.keyAlias") ) ;
+ ssl.setAttribute("keystorePass", getConfig("https.attrib.keystorePass"));
+ ssl.setAttribute("keystoreFile", getConfig("https.attrib.keystoreFile")) ;
+
+ String enabledProtocols = "SSLv2Hello, TLSv1, TLSv1.1, TLSv1.2" ;
+ ssl.setAttribute("sslEnabledProtocols", enabledProtocols ) ;
+
+ server.getService().addConnector(ssl);
+ }
+
+
+ File baseDir = new File(".") ;
+
+ File logDirectory = new File(baseDir, "logs") ;
+ if (! logDirectory.exists()) {
+ logDirectory.mkdirs() ;
+ }
+
+ AccessLogValve valve = new AccessLogValve() ;
+ valve.setRotatable(true) ;
+ valve.setAsyncSupported(true);
+ valve.setBuffered(false);
+ valve.setEnabled(true);
+ valve.setFileDateFormat(getConfig("accesslog.dateformat","yyyy-MM-dd.HH")) ;
+ valve.setDirectory(logDirectory.getAbsolutePath());
+ valve.setRotatable(true);
+ valve.setSuffix(".log");
+
+ String logPattern = getConfig("accesslog.pattern", "%h %l %u %t \"%r\" %s %b") ;
+ valve.setPattern(logPattern);
+
+ server.getHost().getPipeline().addValve(valve);
+
+ try {
+ String webapp_dir= getConfig("xa.webapp.dir");
+ if( webapp_dir == null || webapp_dir.trim().isEmpty()) {
+ //If webapp location property is not set, then let's dervice from catalina_base
+ String catalina_base = getConfig("catalina.base");
+ if( catalina_base == null || catalina_base.trim().isEmpty()) {
+ LOG.severe("Tomcat Server failed to start: catalina.base and/or xa.webapp.dir is not set") ;
+ System.exit(1);
+ }
+ webapp_dir = catalina_base + File.separator + "webapp";
+ LOG.info("Deriving webapp folder from catalina.base property. folder=" + webapp_dir);
+ }
+ LOG.info("Webapp folder=" + webapp_dir);
+ Context webappCtx = server.addWebapp("/", new File(webapp_dir).getAbsolutePath()) ;
+ webappCtx.init() ;
+ } catch (ServletException e1) {
+ LOG.severe("Tomcat Server failed to add webapp:" + e1.toString()) ;
+ e1.printStackTrace();
+ } catch(LifecycleException lce) {
+ LOG.severe("Tomcat Server failed to start webapp:" + lce.toString()) ;
+ lce.printStackTrace();
+ }
+
+ try {
+ server.start();
+ server.getServer().await();
+ } catch (LifecycleException e) {
+ LOG.severe("Tomcat Server failed to start:" + e.toString()) ;
+ e.printStackTrace();
+ }
+ }
+
+
+ protected String getConfig(String key) {
+ String value = serverConfigProperties.getProperty(key) ;
+ if ( value == null || value.trim().isEmpty()) {
+ //Value not found in properties file, let's try to get from System's property
+ value = System.getProperty(key);
+ }
+ return value;
+ }
+
+ protected String getConfig(String key, String defaultValue) {
+ String ret = getConfig(key) ;
+ if (key == null) {
+ ret = defaultValue ;
+ }
+ return ret;
+ }
+
+ protected int getIntConfig(String key, int defaultValue) {
+ int ret = 0 ;
+ String retStr = getConfig(key) ;
+ if (retStr == null) {
+ ret = defaultValue ;
+ }
+ else {
+ ret = Integer.parseInt(retStr) ;
+ }
+ return ret;
+ }
+
+ private String getResourceFileName(String aResourceName) {
+
+ String ret = aResourceName ;
+
+ ClassLoader cl = getClass().getClassLoader() ;
+
+ for (String path : new String[] { aResourceName, "/" + aResourceName }) {
+
+ try {
+ URL lurl = cl.getResource(path) ;
+
+ if (lurl != null) {
+ ret = lurl.getFile() ;
+ }
+ }
+ catch(Throwable t) {
+ ret = null;
+ }
+ if (ret != null) {
+ break ;
+ }
+
+ }
+
+ if (ret == null) {
+ ret = aResourceName ;
+ }
+
+ return ret ;
+
+
+
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/embededwebserver/src/main/java/org/apache/ranger/server/tomcat/StopEmbededServer.java
----------------------------------------------------------------------
diff --git a/embededwebserver/src/main/java/org/apache/ranger/server/tomcat/StopEmbededServer.java b/embededwebserver/src/main/java/org/apache/ranger/server/tomcat/StopEmbededServer.java
new file mode 100644
index 0000000..d0c0b3b
--- /dev/null
+++ b/embededwebserver/src/main/java/org/apache/ranger/server/tomcat/StopEmbededServer.java
@@ -0,0 +1,62 @@
+/*
+ * 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.server.tomcat;
+
+import java.io.PrintWriter;
+import java.net.Socket;
+
+public class StopEmbededServer extends EmbededServer {
+
+ private static final String SHUTDOWN_HOSTNAME = "localhost" ;
+
+ public static void main(String[] args) {
+ new StopEmbededServer(args).stop();
+ }
+
+ public StopEmbededServer(String[] args) {
+ super(args);
+ }
+
+ public void stop() {
+
+ try {
+
+ int shutdownPort = getIntConfig("service.shutdownPort", DEFAULT_SHUTDOWN_PORT ) ;
+
+ String shutdownCommand = getConfig("service.shutdownCommand", DEFAULT_SHUTDOWN_COMMAND ) ;
+
+ Socket sock = new Socket(SHUTDOWN_HOSTNAME,shutdownPort) ;
+
+ PrintWriter out = new PrintWriter(sock.getOutputStream(), true) ;
+
+ out.println(shutdownCommand) ;
+
+ out.flush();
+
+ out.close();
+ }
+ catch(Throwable t) {
+ System.err.println("Server could not be shutdown due to exception:" + t) ;
+ System.exit(1);
+ }
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hbase-agent/.settings/org.eclipse.core.resources.prefs
----------------------------------------------------------------------
diff --git a/hbase-agent/.settings/org.eclipse.core.resources.prefs b/hbase-agent/.settings/org.eclipse.core.resources.prefs
index e9441bb..f9fe345 100644
--- a/hbase-agent/.settings/org.eclipse.core.resources.prefs
+++ b/hbase-agent/.settings/org.eclipse.core.resources.prefs
@@ -1,3 +1,4 @@
eclipse.preferences.version=1
encoding//src/main/java=UTF-8
+encoding//src/test/java=UTF-8
encoding/<project>=UTF-8
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hbase-agent/conf/hbase-site-changes.cfg
----------------------------------------------------------------------
diff --git a/hbase-agent/conf/hbase-site-changes.cfg b/hbase-agent/conf/hbase-site-changes.cfg
index ca1f68a..9b15375 100644
--- a/hbase-agent/conf/hbase-site-changes.cfg
+++ b/hbase-agent/conf/hbase-site-changes.cfg
@@ -16,7 +16,7 @@
hbase.security.authorization true mod create-if-not-exists
hbase.coprocessor.master.classes org.apache.hadoop.hbase.security.access.AccessController delval - ,
hbase.coprocessor.region.classes org.apache.hadoop.hbase.security.access.AccessController delval - ,
-hbase.coprocessor.master.classes com.xasecure.authorization.hbase.XaSecureAuthorizationCoprocessor append create-if-not-exists ,
-hbase.coprocessor.region.classes com.xasecure.authorization.hbase.XaSecureAuthorizationCoprocessor append create-if-not-exists ,
+hbase.coprocessor.master.classes org.apache.ranger.authorization.hbase.RangerAuthorizationCoprocessor append create-if-not-exists ,
+hbase.coprocessor.region.classes org.apache.ranger.authorization.hbase.RangerAuthorizationCoprocessor append create-if-not-exists ,
hbase.rpc.protection PRIVACY mod create-if-not-exists
hbase.rpc.engine org.apache.hadoop.hbase.ipc.SecureRpcEngine mod create-if-not-exists
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hbase-agent/conf/xasecure-hbase-security-changes.cfg
----------------------------------------------------------------------
diff --git a/hbase-agent/conf/xasecure-hbase-security-changes.cfg b/hbase-agent/conf/xasecure-hbase-security-changes.cfg
index 2400218..dc3ec1a 100644
--- a/hbase-agent/conf/xasecure-hbase-security-changes.cfg
+++ b/hbase-agent/conf/xasecure-hbase-security-changes.cfg
@@ -16,7 +16,7 @@
# Change the original policy parameter to work with policy manager based.
#
#
-hbase.authorization.verifier.classname com.xasecure.pdp.hbase.XASecureAuthorizer mod create-if-not-exists
+hbase.authorization.verifier.classname org.apache.ranger.pdp.hbase.RangerAuthorizer mod create-if-not-exists
xasecure.hbase.policymgr.url %POLICY_MGR_URL%/service/assets/policyList/%REPOSITORY_NAME% mod create-if-not-exists
xasecure.hbase.policymgr.url.saveAsFile /tmp/hbase_%REPOSITORY_NAME%_json mod create-if-not-exists
xasecure.hbase.policymgr.url.laststoredfile %POLICY_CACHE_FILE_PATH%/hbase_%REPOSITORY_NAME%_json mod create-if-not-exists
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hbase-agent/conf/xasecure-hbase-security.xml
----------------------------------------------------------------------
diff --git a/hbase-agent/conf/xasecure-hbase-security.xml b/hbase-agent/conf/xasecure-hbase-security.xml
index 486e06d..01e17a3 100644
--- a/hbase-agent/conf/xasecure-hbase-security.xml
+++ b/hbase-agent/conf/xasecure-hbase-security.xml
@@ -22,7 +22,7 @@
Authorizer Module (file-based, policy-manager based) -->
<property>
<name>hbase.authorization.verifier.classname</name>
- <value>com.xasecure.pdp.hbase.XASecureAuthorizer</value>
+ <value>org.apache.ranger.pdp.hbase.RangerAuthorizer</value>
<description>
Class Name of the authorization Module
</description>
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hbase-agent/disable-conf/hbase-site-changes.cfg
----------------------------------------------------------------------
diff --git a/hbase-agent/disable-conf/hbase-site-changes.cfg b/hbase-agent/disable-conf/hbase-site-changes.cfg
index a7804b0..300032e 100644
--- a/hbase-agent/disable-conf/hbase-site-changes.cfg
+++ b/hbase-agent/disable-conf/hbase-site-changes.cfg
@@ -12,5 +12,5 @@
# 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.
-hbase.coprocessor.master.classes com.xasecure.authorization.hbase.XaSecureAuthorizationCoprocessor delval - ,
-hbase.coprocessor.region.classes com.xasecure.authorization.hbase.XaSecureAuthorizationCoprocessor delval - ,
+hbase.coprocessor.master.classes org.apache.ranger.authorization.hbase.RangerAuthorizationCoprocessor delval - ,
+hbase.coprocessor.region.classes org.apache.ranger.authorization.hbase.RangerAuthorizationCoprocessor delval - ,
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hbase-agent/scripts/install.sh
----------------------------------------------------------------------
diff --git a/hbase-agent/scripts/install.sh b/hbase-agent/scripts/install.sh
index 66c5d39..548314d 100644
--- a/hbase-agent/scripts/install.sh
+++ b/hbase-agent/scripts/install.sh
@@ -308,7 +308,7 @@ do
if [ $? -eq 0 ]
then
cp="${install_dir}/installer/lib/*:${hdp_dir}/*:${hdp_lib_dir}/*"
- java -cp "${cp}" com.xasecure.utils.install.XmlConfigChanger -i ${archivefn} -o ${newfn} -c ${f} ${PROP_ARGS}
+ java -cp "${cp}" org.apache.ranger.utils.install.XmlConfigChanger -i ${archivefn} -o ${newfn} -c ${f} ${PROP_ARGS}
if [ $? -eq 0 ]
then
diff -w ${newfn} ${fullpathorgfn} > /dev/null 2>&1
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hbase-agent/src/main/java/com/xasecure/authorization/hbase/Crypt.java
----------------------------------------------------------------------
diff --git a/hbase-agent/src/main/java/com/xasecure/authorization/hbase/Crypt.java b/hbase-agent/src/main/java/com/xasecure/authorization/hbase/Crypt.java
deleted file mode 100644
index 415a33b..0000000
--- a/hbase-agent/src/main/java/com/xasecure/authorization/hbase/Crypt.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * 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 com.xasecure.authorization.hbase;
-
-import javax.crypto.Cipher;
-import javax.crypto.spec.IvParameterSpec;
-import javax.crypto.spec.SecretKeySpec;
-
-import org.apache.commons.codec.binary.Hex;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-public class Crypt {
-
- private static final Log LOG = LogFactory.getLog("SecurityLogger." + XaSecureAuthorizationCoprocessor.class.getName());
-
- private static byte[] IV = { 01, 21, 22, 86, 121, 45, 98, 28, 111, 72, 54, 39, 96, 47, 84, 13 };
- private static final byte[] encryptionKey = "324234sdff3a7d8e".getBytes();
- private static final String CIPHER_ALGO = "AES/CBC/PKCS5Padding";
- private static final String CIPHER_INIT_ALGO = "AES";
-
- private static Crypt me = null ;
-
- private Cipher encrypter = null;
- private Cipher descrypter = null;
-
-
- public static Crypt getInstance() {
- if (me == null) {
- synchronized (Crypt.class) {
- Crypt other = me ;
- if (other == null) {
- me = new Crypt() ;
- }
- }
- }
- return me ;
- }
-
- private Crypt() {
- try {
- encrypter = Cipher.getInstance(CIPHER_ALGO);
- SecretKeySpec enckey = new SecretKeySpec(encryptionKey, CIPHER_INIT_ALGO);
- encrypter.init(Cipher.ENCRYPT_MODE, enckey, new IvParameterSpec(IV));
-
- descrypter = Cipher.getInstance(CIPHER_ALGO);
- SecretKeySpec deckey = new SecretKeySpec(encryptionKey, CIPHER_INIT_ALGO);
- descrypter.init(Cipher.DECRYPT_MODE, deckey, new IvParameterSpec(IV));
- } catch (Throwable t) {
- LOG.error("Unable to initialzie Encrypt/Decrypt module - Exiting from HBase", t);
- System.exit(1);
- }
- }
-
- public synchronized byte[] encrypt(byte[] plainText) throws Exception {
- byte[] ret = encrypter.doFinal(plainText);
- LOG.debug("Encrypted plain text: [" + new String(plainText) + "] => {" + Hex.encodeHexString(ret) + "}") ;
- return ret ;
- }
-
- public synchronized byte[] decrypt(byte[] cipherText) throws Exception {
- byte[] ret = descrypter.doFinal(cipherText);
- LOG.debug("Decrypted From text: [" + Hex.encodeHexString(cipherText) + "] => {" + new String(ret) + "}") ;
- return ret ;
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hbase-agent/src/main/java/com/xasecure/authorization/hbase/HBaseAccessController.java
----------------------------------------------------------------------
diff --git a/hbase-agent/src/main/java/com/xasecure/authorization/hbase/HBaseAccessController.java b/hbase-agent/src/main/java/com/xasecure/authorization/hbase/HBaseAccessController.java
deleted file mode 100644
index 6370668..0000000
--- a/hbase-agent/src/main/java/com/xasecure/authorization/hbase/HBaseAccessController.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * 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 com.xasecure.authorization.hbase;
-
-import java.util.List;
-
-import org.apache.hadoop.hbase.security.User;
-import org.apache.hadoop.hbase.security.access.Permission.Action;
-import org.apache.hadoop.hbase.security.access.UserPermission;
-
-public interface HBaseAccessController {
- public boolean isAccessAllowed(User user, Action accessAction) ;
- public boolean isAccessAllowed(User user, byte[] tableName, Action accessAction) ;
- public boolean isAccessAllowed(User user, byte[] tableName, byte[] columnFamily, byte[] qualifier, Action accessAction) ;
- public boolean isEncrypted(byte[] tableName, byte[] columnFamily, byte[] qualifier) ;
- public boolean isAudited(byte[] tableName) ;
- public boolean isTableHasEncryptedColumn(byte[] tableName) ;
- public List<UserPermission> getUserPermissions(User user) ;
- public List<UserPermission> getUserPermissions(User user, byte[] tableName) ;
-
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hbase-agent/src/main/java/com/xasecure/authorization/hbase/HBaseAccessControllerFactory.java
----------------------------------------------------------------------
diff --git a/hbase-agent/src/main/java/com/xasecure/authorization/hbase/HBaseAccessControllerFactory.java b/hbase-agent/src/main/java/com/xasecure/authorization/hbase/HBaseAccessControllerFactory.java
deleted file mode 100644
index a762bc8..0000000
--- a/hbase-agent/src/main/java/com/xasecure/authorization/hbase/HBaseAccessControllerFactory.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * 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 com.xasecure.authorization.hbase;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import com.xasecure.authorization.hadoop.config.XaSecureConfiguration;
-import com.xasecure.authorization.hadoop.constants.XaSecureHadoopConstants;
-
-public class HBaseAccessControllerFactory {
-
- private static final Log LOG = LogFactory.getLog(HBaseAccessControllerFactory.class) ;
-
- private static HBaseAccessController hBaseAccessController = null ;
-
- public static HBaseAccessController getInstance() {
- if (hBaseAccessController == null) {
- synchronized(HBaseAccessControllerFactory.class) {
- HBaseAccessController temp = hBaseAccessController ;
- if (temp == null) {
-
- String hBaseAccessControllerClassName = XaSecureConfiguration.getInstance().get(XaSecureHadoopConstants.HBASE_ACCESS_VERIFIER_CLASS_NAME_PROP, XaSecureHadoopConstants.HBASE_ACCESS_VERIFIER_CLASS_NAME_DEFAULT_VALUE) ;
- if (hBaseAccessControllerClassName != null) {
- try {
- hBaseAccessControllerClassName = hBaseAccessControllerClassName.trim();
- hBaseAccessController = (HBaseAccessController) (Class.forName(hBaseAccessControllerClassName).newInstance()) ;
- LOG.info("Created a new instance of class: [" + hBaseAccessControllerClassName + "] for HBase Access verification.");
- } catch (InstantiationException e) {
- LOG.error("Unable to create HBaseAccessController : [" + hBaseAccessControllerClassName + "]", e);
- } catch (IllegalAccessException e) {
- LOG.error("Unable to create HBaseAccessController : [" + hBaseAccessControllerClassName + "]", e);
- } catch (ClassNotFoundException e) {
- LOG.error("Unable to create HBaseAccessController : [" + hBaseAccessControllerClassName + "]", e);
- }
- }
- }
- }
- }
- return hBaseAccessController ;
-
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hbase-agent/src/main/java/com/xasecure/authorization/hbase/XaSecureAccessControlFilter.java
----------------------------------------------------------------------
diff --git a/hbase-agent/src/main/java/com/xasecure/authorization/hbase/XaSecureAccessControlFilter.java b/hbase-agent/src/main/java/com/xasecure/authorization/hbase/XaSecureAccessControlFilter.java
deleted file mode 100644
index 95e5827..0000000
--- a/hbase-agent/src/main/java/com/xasecure/authorization/hbase/XaSecureAccessControlFilter.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * 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 com.xasecure.authorization.hbase;
-
-import java.io.IOException;
-
-import org.apache.hadoop.hbase.Cell;
-import org.apache.hadoop.hbase.filter.FilterBase;
-import org.apache.hadoop.hbase.security.User;
-import org.apache.hadoop.hbase.security.access.TablePermission;
-
-public class XaSecureAccessControlFilter extends FilterBase {
-
- private byte[] table = null;
- private User user = null;
-
- public XaSecureAccessControlFilter(User ugi, byte[] tableName) {
- table = tableName;
- user = ugi;
- }
-
-
- @SuppressWarnings("deprecation")
- @Override
- public ReturnCode filterKeyValue(Cell kv) throws IOException {
- HBaseAccessController accessController = HBaseAccessControllerFactory.getInstance();
- if (accessController.isAccessAllowed(user, table, kv.getFamily(), kv.getQualifier(), TablePermission.Action.READ)) {
- return ReturnCode.INCLUDE;
- } else {
- return ReturnCode.NEXT_COL;
- }
- }
-
-}
[44/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-common/src/main/java/org/apache/ranger/authorization/hadoop/log/HdfsFileAppender.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/authorization/hadoop/log/HdfsFileAppender.java b/agents-common/src/main/java/org/apache/ranger/authorization/hadoop/log/HdfsFileAppender.java
new file mode 100644
index 0000000..d0ff30e
--- /dev/null
+++ b/agents-common/src/main/java/org/apache/ranger/authorization/hadoop/log/HdfsFileAppender.java
@@ -0,0 +1,1376 @@
+/*
+ * 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.authorization.hadoop.log;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.security.PrivilegedExceptionAction;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.Locale;
+import java.util.TimeZone;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FSDataOutputStream;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.FileUtil;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.log4j.FileAppender;
+import org.apache.log4j.Layout;
+import org.apache.log4j.spi.LoggingEvent;
+import org.apache.log4j.helpers.LogLog;
+
+
+/********************************
+* HdfsFileAppender
+*
+**********************************/
+public class HdfsFileAppender extends FileAppender {
+
+
+ // Constants for checking the DatePattern
+ public static final String MINUTES ="Min";
+ public static final String HOURS ="Hr";
+ public static final String DAYS ="Day";
+ public static final String WEEKS ="Week";
+ public static final String MONTHS ="Month";
+
+ // The code assumes that the following constants are in a increasing sequence.
+ public static final int TOP_OF_TROUBLE = -1;
+ public static final int TOP_OF_MINUTE = 0;
+ public static final int TOP_OF_HOUR = 1;
+ public static final int HALF_DAY = 2;
+ public static final int TOP_OF_DAY = 3;
+ public static final int TOP_OF_WEEK = 4;
+ public static final int TOP_OF_MONTH = 5;
+
+ /**
+ * The date pattern. By default, the pattern is set to "1Day" meaning daily rollover.
+ */
+ private String hdfsFileRollingInterval = "1Day";
+
+ private String fileRollingInterval = "1Day";
+
+
+ private String scheduledFileCache;
+
+ /**
+ * The next time we estimate a rollover should occur.
+ */
+ private long nextCheck = System.currentTimeMillis() - 1;
+
+ private long prevnextCheck = nextCheck;
+
+ private long nextCheckLocal = System.currentTimeMillis() -1;
+
+ private long prevnextCheckLocal = nextCheckLocal;
+
+ private Date now = new Date();
+
+ private Date nowLocal = now;
+
+ private SimpleDateFormat sdf;
+
+ private RollingCalendar rc = new RollingCalendar();
+
+ private RollingCalendar rcLocal = new RollingCalendar();
+
+ private FileOutputStream ostream = null;
+
+ private String fileSystemName;
+
+ private Layout layout = null;
+
+ private String encoding = null;
+
+ private String hdfsfileName = null;
+
+ private String actualHdfsfileName = null;
+
+ private String scheduledHdfsFileName = null;
+
+ private String fileCache = null;
+
+ private HdfsSink hs = null;
+
+ private Writer cacheWriter = null;
+
+ private FileOutputStream cacheOstream = null;
+
+ private boolean hdfsAvailable = false;
+
+ private long hdfsNextCheck = System.currentTimeMillis() - 1;
+
+ private boolean timeCheck = false;
+
+ private int hdfsFileRollOffset = 0;
+
+ private int fileRollOffset = 0;
+
+ private boolean firstTime = true;
+
+ private boolean firstTimeLocal = true;
+
+ private String hdfsLiveUpdate = "true";
+
+ boolean hdfsUpdateAllowed = true;
+
+ private String hdfsCheckInterval=null;
+
+ private String processUser = null;
+
+ private String datePattern = "'.'yyyy-MM-dd-HH-mm";
+
+ /**
+ * The gmtTimeZone is used only in computeCheckPeriod() method.
+ */
+ private static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT+0");
+
+ private static final String DEFAULT_HDFSCHECKINTERVAL = "2min";
+
+ /**
+ * The default constructor does nothing.
+ */
+ public HdfsFileAppender() {
+
+ }
+
+
+ /**
+ * The <b>hdfsFileRollingInterval</b> takes a string like 1min, 5min,... 1hr, 2hrs,.. 1day, 2days... 1week, 2weeks.. 1month, 2months.. for hdfs File rollover schedule.
+ */
+ public void setHdfsFileRollingInterval(String pattern) {
+ hdfsFileRollingInterval = pattern;
+ }
+
+ /** Returns the value of the <b>hdfsFileRollingInterval</b> option. */
+ public String getHdfsFileRollingInterval() {
+ return hdfsFileRollingInterval;
+ }
+
+ /**
+ * The <b>LocalDatePattern</b> takes a string like 1min, 5min,... 1hr, 2hrs,.. 1day, 2days... 1week, 2weeks.. 1month, 2months.. for local cache File rollover schedule.
+ */
+ public void setFileRollingInterval(String pattern) {
+ fileRollingInterval = pattern;
+ }
+
+ /** Returns the value of the <b>FileRollingInterval</b> option. */
+ public String getFileRollingInterval() {
+ return fileRollingInterval;
+ }
+
+ /**
+ * This will set liveHdfsUpdate flag , where true will update hdfs live else false will create local cache files and copy the files to hdfs
+ */
+ public void setHdfsLiveUpdate(String val) {
+ hdfsLiveUpdate=val;
+ }
+
+ /** Returns the value of the <b>FileRollingInterval</b> option. */
+ public String getHdfsLiveUpdate() {
+ return hdfsLiveUpdate;
+ }
+
+ public String getHdfsCheckInterval() {
+ return hdfsCheckInterval;
+ }
+
+ public void setHdfsCheckInterval(String val){
+ hdfsCheckInterval = ( hdfsCheckInterval != null) ? val : DEFAULT_HDFSCHECKINTERVAL;
+ }
+
+ public String getEncoding() {
+ return encoding;
+ }
+
+ public void setEncoding(String value) {
+ encoding = value;
+ }
+
+ public void activateOptions() {
+ super.activateOptions();
+
+ sdf = new SimpleDateFormat(datePattern);
+ processUser=System.getProperties().getProperty("user.name");
+
+ if(hdfsFileRollingInterval != null && fileName != null) {
+ now.setTime(System.currentTimeMillis());
+ int type = computeCheckPeriod(hdfsFileRollingInterval);
+ hdfsFileRollOffset = getTimeOffset(hdfsFileRollingInterval);
+ printHdfsPeriodicity(type,hdfsFileRollOffset);
+ rc.setType(type);
+ LogLog.debug("File name: " + fileName);
+ File file = new File(fileName);
+ scheduledHdfsFileName = hdfsfileName+sdf.format(new Date(file.lastModified()));
+ firstTime = true;
+ LogLog.debug("Local and hdfs Files" + scheduledHdfsFileName + " " +scheduledHdfsFileName) ;
+
+ } else {
+ LogLog.error("Either File or hdfsFileRollingInterval options are not set for appender [" + name + "].");
+ }
+
+ // Local Cache File
+
+ if (fileRollingInterval != null && fileCache != null){
+ nowLocal.setTime(System.currentTimeMillis());
+ int localtype = computeCheckPeriod(fileRollingInterval);
+ fileRollOffset = getTimeOffset(fileRollingInterval);
+ printLocalPeriodicity(localtype,fileRollOffset);
+ rcLocal.setType(localtype);
+ LogLog.debug("LocalCacheFile name: " + fileCache);
+ File fileCachehandle = new File(fileCache);
+ scheduledFileCache = fileCache+sdf.format(new Date(fileCachehandle.lastModified()));
+ firstTimeLocal = true;
+
+ } else {
+ LogLog.error("Either File or LocalDatePattern options are not set for appender [" + name + "].");
+ }
+
+ hdfsUpdateAllowed = Boolean.parseBoolean(hdfsLiveUpdate);
+ actualHdfsfileName = hdfsfileName + sdf.format(System.currentTimeMillis());
+ }
+
+ public static int containsIgnoreCase(String str1, String str2) {
+ return str1.toLowerCase().indexOf(str2.toLowerCase());
+ }
+
+
+ public int computeCheckPeriod(String timePattern){
+
+ if(containsIgnoreCase(timePattern, MINUTES) > 0) {
+ return TOP_OF_MINUTE;
+ }
+
+ if(containsIgnoreCase(timePattern, HOURS) > 0) {
+ return TOP_OF_HOUR;
+ }
+
+ if(containsIgnoreCase(timePattern, DAYS) > 0) {
+ return TOP_OF_DAY;
+ }
+
+ if(containsIgnoreCase(timePattern, WEEKS) > 0) {
+ return TOP_OF_WEEK;
+ }
+
+ if(containsIgnoreCase(timePattern, MONTHS) > 0) {
+ return TOP_OF_MONTH;
+ }
+
+ return TOP_OF_TROUBLE;
+ }
+
+
+ private void printHdfsPeriodicity(int type, int offset) {
+ switch(type) {
+ case TOP_OF_MINUTE:
+ LogLog.debug("Appender [" + name + "] to be rolled every " + offset + " minute.");
+ break;
+ case TOP_OF_HOUR:
+ LogLog.debug("Appender [" + name + "] to be rolled on top of every " + offset + " hour.");
+ break;
+ case HALF_DAY:
+ LogLog.debug("Appender [" + name + "] to be rolled at midday and midnight.");
+ break;
+ case TOP_OF_DAY:
+ LogLog.debug("Appender [" + name + "] to be rolled on top of every " + offset + " day.");
+ break;
+ case TOP_OF_WEEK:
+ LogLog.debug("Appender [" + name + "] to be rolled on top of every " + offset + " week.");
+ break;
+ case TOP_OF_MONTH:
+ LogLog.debug("Appender [" + name + "] to be rolled at start of every " + offset + " month.");
+ break;
+ default:
+ LogLog.warn("Unknown periodicity for appender [" + name + "].");
+ }
+ }
+
+
+ public int getTimeOffset(String timePattern){
+ int index;
+ int offset=-1;
+
+ if ((index = containsIgnoreCase(timePattern, MINUTES)) > 0) {
+ offset = Integer.parseInt(timePattern.substring(0,index));
+ }
+
+ if ((index = containsIgnoreCase(timePattern, HOURS)) > 0) {
+ offset = Integer.parseInt(timePattern.substring(0,index));
+
+ }
+
+ if ((index = containsIgnoreCase(timePattern, DAYS)) > 0) {
+ offset = Integer.parseInt(timePattern.substring(0,index));
+
+ }
+
+ if ((index = containsIgnoreCase(timePattern, WEEKS)) > 0) {
+ offset = Integer.parseInt(timePattern.substring(0,index));
+
+ }
+
+ if ((index = containsIgnoreCase(timePattern, MONTHS)) > 0) {
+ offset = Integer.parseInt(timePattern.substring(0,index));
+
+ }
+
+ return offset;
+ }
+
+ private void printLocalPeriodicity(int type, int offset) {
+ switch(type) {
+ case TOP_OF_MINUTE:
+ LogLog.debug("Appender [" + name + "] Local File to be rolled every " + offset + " minute.");
+ break;
+ case TOP_OF_HOUR:
+ LogLog.debug("Appender [" + name + "] Local File to be rolled on top of every " + offset + " hour.");
+ break;
+ case HALF_DAY:
+ LogLog.debug("Appender [" + name + "] Local File to be rolled at midday and midnight.");
+ break;
+ case TOP_OF_DAY:
+ LogLog.debug("Appender [" + name + "] Local File to be rolled on top of every " + offset + " day.");
+ break;
+ case TOP_OF_WEEK:
+ LogLog.debug("Appender [" + name + "] Local File to be rolled on top of every " + offset + " week.");
+ break;
+ case TOP_OF_MONTH:
+ LogLog.debug("Appender [" + name + "] Local File to be rolled at start of every " + offset + " month.");
+ break;
+ default:
+ LogLog.warn("Unknown periodicity for appender [" + name + "].");
+ }
+ }
+
+
+
+
+ /**
+ * Rollover the current file to a new file.
+ */
+ private void rollOver() throws IOException {
+ /* Compute filename, but only if hdfsFileRollingInterval is specified */
+ if(hdfsFileRollingInterval == null) {
+ errorHandler.error("Missing hdfsFileRollingInterval option in rollOver().");
+ return;
+ }
+
+ long epochNow = System.currentTimeMillis();
+
+ String datedhdfsFileName = hdfsfileName+sdf.format(epochNow);
+
+ LogLog.debug("In rollOver epochNow" + epochNow + " " + "nextCheck: " + prevnextCheck );
+
+
+ // It is too early to roll over because we are still within the bounds of the current interval. Rollover will occur once the next interval is reached.
+
+ if (epochNow < prevnextCheck) {
+ return;
+ }
+
+ // close current file, and rename it to datedFilename
+ this.closeFile();
+
+ LogLog.debug("Rolling Over hdfs file to " + scheduledHdfsFileName);
+
+
+ if ( hdfsAvailable ) {
+ // for hdfs file we don't rollover the fike, we rename the file.
+ actualHdfsfileName = hdfsfileName + sdf.format(System.currentTimeMillis());
+ }
+
+ try {
+ // This will also close the file. This is OK since multiple close operations are safe.
+ this.setFile(fileName, false, this.bufferedIO, this.bufferSize);
+ } catch(IOException e) {
+ errorHandler.error("setFile(" + fileName + ", false) call failed.");
+ }
+ scheduledHdfsFileName = datedhdfsFileName;
+ }
+
+
+ /**
+ * Rollover the current Local file to a new file.
+ */
+ private void rollOverLocal() throws IOException {
+ /* Compute filename, but only if datePattern is specified */
+ if(fileRollingInterval == null) {
+ errorHandler.error("Missing LocalDatePattern option in rollOverLocal().");
+ return;
+ }
+
+ long epochNow = System.currentTimeMillis();
+
+ String datedCacheFileName = fileCache+sdf.format(epochNow);
+ LogLog.debug("In rollOverLocal() epochNow" + epochNow + " " + "nextCheckLocal: " + prevnextCheckLocal );
+
+ // It is too early to roll over because we are still within the bounds of the current interval. Rollover will occur once the next interval is reached.
+ if (epochNow < prevnextCheckLocal ) {
+ return;
+ }
+
+ if (new File(fileCache).length() != 0 ) {
+ LogLog.debug("Rolling Local cache to " + scheduledFileCache);
+
+ this.closeCacheWriter();
+
+ File target = new File(scheduledFileCache);
+ if (target.exists()) {
+ target.delete();
+ }
+
+ File file = new File(fileCache);
+
+ boolean result = file.renameTo(target);
+
+ if(result) {
+ LogLog.debug(fileCache +" -> "+ scheduledFileCache);
+ } else {
+ LogLog.error("Failed to rename cache file ["+fileCache+"] to ["+scheduledFileCache+"].");
+ }
+ setFileCacheWriter();
+ scheduledFileCache = datedCacheFileName;
+ }
+ }
+
+
+ /**
+ * <p>
+ * Sets and <i>opens</i> the file where the log output will go. The specified file must be writable.
+ * <p>
+ * If there was already an opened file, then the previous file is closed first.
+ * <p>
+ * <b>Do not use this method directly. To configure a FileAppender or one of its subclasses, set its properties one by one and then call
+ * activateOptions.</b>
+ *
+ * @param fileName The path to the log file.
+ * @param append If true will append to fileName. Otherwise will truncate fileName.
+ */
+ public void setFile(String file) {
+ // Trim spaces from both ends. The users probably does not want
+ // trailing spaces in file names.
+ String val = file.trim();
+
+ fileName=val;
+ fileCache=val+".cache";
+
+ }
+
+ @Override
+ public synchronized void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize) throws IOException {
+ LogLog.debug("setFile called: "+fileName+", "+append);
+
+ // It does not make sense to have immediate flush and bufferedIO.
+ if(bufferedIO) {
+ setImmediateFlush(false);
+ }
+
+ reset();
+
+ try {
+ //
+ // attempt to create file
+ //
+ ostream = new FileOutputStream(fileName, append);
+ } catch(FileNotFoundException ex) {
+ //
+ // if parent directory does not exist then
+ // attempt to create it and try to create file
+ // see bug 9150
+ //
+ File umFile = new File(fileName);
+ String parentName = umFile.getParent();
+
+ if (parentName != null) {
+ File parentDir = new File(parentName);
+ if(!parentDir.exists() && parentDir.mkdirs()) {
+ ostream = new FileOutputStream(fileName, append);
+ } else {
+ throw ex;
+ }
+ } else {
+ throw ex;
+ }
+ }
+
+ Writer fw = createWriter(ostream);
+ if(bufferedIO) {
+ fw = new BufferedWriter(fw, bufferSize);
+ }
+ this.setQWForFiles(fw);
+ this.fileName = fileName;
+ this.fileAppend = append;
+ this.bufferedIO = bufferedIO;
+ this.bufferSize = bufferSize;
+
+ //set cache file
+ setFileCacheWriter();
+
+ writeHeader();
+
+ LogLog.debug("setFile ended");
+ }
+
+ public void setHdfsDestination(final String name) {
+ //Setting the fileSystemname
+
+ String hostName = null;
+
+ String val = name.trim();
+
+ try {
+
+ hostName = InetAddress.getLocalHost().getHostName();
+ val=val.replaceAll("%hostname%", hostName);
+ String hostStr[] = val.split(":");
+ if ( hostStr.length > 0 ) {
+ fileSystemName = hostStr[0]+":"+hostStr[1]+":"+hostStr[2];
+
+ hdfsfileName = hostStr[3];
+
+ } else {
+ LogLog.error("Failed to set HdfsSystem and File");
+ }
+
+ } catch (UnknownHostException uhe) {
+ LogLog.error("Setting the Hdfs Desitination Failed", uhe);
+ }
+
+ LogLog.debug("FileSystemName:" + fileSystemName + "fileName:"+ hdfsfileName);
+
+ }
+
+ /**
+ * This method differentiates HdfsFileAppender from its super class.
+ * <p>
+ * Before actually logging, this method will check whether it is time to do a rollover. If it is, it will schedule the next rollover time and then rollover.
+ */
+ @Override
+ protected void subAppend(LoggingEvent event) {
+ LogLog.debug("Called subAppend for logging into hdfs...");
+
+ long n = System.currentTimeMillis();
+ if(n >= nextCheck) {
+ now.setTime(n);
+ prevnextCheck = nextCheck;
+ nextCheck = rc.getNextCheckMillis(now,hdfsFileRollOffset);
+ if ( firstTime) {
+ prevnextCheck = nextCheck;
+ firstTime = false;
+ }
+ try {
+ if (hdfsUpdateAllowed) {
+ rollOver();
+ }
+ } catch(IOException e) {
+ LogLog.error("rollOver() failed.", e);
+ }
+ }
+
+ long nLocal = System.currentTimeMillis();
+ if ( nLocal > nextCheckLocal ) {
+ nowLocal.setTime(nLocal);
+ prevnextCheckLocal = nextCheckLocal;
+ nextCheckLocal = rcLocal.getNextCheckMillis(nowLocal, fileRollOffset);
+ if ( firstTimeLocal) {
+ prevnextCheckLocal = nextCheckLocal;
+ firstTimeLocal = false;
+ }
+ try {
+ rollOverLocal();
+ } catch(IOException e) {
+ LogLog.error("rollOverLocal() failed.", e);
+ }
+ }
+
+ this.layout = this.getLayout();
+ this.encoding = this.getEncoding();
+
+ // Append HDFS
+ appendHDFSFileSystem(event);
+
+
+ //super.subAppend(event);
+ }
+
+ @Override
+ protected
+ void reset() {
+ closeWriter();
+ this.qw = null;
+ //this.
+ this.closeHdfsWriter();
+ this.closeCacheWriter();
+ }
+
+ @Override
+ public synchronized void close() {
+ LogLog.debug("Closing all resource..");
+ this.closeFile();
+ this.closeHdfsWriter();
+ this.closeHdfsOstream();
+ this.closeFileSystem();
+ }
+
+ @Override
+ protected void closeFile() {
+ try {
+ if(this.ostream != null) {
+ this.ostream.close();
+ this.ostream = null;
+ }
+ } catch(IOException ie) {
+ LogLog.error("unable to close output stream", ie);
+ }
+ this.closeHdfsWriter();
+ this.closeHdfsOstream();
+ }
+
+ @Override
+ protected void closeWriter() {
+ try {
+ if(this.qw != null) {
+ this.qw.close();
+ this.qw = null;
+ }
+ } catch(IOException ie) {
+ LogLog.error("unable to close writer", ie);
+ }
+ }
+
+ @Override
+ public void finalize() {
+ super.finalize();
+ close();
+ }
+
+
+ /******* HDFS Appender methods ***********/
+
+ private void appendHDFSFileSystem(LoggingEvent event) {
+
+ long currentTime = System.currentTimeMillis();
+
+ try {
+
+ if ( currentTime >= hdfsNextCheck ) {
+
+ LogLog.debug("About to Open fileSystem" + fileSystemName+" "+actualHdfsfileName) ;
+ hs = openHdfsSink(fileSystemName,actualHdfsfileName,fileCache,fileAppend,bufferedIO,bufferSize,layout,encoding,scheduledFileCache,cacheWriter,hdfsUpdateAllowed,processUser);
+ if (hdfsUpdateAllowed) {
+ // stream into hdfs only when liveHdfsUpdate flag is true else write to cache file.
+ hs.setOsteam();
+ hs.setWriter();
+ hs.append(event);
+ } else {
+ writeToCache(event);
+ }
+ hdfsAvailable = true;
+
+ } else {
+ // Write the Log To cache file util time to check hdfs availability
+ hdfsAvailable = false;
+ LogLog.debug("Hdfs Down..Will check hdfs vailability after " + hdfsNextCheck + "Current Time :" +hdfsNextCheck ) ;
+ writeToCache(event);
+ }
+ }
+ catch(Throwable t) {
+ // Write the Log To cache file if hdfs connect error out.
+ hdfsAvailable = false;
+ if ( !timeCheck ) {
+ int hdfscheckInterval = getTimeOffset(hdfsCheckInterval);
+ hdfsNextCheck = System.currentTimeMillis()+(1000*60*hdfscheckInterval);
+ timeCheck = true;
+ LogLog.debug("Hdfs Down..Will check hdfs vailability after " + hdfsCheckInterval , t) ;
+
+ }
+ writeToCache(event);
+ }
+
+ }
+
+
+ private HdfsSink openHdfsSink(String fileSystemName,String filename, String fileCache, boolean append, boolean bufferedIO,int bufferSize,Layout layout, String encoding, String scheduledCacheFile, Writer cacheWriter,boolean hdfsUpdateAllowed,String processUser) throws Throwable {
+
+ HdfsSink hs = null;
+ hs = HdfsSink.getInstance();
+ if ( hs != null)
+
+ LogLog.debug("Hdfs Sink successfully instatiated");
+ try {
+ hs.init(fileSystemName, filename, fileCache, append, bufferedIO, bufferSize, layout, encoding,scheduledCacheFile,cacheWriter,hdfsUpdateAllowed,processUser);
+
+ } catch (Throwable t) {
+ throw t;
+ }
+ return hs;
+
+ }
+
+ private void closeHdfsOstream() {
+ if (hs != null ){
+ LogLog.debug("Closing hdfs outstream") ;
+ hs.closeHdfsOstream();
+ }
+ }
+
+ private void closeHdfsWriter() {
+
+ if (hs != null) {
+ LogLog.debug("Closing hdfs Writer") ;
+ hs.closeHdfsWriter();
+ }
+ }
+
+ private void closeFileSystem() {
+ hs.closeHdfsSink();
+ }
+
+
+
+ /****** Cache File Methods **/
+
+
+ public void setFileCacheWriter() {
+
+ try {
+ setFileCacheOstream(fileCache);
+ } catch(IOException ie) {
+ LogLog.error("Logging failed while tring to write into Cache File..", ie);
+ }
+ LogLog.debug("Setting Cache Writer..");
+ cacheWriter = createCacheFileWriter(cacheOstream);
+ if(bufferedIO) {
+ cacheWriter = new BufferedWriter(cacheWriter, bufferSize);
+ }
+ }
+
+
+ private void setFileCacheOstream(String fileCache) throws IOException {
+
+ try {
+ cacheOstream = new FileOutputStream(fileCache, true);
+ } catch(FileNotFoundException ex) {
+ String parentName = new File(fileCache).getParent();
+ if (parentName != null) {
+ File parentDir = new File(parentName);
+ if(!parentDir.exists() && parentDir.mkdirs()) {
+ cacheOstream = new FileOutputStream(fileName, true);
+ } else {
+ throw ex;
+ }
+ } else {
+ throw ex;
+ }
+ }
+ }
+
+
+ public OutputStreamWriter createCacheFileWriter(OutputStream os ) {
+ OutputStreamWriter retval = null;
+
+ if(encoding != null) {
+ try {
+ retval = new OutputStreamWriter(os, encoding);
+ } catch(IOException ie) {
+ LogLog.warn("Error initializing output writer.");
+ LogLog.warn("Unsupported encoding?");
+ }
+ }
+ if(retval == null) {
+ retval = new OutputStreamWriter(os);
+ }
+ return retval;
+ }
+
+
+ public void writeToCache(LoggingEvent event) {
+
+ try {
+ LogLog.debug("Writing log to Cache.." + "layout: "+ this.layout.format(event) + "ignoresThowable: "+layout.ignoresThrowable() + "Writer:" + cacheWriter.toString());
+
+ cacheWriter.write(this.layout.format(event));
+ cacheWriter.flush();
+
+ if(layout.ignoresThrowable()) {
+ String[] s = event.getThrowableStrRep();
+ if (s != null) {
+ int len = s.length;
+ for(int i = 0; i < len; i++) {
+ LogLog.debug("Log:" + s[i]);
+ cacheWriter.write(s[i]);
+ cacheWriter.write(Layout.LINE_SEP);
+ cacheWriter.flush();
+ }
+ }
+ }
+ } catch (IOException ie) {
+ LogLog.error("Unable to log event message to hdfs:", ie);
+ }
+ }
+
+ public void rollOverCacheFile() {
+
+ if (new File(fileCache).length() != 0 ) {
+
+ long epochNow = System.currentTimeMillis();
+
+ String datedCacheFileName = fileCache + "." + epochNow;
+ LogLog.debug("Rolling over remaining cache File to new file"+ datedCacheFileName);
+ closeCacheWriter();
+
+ File target = new File(datedCacheFileName);
+ if (target.exists()) {
+ target.delete();
+ }
+
+ File file = new File(fileCache);
+
+ boolean result = file.renameTo(target);
+
+ if(result) {
+ LogLog.debug(fileCache +" -> "+ datedCacheFileName);
+ } else {
+ LogLog.error("Failed to rename cache file ["+fileCache+"] to ["+datedCacheFileName+"].");
+ }
+ }
+ }
+
+ public void closeCacheWriter() {
+ try {
+ if(cacheWriter != null) {
+ cacheWriter.close();
+ cacheWriter = null;
+ }
+ } catch(IOException ie) {
+ LogLog.error("unable to close cache writer", ie);
+ }
+ }
+}
+
+/**
+ * RollingCalendar is a helper class to HdfsFileAppender. Given a periodicity type and the current time, it computes the start of the next interval.
+ */
+
+class RollingCalendar extends GregorianCalendar {
+ private static final long serialVersionUID = 1L;
+
+ private int type = HdfsFileAppender.TOP_OF_TROUBLE;
+
+ RollingCalendar() {
+ super();
+ }
+
+ RollingCalendar(TimeZone tz, Locale locale) {
+ super(tz, locale);
+ }
+
+ void setType(int type) {
+ this.type = type;
+ }
+
+ public long getNextCheckMillis(Date now, int offset) {
+ return getNextCheckDate(now,offset).getTime();
+ }
+
+ public Date getNextCheckDate(Date now,int offset) {
+ this.setTime(now);
+
+ switch(this.type) {
+ case HdfsFileAppender.TOP_OF_MINUTE:
+ this.set(Calendar.SECOND, 0);
+ this.set(Calendar.MILLISECOND, 0);
+ this.add(Calendar.MINUTE, offset);
+ break;
+ case HdfsFileAppender.TOP_OF_HOUR:
+ this.set(Calendar.MINUTE, 0);
+ this.set(Calendar.SECOND, 0);
+ this.set(Calendar.MILLISECOND, 0);
+ this.add(Calendar.HOUR_OF_DAY, offset);
+ break;
+ case HdfsFileAppender.HALF_DAY:
+ this.set(Calendar.MINUTE, 0);
+ this.set(Calendar.SECOND, 0);
+ this.set(Calendar.MILLISECOND, 0);
+ int hour = get(Calendar.HOUR_OF_DAY);
+ if(hour < 12) {
+ this.set(Calendar.HOUR_OF_DAY, 12);
+ } else {
+ this.set(Calendar.HOUR_OF_DAY, 0);
+ this.add(Calendar.DAY_OF_MONTH, 1);
+ }
+ break;
+ case HdfsFileAppender.TOP_OF_DAY:
+ this.set(Calendar.HOUR_OF_DAY, 0);
+ this.set(Calendar.MINUTE, 0);
+ this.set(Calendar.SECOND, 0);
+ this.set(Calendar.MILLISECOND, 0);
+ this.add(Calendar.DATE, offset);
+ break;
+ case HdfsFileAppender.TOP_OF_WEEK:
+ this.set(Calendar.DAY_OF_WEEK, getFirstDayOfWeek());
+ this.set(Calendar.HOUR_OF_DAY, 0);
+ this.set(Calendar.SECOND, 0);
+ this.set(Calendar.MILLISECOND, 0);
+ this.add(Calendar.WEEK_OF_YEAR, offset);
+ break;
+ case HdfsFileAppender.TOP_OF_MONTH:
+ this.set(Calendar.DATE, 1);
+ this.set(Calendar.HOUR_OF_DAY, 0);
+ this.set(Calendar.SECOND, 0);
+ this.set(Calendar.MILLISECOND, 0);
+ this.add(Calendar.MONTH, offset);
+ break;
+ default:
+ throw new IllegalStateException("Unknown periodicity type.");
+ }
+ return getTime();
+ }
+
+
+}
+
+
+/*************
+ * Hdfs Sink
+ *
+ *************/
+
+class HdfsSink {
+
+ private static final String DS_REPLICATION_VAL = "1";
+ private static final String DS_REPLICATION_KEY = "dfs.replication";
+ private static final String FS_DEFAULT_NAME_KEY = "fs.default.name";
+ private Configuration conf = null;
+ private FileSystem fs= null;
+ private Path pt = null;
+ private FSDataOutputStream hdfsostream = null;
+ private String fsName = null;
+ private String fileName = null;
+ private String fileCache = null;
+ private Layout layout = null;
+ private String encoding = null;
+ private Writer hdfswriter = null;
+ private int bufferSize;
+ private boolean bufferedIO=false;
+ private static int fstime=0;
+ private CacheFileWatcher cfw = null;
+ private boolean hdfsUpdateAllowed=true;
+ private String processUser=null;
+
+
+ HdfsSink() {
+ }
+
+ private static final ThreadLocal<HdfsSink> hdfssink = new ThreadLocal<HdfsSink>() {
+ protected HdfsSink initialValue() {
+ return new HdfsSink();
+ }
+ };
+
+ public static HdfsSink getInstance() {
+ return hdfssink.get();
+ }
+
+ public void init(String fileSystemName, String fileName, String fileCache,boolean append, boolean bufferedIO, int bufferSize, Layout layout, String encoding, String scheduledCacheFile, Writer cacheWriter, boolean hdfsUpdateAllowed, String processUser) throws Exception{
+
+ this.fsName=fileSystemName;
+ this.fileName=fileName;
+ this.layout=layout;
+ this.encoding=encoding;
+ this.bufferSize=bufferSize;
+ this.bufferedIO=bufferedIO;
+ this.fileCache=fileCache;
+ this.hdfsUpdateAllowed=hdfsUpdateAllowed;
+ this.processUser=processUser;
+
+ final Configuration conf= new Configuration();
+ conf.set(DS_REPLICATION_KEY,DS_REPLICATION_VAL);
+ conf.set(FS_DEFAULT_NAME_KEY, fsName);
+
+ try {
+ if ( fs == null) {
+ LogLog.debug("Opening Connection to hdfs Sytem" + this.fsName);
+
+ UserGroupInformation ugi = UserGroupInformation.createProxyUser(this.processUser, UserGroupInformation.getLoginUser());
+ fs = ugi.doAs( new PrivilegedExceptionAction<FileSystem>() {
+ public FileSystem run() throws Exception {
+ FileSystem filesystem = FileSystem.get(conf);
+ LogLog.debug("Inside UGI.." + fsName + " " + filesystem);
+ return filesystem;
+ }
+ });
+
+ if ( cfw == null) {
+ // Start the CacheFileWatcher to move the Cache file.
+
+ LogLog.debug("About to run CacheFilWatcher...");
+ Path hdfsfilePath = getParent();
+ cfw = new CacheFileWatcher(this.fs,this.fileCache,hdfsfilePath,cacheWriter,this.hdfsUpdateAllowed,conf);
+ cfw.start();
+ }
+
+ }
+
+ } catch(Exception ie) {
+
+ LogLog.error("Unable to Create hdfs logfile:" + ie.getMessage());
+ throw ie;
+ }
+
+ LogLog.debug("HdfsSystem up: " + fsName + "FS Object:" + fs);
+ }
+
+ public int getfstime() {
+ return fstime;
+ }
+ public FileSystem getFileSystem() {
+ return fs;
+ }
+
+ public Path getPath() {
+ return pt;
+ }
+
+ public Path getParent() {
+ Path pt = new Path(this.fileName);
+ return pt.getParent();
+ }
+
+ public void setOsteam() throws IOException {
+ try {
+ pt = new Path(this.fileName);
+ // if file Exist append it
+ if(fs.exists(pt)) {
+ LogLog.debug("Appending File: "+ this.fsName+":"+this.fileName+fs);
+ if (hdfsostream !=null) {
+ hdfsostream.close();
+ }
+ hdfsostream=fs.append(pt);
+
+ } else {
+ LogLog.debug("Creating File directories in hdfs if not present.."+ this.fsName+":"+this.fileName + fs);
+ String parentName = new Path(this.fileName).getParent().toString();
+ if(parentName != null) {
+ Path parentDir = new Path(parentName);
+ if (!fs.exists(parentDir) ) {
+ LogLog.debug("Creating Parent Directory: " + parentDir );
+ fs.mkdirs(parentDir);
+ }
+ }
+ hdfsostream = fs.create(pt);
+ }
+ } catch (IOException ie) {
+ LogLog.debug("Error While appending hdfsd file." + ie);
+ throw ie;
+ }
+ }
+
+ public void setWriter() {
+ LogLog.debug("Setting Writer..");
+ hdfswriter = createhdfsWriter(hdfsostream);
+ if(bufferedIO) {
+ hdfswriter = new BufferedWriter(hdfswriter, bufferSize);
+ }
+ }
+
+ public Writer getWriter() {
+ return hdfswriter;
+ }
+
+ public void append(LoggingEvent event) throws IOException {
+ try {
+ LogLog.debug("Writing log to HDFS." + "layout: "+ this.layout.format(event) + "ignoresThowable: "+layout.ignoresThrowable() + "Writer:" + hdfswriter.toString());
+
+ hdfswriter.write(this.layout.format(event));
+ hdfswriter.flush();
+ if(layout.ignoresThrowable()) {
+ String[] s = event.getThrowableStrRep();
+ if (s != null) {
+ int len = s.length;
+ for(int i = 0; i < len; i++) {
+ LogLog.debug("Log:" + s[i]);
+ hdfswriter.write(s[i]);
+ hdfswriter.write(Layout.LINE_SEP);
+ hdfswriter.flush();
+ }
+ }
+ }
+ } catch (IOException ie) {
+ LogLog.error("Unable to log event message to hdfs:", ie);
+ throw ie;
+ }
+ }
+
+ public void writeHeader() throws IOException {
+ LogLog.debug("Writing log header...");
+ try {
+ if(layout != null) {
+ String h = layout.getHeader();
+ if(h != null && hdfswriter != null)
+ LogLog.debug("Log header:" + h);
+ hdfswriter.write(h);
+ hdfswriter.flush();
+ }
+ } catch (IOException ie) {
+ LogLog.error("Unable to log header message to hdfs:", ie);
+ throw ie;
+ }
+ }
+
+ public
+ void writeFooter() throws IOException{
+ LogLog.debug("Writing footer header...");
+ try {
+ if(layout != null) {
+ String f = layout.getFooter();
+ if(f != null && hdfswriter != null) {
+ LogLog.debug("Log:" + f);
+ hdfswriter.write(f);
+ hdfswriter.flush();
+ }
+ }
+ } catch (IOException ie) {
+ LogLog.debug("Unable to log header message to hdfs:", ie);
+ throw ie;
+ }
+
+ }
+
+ public void closeHdfsOstream() {
+ try {
+ if(this.hdfsostream != null) {
+ this.hdfsostream.close();
+ this.hdfsostream = null;
+ }
+ } catch(IOException ie) {
+ LogLog.error("unable to close output stream", ie);
+ }
+
+ }
+
+ public void closeHdfsWriter() {
+ try {
+ if(hdfswriter != null) {
+ hdfswriter.close();
+ hdfswriter = null;
+ }
+ } catch(IOException ie) {
+ LogLog.error("unable to hfds writer", ie);
+ }
+ }
+
+ public void closeHdfsSink() {
+ try {
+ if (fs !=null) {
+ fs.close();
+ }
+ } catch (IOException ie) {
+ LogLog.error("Unable to close hdfs " + fs ,ie);
+ }
+ }
+
+
+ public OutputStreamWriter createhdfsWriter(FSDataOutputStream os ) {
+ OutputStreamWriter retval = null;
+
+ if(encoding != null) {
+ try {
+ retval = new OutputStreamWriter(os, encoding);
+ } catch(IOException ie) {
+ LogLog.warn("Error initializing output writer.");
+ LogLog.warn("Unsupported encoding?");
+ }
+ }
+ if(retval == null) {
+ retval = new OutputStreamWriter(os);
+ }
+ return retval;
+ }
+
+
+ }
+
+
+// CacheFileWatcher Thread
+
+class CacheFileWatcher extends Thread {
+
+ long CACHEFILE_WATCHER_SLEEP_TIME = 1000*60*2;
+
+ Configuration conf = null;
+ private FileSystem fs = null;
+ private String cacheFile = null;
+ private File parentDir = null;
+ private File[] files = null;
+ private Path fsPath = null;
+ private Path hdfsfilePath = null;
+ private Writer cacheWriter = null;
+
+ private boolean hdfsUpdateAllowed=true;
+ private boolean cacheFilesCopied = false;
+
+ CacheFileWatcher(FileSystem fs, String cacheFile, Path hdfsfilePath, Writer cacheWriter, boolean hdfsUpdateAllowed, Configuration conf) {
+ this.fs = fs;
+ this.cacheFile = cacheFile;
+ this.conf = conf;
+ this.hdfsfilePath = hdfsfilePath;
+ this.cacheWriter = cacheWriter;
+ this.hdfsUpdateAllowed = hdfsUpdateAllowed;
+ }
+
+
+ public void run(){
+
+ LogLog.debug("CacheFileWatcher Started");
+
+ while (!cacheFilesCopied ){
+
+ if (hdfsUpdateAllowed) {
+ rollRemainingCacheFile();
+ }
+
+ if ( !cacheFilePresent(cacheFile) ) {
+
+ try {
+ Thread.sleep(CACHEFILE_WATCHER_SLEEP_TIME);
+ } catch (InterruptedException ie) {
+ LogLog.error("Unable to complete the CatchFileWatcher Sleep", ie);
+ }
+ } else {
+ try {
+ copyCacheFilesToHdfs();
+ if (hdfsUpdateAllowed) {
+ cacheFilesCopied = true;
+ } else {
+ cacheFilesCopied = false;
+ }
+ } catch (Throwable t) {
+ // Error While copying the file to hdfs and thread goes for sleep and check later
+ cacheFilesCopied = false;
+ LogLog. error("Error while copying Cache Files to hdfs..Sleeping for next try",t);
+
+ try {
+ Thread.sleep(CACHEFILE_WATCHER_SLEEP_TIME);
+ } catch (InterruptedException ie) {
+ LogLog.error("Unable to complete the CatchFileWatcher Sleep", ie);
+ }
+ }
+ }
+ }
+ }
+
+ public boolean cacheFilePresent(String filename) {
+ String parent = new File(filename).getParent();
+ if ( parent != null ) {
+ parentDir = new File(parent);
+ fsPath = new Path(parent);
+ files = parentDir.listFiles(new FilenameFilter() {
+ @Override
+ public boolean accept(File parentDir, String name) {
+ return name.matches(".*cache.+");
+ }
+ });
+ if ( files.length > 0) {
+ LogLog.debug("CacheFile Present..");
+ return true;
+ }
+ }
+ return false;
+ }
+
+
+ public void copyCacheFilesToHdfs() throws Throwable{
+
+ try {
+
+ if (!fs.exists(hdfsfilePath) ) {
+ LogLog.debug("Creating Parent Directory: " + hdfsfilePath );
+ fs.mkdirs(hdfsfilePath);
+ }
+ } catch ( Throwable t) {
+ throw t;
+ }
+
+
+ for ( File cacheFile : files) {
+ try {
+ LogLog.debug("Copying Files..." + "File Path: " + fsPath + "CacheFile: " +cacheFile + "HDFS Path:" + hdfsfilePath);
+ FileUtil.copy(cacheFile, this.fs, this.hdfsfilePath, true, this.conf);
+ } catch (Throwable t) {
+
+ throw t;
+ }
+ }
+ }
+
+ public void rollRemainingCacheFile() {
+ String datePattern = "'.'yyyy-MM-dd-HH-mm";
+ SimpleDateFormat sdf = new SimpleDateFormat(datePattern);
+ if (new File(cacheFile).length() != 0 ) {
+ long epochNow = System.currentTimeMillis();
+
+ String datedCacheFileName = cacheFile + sdf.format(epochNow);
+
+ LogLog.debug("Rolling over remaining cache File "+ datedCacheFileName);
+ closeCacheFile();
+
+ File target = new File(datedCacheFileName);
+ if (target.exists()) {
+ target.delete();
+ }
+
+ File file = new File(cacheFile);
+
+ boolean result = file.renameTo(target);
+
+ if(result) {
+ LogLog.debug(cacheFile +" -> "+ datedCacheFileName);
+ } else {
+ LogLog.error("Failed to rename cache file ["+cacheFile+"] to ["+datedCacheFileName+"].");
+ }
+
+ }
+ }
+
+ public void closeCacheFile() {
+ try {
+ if(cacheWriter != null) {
+ cacheWriter.close();
+ cacheWriter = null;
+ }
+ } catch(IOException ie) {
+ LogLog.error("unable to close cache writer", ie);
+ }
+ }
+}
+
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-common/src/main/java/org/apache/ranger/authorization/utils/StringUtil.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/authorization/utils/StringUtil.java b/agents-common/src/main/java/org/apache/ranger/authorization/utils/StringUtil.java
new file mode 100644
index 0000000..f6f3d2d
--- /dev/null
+++ b/agents-common/src/main/java/org/apache/ranger/authorization/utils/StringUtil.java
@@ -0,0 +1,276 @@
+/*
+ * 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.authorization.utils;
+
+import java.util.Calendar;
+import java.util.Collection;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.List;
+import java.util.TimeZone;
+
+public class StringUtil {
+
+ private static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT+0");
+
+ public static boolean equals(String str1, String str2) {
+ boolean ret = false;
+
+ if(str1 == null) {
+ ret = str2 == null;
+ } else if(str2 == null) {
+ ret = false;
+ } else {
+ ret = str1.equals(str2);
+ }
+
+ return ret;
+ }
+
+ public static boolean equalsIgnoreCase(String str1, String str2) {
+ boolean ret = false;
+
+ if(str1 == null) {
+ ret = str2 == null;
+ } else if(str2 == null) {
+ ret = false;
+ } else {
+ ret = str1.equalsIgnoreCase(str2);
+ }
+
+ return ret;
+ }
+
+ public static boolean equals(Collection<String> set1, Collection<String> set2) {
+ boolean ret = false;
+
+ if(set1 == null) {
+ ret = set2 == null;
+ } else if(set2 == null) {
+ ret = false;
+ } else if(set1.size() == set2.size()) {
+ ret = set1.containsAll(set2);
+ }
+
+ return ret;
+ }
+
+ public static boolean equalsIgnoreCase(Collection<String> set1, Collection<String> set2) {
+ boolean ret = false;
+
+ if(set1 == null) {
+ ret = set2 == null;
+ } else if(set2 == null) {
+ ret = false;
+ } else if(set1.size() == set2.size()) {
+ int numFound = 0;
+
+ for(String str1 : set1) {
+ boolean str1Found = false;
+
+ for(String str2 : set2) {
+ if(equalsIgnoreCase(str1, str2)) {
+ str1Found = true;
+
+ break;
+ }
+ }
+
+ if(str1Found) {
+ numFound++;
+ } else {
+ break;
+ }
+ }
+
+ ret = numFound == set1.size();
+ }
+
+ return ret;
+ }
+
+ public static boolean matches(String pattern, String str) {
+ boolean ret = false;
+
+ if(pattern == null || str == null || pattern.isEmpty() || str.isEmpty()) {
+ ret = true;
+ } else {
+ ret = str.matches(pattern);
+ }
+
+ return ret;
+ }
+
+ /*
+ public static boolean matches(Collection<String> patternSet, Collection<String> strSet) {
+ boolean ret = false;
+
+ if(patternSet == null || strSet == null || patternSet.isEmpty() || strSet.isEmpty()) {
+ ret = true;
+ } else {
+ boolean foundUnmatched = false;
+
+ for(String str : strSet) {
+ boolean isMatched = false;
+ for(String pattern : patternSet) {
+ isMatched = str.matches(pattern);
+
+ if(isMatched) {
+ break;
+ }
+ }
+
+ foundUnmatched = ! isMatched;
+
+ if(foundUnmatched) {
+ break;
+ }
+ }
+
+ ret = !foundUnmatched;
+ }
+
+ return ret;
+ }
+ */
+
+ public static boolean contains(String str, String strToFind) {
+ boolean ret = false;
+
+ if(str != null && strToFind != null) {
+ ret = str.contains(strToFind);
+ }
+
+ return ret;
+ }
+
+ public static boolean containsIgnoreCase(String str, String strToFind) {
+ boolean ret = false;
+
+ if(str != null && strToFind != null) {
+ ret = str.toLowerCase().contains(strToFind.toLowerCase());
+ }
+
+ return ret;
+ }
+
+ public static boolean contains(String[] strArr, String str) {
+ boolean ret = false;
+
+ if(strArr != null && strArr.length > 0 && str != null) {
+ for(String s : strArr) {
+ ret = equals(s, str);
+
+ if(ret) {
+ break;
+ }
+ }
+ }
+
+ return ret;
+ }
+
+ public static boolean containsIgnoreCase(String[] strArr, String str) {
+ boolean ret = false;
+
+ if(strArr != null && strArr.length > 0 && str != null) {
+ for(String s : strArr) {
+ ret = equalsIgnoreCase(s, str);
+
+ if(ret) {
+ break;
+ }
+ }
+ }
+
+ return ret;
+ }
+
+ public static String toString(Iterable<String> iterable) {
+ String ret = "";
+
+ if(iterable != null) {
+ int count = 0;
+ for(String str : iterable) {
+ if(count == 0)
+ ret = str;
+ else
+ ret += (", " + str);
+ count++;
+ }
+ }
+
+ return ret;
+ }
+
+ public static String toString(String[] arr) {
+ String ret = "";
+
+ if(arr != null && arr.length > 0) {
+ ret = arr[0];
+ for(int i = 1; i < arr.length; i++) {
+ ret += (", " + arr[i]);
+ }
+ }
+
+ return ret;
+ }
+
+ public static String toString(List<String> arr) {
+ String ret = "";
+
+ if(arr != null && arr.size() > 0) {
+ ret = arr.get(0);
+ for(int i = 1; i < arr.size(); i++) {
+ ret += (", " + arr.get(i));
+ }
+ }
+
+ return ret;
+ }
+
+ public static boolean isEmpty(String str) {
+ return str == null || str.trim().isEmpty();
+ }
+
+ public static <T> boolean isEmpty(Collection<T> set) {
+ return set == null || set.isEmpty();
+ }
+
+ public static String toLower(String str) {
+ return str == null ? null : str.toLowerCase();
+ }
+
+ public static byte[] getBytes(String str) {
+ return str == null ? null : str.getBytes();
+ }
+
+ public static Date getUTCDate() {
+ Calendar local = Calendar.getInstance();
+ int offset = local.getTimeZone().getOffset(local.getTimeInMillis());
+
+ GregorianCalendar utc = new GregorianCalendar(gmtTimeZone);
+
+ utc.setTimeInMillis(local.getTimeInMillis());
+ utc.add(Calendar.MILLISECOND, -offset);
+
+ return utc.getTime();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-cred/.settings/org.eclipse.core.resources.prefs
----------------------------------------------------------------------
diff --git a/agents-cred/.settings/org.eclipse.core.resources.prefs b/agents-cred/.settings/org.eclipse.core.resources.prefs
index e9441bb..f9fe345 100644
--- a/agents-cred/.settings/org.eclipse.core.resources.prefs
+++ b/agents-cred/.settings/org.eclipse.core.resources.prefs
@@ -1,3 +1,4 @@
eclipse.preferences.version=1
encoding//src/main/java=UTF-8
+encoding//src/test/java=UTF-8
encoding/<project>=UTF-8
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-cred/src/main/java/com/xasecure/authorization/hadoop/utils/XaSecureCredentialProvider.java
----------------------------------------------------------------------
diff --git a/agents-cred/src/main/java/com/xasecure/authorization/hadoop/utils/XaSecureCredentialProvider.java b/agents-cred/src/main/java/com/xasecure/authorization/hadoop/utils/XaSecureCredentialProvider.java
deleted file mode 100644
index 3fc0728..0000000
--- a/agents-cred/src/main/java/com/xasecure/authorization/hadoop/utils/XaSecureCredentialProvider.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * 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 com.xasecure.authorization.hadoop.utils;
-
-import java.lang.String;
-import java.util.List;
-import java.io.IOException;
-
-import org.apache.hadoop.security.alias.CredentialProvider;
-import org.apache.hadoop.security.alias.CredentialProviderFactory;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-
-public class XaSecureCredentialProvider {
-
- private static Log LOG = LogFactory.getLog(XaSecureCredentialProvider.class);
-
- private static XaSecureCredentialProvider me = null;
-
-
- public static XaSecureCredentialProvider getInstance() {
- if ( me == null) {
- synchronized(XaSecureCredentialProvider.class) {
- XaSecureCredentialProvider temp = me;
- if ( temp == null){
- me = new XaSecureCredentialProvider();
- }
- }
- }
- return me;
- }
-
- public char[] getCredentialString(String url, String alias) {
- List<CredentialProvider> providers = getCredentialProviders(url);
-
- if(providers != null) {
- for( CredentialProvider provider: providers) {
- try {
- CredentialProvider.CredentialEntry credEntry = provider.getCredentialEntry(alias);
-
- if (credEntry != null) {
- return credEntry.getCredential();
- }
- } catch(Exception ie) {
- LOG.error("Unable to get the Credential Provider from the Configuration", ie);
- }
- }
- }
- return null;
- }
-
- List<CredentialProvider> getCredentialProviders(String url){
- try {
- Configuration conf = new Configuration();
-
- conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, url);
-
- return CredentialProviderFactory.getProviders(conf);
- } catch(Exception ie) {
- LOG.error("Unable to get the Credential Provider from the Configuration", ie);
- }
- return null;
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-cred/src/main/java/org/apache/ranger/authorization/hadoop/utils/RangerCredentialProvider.java
----------------------------------------------------------------------
diff --git a/agents-cred/src/main/java/org/apache/ranger/authorization/hadoop/utils/RangerCredentialProvider.java b/agents-cred/src/main/java/org/apache/ranger/authorization/hadoop/utils/RangerCredentialProvider.java
new file mode 100644
index 0000000..ebfcc45
--- /dev/null
+++ b/agents-cred/src/main/java/org/apache/ranger/authorization/hadoop/utils/RangerCredentialProvider.java
@@ -0,0 +1,84 @@
+/*
+ * 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.authorization.hadoop.utils;
+
+import java.lang.String;
+import java.util.List;
+import java.io.IOException;
+
+import org.apache.hadoop.security.alias.CredentialProvider;
+import org.apache.hadoop.security.alias.CredentialProviderFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+
+public class RangerCredentialProvider {
+
+ private static Log LOG = LogFactory.getLog(RangerCredentialProvider.class);
+
+ private static RangerCredentialProvider me = null;
+
+
+ public static RangerCredentialProvider getInstance() {
+ if ( me == null) {
+ synchronized(RangerCredentialProvider.class) {
+ RangerCredentialProvider temp = me;
+ if ( temp == null){
+ me = new RangerCredentialProvider();
+ }
+ }
+ }
+ return me;
+ }
+
+ public char[] getCredentialString(String url, String alias) {
+ List<CredentialProvider> providers = getCredentialProviders(url);
+
+ if(providers != null) {
+ for( CredentialProvider provider: providers) {
+ try {
+ CredentialProvider.CredentialEntry credEntry = provider.getCredentialEntry(alias);
+
+ if (credEntry != null) {
+ return credEntry.getCredential();
+ }
+ } catch(Exception ie) {
+ LOG.error("Unable to get the Credential Provider from the Configuration", ie);
+ }
+ }
+ }
+ return null;
+ }
+
+ List<CredentialProvider> getCredentialProviders(String url){
+ try {
+ Configuration conf = new Configuration();
+
+ conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, url);
+
+ return CredentialProviderFactory.getProviders(conf);
+ } catch(Exception ie) {
+ LOG.error("Unable to get the Credential Provider from the Configuration", ie);
+ }
+ return null;
+ }
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-cred/src/test/java/com/xasecure/authorization/hadoop/utils/XaSecureCredentialProviderTest.java
----------------------------------------------------------------------
diff --git a/agents-cred/src/test/java/com/xasecure/authorization/hadoop/utils/XaSecureCredentialProviderTest.java b/agents-cred/src/test/java/com/xasecure/authorization/hadoop/utils/XaSecureCredentialProviderTest.java
deleted file mode 100644
index 4877c57..0000000
--- a/agents-cred/src/test/java/com/xasecure/authorization/hadoop/utils/XaSecureCredentialProviderTest.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/**
- * 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 com.xasecure.authorization.hadoop.utils;
-
-import java.util.List;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.After;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.security.alias.CredentialShell;
-import org.apache.hadoop.security.alias.CredentialProvider;
-
-public class XaSecureCredentialProviderTest {
- private final String keystoreFile = System.getProperty("user.home")+"/testkeystore.jceks";
- private String[] argsCreate = {"create", "TestCredential001", "-value", "PassworD123", "-provider", "jceks://file" + keystoreFile};
- private String[] argsDelete = {"delete", "TestCredential001", "-provider", "jceks://file" + keystoreFile};
- private String url = "jceks://file" + keystoreFile;
- XaSecureCredentialProvider cp = null;
- List<CredentialProvider> providers = null;
-
- @Before
- public void setup() throws Exception {
- int ret;
- Configuration conf = new Configuration();
- CredentialShell cs = new CredentialShell();
- cs.setConf(conf);
- try {
- ret =cs.run(argsCreate);
- } catch (Exception e) {
- throw e;
- }
- assertEquals(0,ret);
- }
-
- @Test
- public void testCredentialProvider() {
- //test credential provider is registered and return credential providers.
- cp = new XaSecureCredentialProvider();
- providers = cp.getCredentialProviders(url);
- if (providers != null) {
- assertTrue(url.equals(providers.get(0).toString()));
- }
- }
-
- @Test
- public void testCredentialString() {
- //test credential provider created is returning the correct credential string.
- cp = new XaSecureCredentialProvider();
- providers = cp.getCredentialProviders(url);
- if (providers != null) {
- assertTrue("PassworD123".equals(new String(cp.getCredentialString(url,"TestCredential001"))));
- }
- }
-
-
- @After
- public void teardown() throws Exception {
- int ret;
- Configuration conf = new Configuration();
- CredentialShell cs = new CredentialShell();
- cs.setConf(conf);
- try {
- ret =cs.run(argsDelete);
- } catch (Exception e) {
- throw e;
- }
- assertEquals(0,ret);
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-cred/src/test/java/org/apache/ranger/authorization/hadoop/utils/RangerCredentialProviderTest.java
----------------------------------------------------------------------
diff --git a/agents-cred/src/test/java/org/apache/ranger/authorization/hadoop/utils/RangerCredentialProviderTest.java b/agents-cred/src/test/java/org/apache/ranger/authorization/hadoop/utils/RangerCredentialProviderTest.java
new file mode 100644
index 0000000..a9dafba
--- /dev/null
+++ b/agents-cred/src/test/java/org/apache/ranger/authorization/hadoop/utils/RangerCredentialProviderTest.java
@@ -0,0 +1,92 @@
+/**
+ * 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.authorization.hadoop.utils;
+
+import java.util.List;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.After;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.security.alias.CredentialShell;
+import org.apache.hadoop.security.alias.CredentialProvider;
+import org.apache.ranger.authorization.hadoop.utils.RangerCredentialProvider;
+
+public class RangerCredentialProviderTest {
+ private final String keystoreFile = System.getProperty("user.home")+"/testkeystore.jceks";
+ private String[] argsCreate = {"create", "TestCredential001", "-value", "PassworD123", "-provider", "jceks://file" + keystoreFile};
+ private String[] argsDelete = {"delete", "TestCredential001", "-provider", "jceks://file" + keystoreFile};
+ private String url = "jceks://file" + keystoreFile;
+ RangerCredentialProvider cp = null;
+ List<CredentialProvider> providers = null;
+
+ @Before
+ public void setup() throws Exception {
+ int ret;
+ Configuration conf = new Configuration();
+ CredentialShell cs = new CredentialShell();
+ cs.setConf(conf);
+ try {
+ ret =cs.run(argsCreate);
+ } catch (Exception e) {
+ throw e;
+ }
+ assertEquals(0,ret);
+ }
+
+ @Test
+ public void testCredentialProvider() {
+ //test credential provider is registered and return credential providers.
+ cp = new RangerCredentialProvider();
+ providers = cp.getCredentialProviders(url);
+ if (providers != null) {
+ assertTrue(url.equals(providers.get(0).toString()));
+ }
+ }
+
+ @Test
+ public void testCredentialString() {
+ //test credential provider created is returning the correct credential string.
+ cp = new RangerCredentialProvider();
+ providers = cp.getCredentialProviders(url);
+ if (providers != null) {
+ assertTrue("PassworD123".equals(new String(cp.getCredentialString(url,"TestCredential001"))));
+ }
+ }
+
+
+ @After
+ public void teardown() throws Exception {
+ int ret;
+ Configuration conf = new Configuration();
+ CredentialShell cs = new CredentialShell();
+ cs.setConf(conf);
+ try {
+ ret =cs.run(argsDelete);
+ } catch (Exception e) {
+ throw e;
+ }
+ assertEquals(0,ret);
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/main/java/com/xasecure/pdp/config/ConfigWatcher.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/main/java/com/xasecure/pdp/config/ConfigWatcher.java b/agents-impl/src/main/java/com/xasecure/pdp/config/ConfigWatcher.java
deleted file mode 100644
index f510328..0000000
--- a/agents-impl/src/main/java/com/xasecure/pdp/config/ConfigWatcher.java
+++ /dev/null
@@ -1,543 +0,0 @@
-/**
- * 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 com.xasecure.pdp.config;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.security.KeyManagementException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.SecureRandom;
-import java.security.UnrecoverableKeyException;
-import java.security.cert.CertificateException;
-
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.conf.Configuration;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.sun.jersey.api.client.Client;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.WebResource;
-import com.sun.jersey.api.client.config.ClientConfig;
-import com.sun.jersey.api.client.config.DefaultClientConfig;
-import com.sun.jersey.client.urlconnection.HTTPSProperties;
-import com.xasecure.authorization.hadoop.config.XaSecureConfiguration;
-import com.xasecure.pdp.config.gson.PolicyExclusionStrategy;
-import com.xasecure.pdp.constants.XaSecureConstants;
-import com.xasecure.pdp.model.PolicyContainer;
-import com.xasecure.authorization.hadoop.utils.XaSecureCredentialProvider;
-
-public abstract class ConfigWatcher extends Thread {
-
- private static final Log LOG = LogFactory.getLog(ConfigWatcher.class);
-
- public static final String EXPECTED_MIME_TYPE = "application/json" ;
-
- // public static final String EXPECTED_MIME_TYPE = "application/octet-stream";
-
- private static final String LASTUPDATED_PARAM = "epoch";
- private static final String POLICY_COUNT_PARAM = "policyCount";
- private static final String AGENT_NAME_PARAM = "agentId" ;
-
- private static final int MAX_AGENT_NAME_LEN = 255 ;
-
-
- private String url;
-
- private long intervalInMilliSeconds;
-
- private long lastModifiedTime = 0;
-
- private boolean shutdownFlag = false;
-
- private String lastStoredFileName = null;
-
- protected PolicyContainer policyContainer = null;
-
- private static PolicyExclusionStrategy policyExclusionStrategy = new PolicyExclusionStrategy();
-
- private static XaSecureCredentialProvider xasecurecp = null;
-
-
- public abstract void doOnChange();
-
- private String keyStoreFile = null ;
- private String keyStoreFilepwd = null;
- private String keyStoreURL = null;
- private String keyStoreAlias = null;
- private String trustStoreFile = null ;
- private String trustStoreFilepwd = null ;
- private String trustStoreURL = null;
- private String trustStoreAlias = null;
- private String keyStoreType = null ;
- private String trustStoreType = null ;
- private SSLContext sslContext = null ;
- private HostnameVerifier hv = null ;
- private String agentName = "unknown" ;
-
- private String sslConfigFileName = null ;
-
- public boolean policyCacheLoadedOnce = false;
-
- public boolean cacheModfied = false;
-
- public ConfigWatcher(String url, long aIntervalInMilliSeconds,String sslConfigFileName,String lastStoredFileName) {
- super("XaSecureConfigURLWatcher");
- setDaemon(true);
- this.url = url;
- intervalInMilliSeconds = aIntervalInMilliSeconds;
- this.sslConfigFileName = sslConfigFileName ;
- this.agentName = getAgentName(this.url) ;
- this.lastStoredFileName = lastStoredFileName;
- if (LOG.isInfoEnabled()) {
- LOG.info("Creating PolicyRefreshser with url: " + url +
- ", refreshInterval(milliSeconds): " + aIntervalInMilliSeconds +
- ", sslConfigFileName: " + sslConfigFileName +
- ", lastStoredFileName: " + lastStoredFileName);
- }
- init();
- validateAndRun();
- LOG.debug("Created new ConfigWatcher for URL [" + url + "]");
- }
-
-
- public void init() {
- if (sslConfigFileName != null) {
- LOG.debug("Loading SSL Configuration from [" + sslConfigFileName + "]");
- InputStream in = null ;
- try {
- Configuration conf = new Configuration() ;
- in = getFileInputStream(sslConfigFileName) ;
- if (in != null) {
- conf.addResource(in);
- }
-
- xasecurecp = XaSecureCredentialProvider.getInstance();
-
- keyStoreFile = conf.get(XaSecureConstants.XASECURE_POLICYMGR_CLIENT_KEY_FILE);
-
- keyStoreURL=conf.get(XaSecureConstants.XASECURE_POLICYMGR_CLIENT_KEY_FILE_CREDENTIAL);
- keyStoreAlias=XaSecureConstants.XASECURE_POLICYMGR_CLIENT_KEY_FILE_CREDENTIAL_ALIAS;
-
- char[] v_keyStoreFilePwd = getCredential(keyStoreURL,keyStoreAlias);
- if ( v_keyStoreFilePwd == null ) {
- keyStoreFilepwd = null;
- } else {
- keyStoreFilepwd = new String(v_keyStoreFilePwd);
- }
-
- trustStoreFile = conf.get(XaSecureConstants.XASECURE_POLICYMGR_TRUSTSTORE_FILE);
-
- trustStoreURL=conf.get(XaSecureConstants.XASECURE_POLICYMGR_TRUSTSTORE_FILE_CREDENTIAL);
- trustStoreAlias=XaSecureConstants.XASECURE_POLICYMGR_TRUSTSTORE_FILE_CREDENTIAL_ALIAS;
-
- char[] v_TrustStoreFilePwd = getCredential(trustStoreURL,trustStoreAlias);
- if ( v_TrustStoreFilePwd == null ) {
- trustStoreFilepwd = null;
- } else {
- trustStoreFilepwd = new String(v_TrustStoreFilePwd);
- }
-
-
- keyStoreType = conf.get(XaSecureConstants.XASECURE_POLICYMGR_CLIENT_KEY_FILE_TYPE, XaSecureConstants.XASECURE_POLICYMGR_CLIENT_KEY_FILE_TYPE_DEFAULT);
- trustStoreType = conf.get(XaSecureConstants.XASECURE_POLICYMGR_TRUSTSTORE_FILE_TYPE, XaSecureConstants.XASECURE_POLICYMGR_TRUSTSTORE_FILE_TYPE_DEFAULT);
- }
- catch(IOException ioe) {
- LOG.error("Unable to load SSL Config FileName: [" + sslConfigFileName + "]", ioe);
- }
- finally {
- if (in != null) {
- try {
- in.close() ;
- } catch (IOException e) {
- LOG.error("Unable to close SSL Config FileName: [" + sslConfigFileName + "]", e) ;
- }
- }
- }
-
- LOG.debug("Keystore filename:[" + keyStoreFile + "]");
- LOG.debug("TrustStore filename:[" + trustStoreFile + "]");
-
- }
- }
-
- public String getURL() {
- return url;
- }
-
- public long getIntervalInMilliSeconds() {
- return intervalInMilliSeconds;
- }
-
- public long getLastModifiedTime() {
- return lastModifiedTime;
- }
-
- public void run() {
- while (!shutdownFlag) {
- validateAndRun();
- try {
- Thread.sleep(intervalInMilliSeconds);
- } catch (InterruptedException e) {
- LOG.error("Unable to complete sleep for [" + intervalInMilliSeconds + "]", e);
- }
- }
- }
-
- private void validateAndRun() {
- if (isFileChanged()) {
- LOG.debug("Policy has been changed from " + url + " ... RELOADING");
- try {
- doOnChange();
- } catch (Exception e) {
- LOG.error("Unable to complete doOnChange() method on file change [" + url + "]", e);
- }
- } else {
- LOG.debug("No Change found in the policy from " + url);
- }
- }
-
- public boolean iscacheModfied() {
- return cacheModfied;
- }
-
- private boolean isFileChanged() {
- boolean isChanged = false;
-
- cacheModfied = false;
- try {
-
- Client client = null;
- ClientResponse response = null;
-
- try {
-
- int policyCount = getPolicyCount(policyContainer);
-
- if (url.contains("https")) {
- // build SSL Client
- client = buildSSLClient();
- }
-
- if (client == null) {
- client = Client.create();
- }
-
- WebResource webResource = client.resource(url)
- .queryParam(LASTUPDATED_PARAM, String.valueOf(lastModifiedTime))
- .queryParam(POLICY_COUNT_PARAM, String.valueOf(policyCount))
- .queryParam(AGENT_NAME_PARAM, agentName);
-
- response = webResource.accept(EXPECTED_MIME_TYPE).get(ClientResponse.class);
-
-
- if (response != null) {
-
- boolean responsePresent = true;
- int responseStatus = response.getStatus();
-
- if ( fetchPolicyfromCahce(responsePresent,responseStatus,lastStoredFileName) ) {
- /* If the response is other than 200 and 304 load the policy from the cache */
- isChanged = true;
-
- } else {
- /* If Policy Manager is available fetch the policy from it */
- if (response.getStatus() == 200) {
- String jsonString = response.getEntity(String.class);
- Gson gson = new GsonBuilder().setPrettyPrinting().addDeserializationExclusionStrategy(policyExclusionStrategy).create();
- PolicyContainer newPolicyContainer = gson.fromJson(jsonString, PolicyContainer.class);
- if ((newPolicyContainer.getLastUpdatedTimeInEpoc() > lastModifiedTime) || (getPolicyCount(newPolicyContainer) != policyCount)) {
- policyContainer = newPolicyContainer;
- lastModifiedTime = policyContainer.getLastUpdatedTimeInEpoc();
- isChanged = true;
- policyCacheLoadedOnce = false;
- cacheModfied = true;
- if (LOG.isDebugEnabled()) {
- LOG.debug("Got response: 200 with {change in lastupdatedTime}\n" + gson.toJson(newPolicyContainer));
- }
- } else {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Got response: 200 with {no-change in lastupdatedTime}\n" + gson.toJson(newPolicyContainer));
- }
- isChanged = false;
- }
- } else if (response.getStatus() == 304) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Got response: 304 ");
- }
- isChanged = false; // No Change has been there since our
- // earlier request
- } else {
- LOG.error("Unable to get a valid response for isFileChanged() call for [" + url + "] = response code found [" + response.getStatus() + "]");
- }
- }
-
- } else {
- LOG.error("Unable to get a valid response for isFileChanged() call for [" + url + "] - got null response.");
- // force the policy update to get fresh copy
- lastModifiedTime = 0;
- }
-
- } finally {
- if (response != null) {
- response.close();
- }
- if (client != null) {
- client.destroy();
- }
- }
- } catch (Throwable t) {
-
- boolean responsePresent = false;
- int responseStatus = -1;
- if (LOG.isDebugEnabled()) {
- LOG.debug("Policy Manager Failed",t);
- }
- if ( fetchPolicyfromCahce(responsePresent,responseStatus,lastStoredFileName) ) {
- /* Successfully found the Policy Cache file and loaded */
- isChanged = false;
- } else {
- LOG.error("Unable to complete isFileChanged() call for [" + url + "]", t);
- // force the policy update to get fresh copy
- lastModifiedTime = 0;
- LOG.error("Policy file Cache not found..");
- throw new RuntimeException("Unable to find Enterprise Policy Storage");
- }
-
- } finally {
- if (isChanged) {
- LOG.info("URL: [" + url + "], isModified: " + isChanged + ", lastModifiedTime:" + lastModifiedTime);
- } else if (LOG.isDebugEnabled()) {
- LOG.debug("URL: [" + url + "], isModified: " + isChanged + ", lastModifiedTime:" + lastModifiedTime);
- }
- }
- return isChanged;
- }
-
- public PolicyContainer getPolicyContainer() {
- return policyContainer;
- }
-
- private int getPolicyCount(PolicyContainer aPolicyContainer) {
- return (aPolicyContainer == null ? 0 : (aPolicyContainer.getAcl() == null ? 0 : aPolicyContainer.getAcl().size()));
- }
-
-
- public synchronized Client buildSSLClient() {
- Client client = null;
- try {
-
- ClientConfig config = new DefaultClientConfig();
-
- if (sslContext == null) {
-
- KeyManager[] kmList = null;
- TrustManager[] tmList = null;
-
- if (keyStoreFile != null && keyStoreFilepwd != null) {
-
- KeyStore keyStore = KeyStore.getInstance(keyStoreType);
- InputStream in = null ;
- try {
- in = getFileInputStream(keyStoreFile) ;
- if (in == null) {
- LOG.error("Unable to obtain keystore from file [" + keyStoreFile + "]");
- return client ;
- }
- keyStore.load(in, keyStoreFilepwd.toCharArray());
- KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(XaSecureConstants.XASECURE_SSL_KEYMANAGER_ALGO_TYPE);
- keyManagerFactory.init(keyStore, keyStoreFilepwd.toCharArray());
- kmList = keyManagerFactory.getKeyManagers();
- }
- finally {
- if (in != null) {
- in.close();
- }
- }
-
- }
-
- if (trustStoreFile != null && trustStoreFilepwd != null) {
-
- KeyStore trustStore = KeyStore.getInstance(trustStoreType);
- InputStream in = null ;
- try {
- in = getFileInputStream(trustStoreFile) ;
- if (in == null) {
- LOG.error("Unable to obtain keystore from file [" + trustStoreFile + "]");
- return client ;
- }
- trustStore.load(in, trustStoreFilepwd.toCharArray());
- TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(XaSecureConstants.XASECURE_SSL_TRUSTMANAGER_ALGO_TYPE);
- trustManagerFactory.init(trustStore);
- tmList = trustManagerFactory.getTrustManagers();
- }
- finally {
- if (in != null) {
- in.close() ;
- }
- }
- }
-
- sslContext = SSLContext.getInstance(XaSecureConstants.XASECURE_SSL_CONTEXT_ALGO_TYPE);
-
- sslContext.init(kmList, tmList, new SecureRandom());
-
- hv = new HostnameVerifier() {
- public boolean verify(String urlHostName, SSLSession session) {
- return session.getPeerHost().equals(urlHostName);
- }
- };
-
- }
-
- config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(hv, sslContext));
-
- client = Client.create(config);
-
- } catch (KeyStoreException e) {
- LOG.error("Unable to obtain from KeyStore", e);
- } catch (NoSuchAlgorithmException e) {
- LOG.error("SSL algorithm is available in the environment", e);
- } catch (CertificateException e) {
- LOG.error("Unable to obtain the requested certification ", e);
- } catch (FileNotFoundException e) {
- LOG.error("Unable to find the necessary SSL Keystore and TrustStore Files", e);
- } catch (IOException e) {
- LOG.error("Unable to read the necessary SSL Keystore and TrustStore Files", e);
- } catch (KeyManagementException e) {
- LOG.error("Unable to initials the SSLContext", e);
- } catch (UnrecoverableKeyException e) {
- LOG.error("Unable to recover the key from keystore", e);
- }
- return client;
- }
-
- private InputStream getFileInputStream(String fileName) throws IOException {
- InputStream in = null ;
-
- File f = new File(fileName) ;
-
- if (f.exists()) {
- in = new FileInputStream(f) ;
- }
- else {
- in = ClassLoader.getSystemResourceAsStream(fileName) ;
- }
- return in ;
- }
-
- public static String getAgentName(String aUrl) {
- String hostName = null ;
- String repoName = null ;
- try {
- hostName = InetAddress.getLocalHost().getHostName() ;
- } catch (UnknownHostException e) {
- LOG.error("ERROR: Unable to find hostname for the agent ", e);
- hostName = "unknownHost" ;
- }
-
- String[] tokens = aUrl.split("/") ;
-
- if ( tokens.length > 0 ) {
- repoName = tokens[tokens.length-1] ;
- }
- else {
- repoName = "unknownRepo" ;
- }
-
- String agentName = hostName + "-" + repoName ;
-
- if (agentName.length() > MAX_AGENT_NAME_LEN ) {
- agentName = agentName.substring(0,MAX_AGENT_NAME_LEN) ;
- }
-
- return agentName ;
- }
-
- private boolean fetchPolicyfromCahce( boolean responsePresent, int responseStatus, String lastStoredFileName){
-
- boolean cacheFound = false;
-
- if ( ( responsePresent == false ) || ( responseStatus != 200 && responseStatus != 304) ) {
-
- /* Policy Manager not available read the policy from the last enforced one */
-
- if (policyCacheLoadedOnce) {
- cacheFound = true;
- return cacheFound;
- }
-
- try {
- /* read the last stored policy file and load the PolicyContainer */
- LOG.info("Policy Manager not available, using the last stored Policy File" + this.lastStoredFileName );
- LOG.debug("LastStoredFileName when policymgr was available" + this.lastStoredFileName);
-
- BufferedReader jsonString = new BufferedReader(new FileReader(this.lastStoredFileName));
- Gson gson = new GsonBuilder().setPrettyPrinting().addDeserializationExclusionStrategy(policyExclusionStrategy).create();
- PolicyContainer newPolicyContainer = gson.fromJson(jsonString, PolicyContainer.class);
- policyContainer = newPolicyContainer;
- lastModifiedTime = policyContainer.getLastUpdatedTimeInEpoc();
- if (LOG.isDebugEnabled()) {
- LOG.debug("Policy Manager not available.Got response =" + responseStatus +"\n" + gson.toJson(newPolicyContainer));
- }
-
- cacheFound = true;
- policyCacheLoadedOnce = true;
-
- } catch( FileNotFoundException fe ){
-
- /* unable to get the last stored policy, raise warning for unavailability of policy cache file and continue...*/
- if ( this.lastStoredFileName == null ) {
- LOG.info("Policy cache file not found...XAagent authorization not enabled");
- }
- else {
- LOG.info("Unable to access Policy cache file...XAagent authorization not enabled");
- }
- }
-
- }
-
- return cacheFound;
- }
-
- private char[] getCredential(String url, String alias) {
- char[] credStr=xasecurecp.getCredentialString(url,alias);
- return credStr;
- }
-}
-
[09/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/biz/AssetMgr.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/AssetMgr.java b/security-admin/src/main/java/org/apache/ranger/biz/AssetMgr.java
new file mode 100644
index 0000000..3aebe39
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/biz/AssetMgr.java
@@ -0,0 +1,3218 @@
+/*
+ * 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.biz;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.UnknownHostException;
+import java.security.cert.X509Certificate;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.TimeUnit;
+
+import javax.naming.InvalidNameException;
+import javax.naming.ldap.LdapName;
+import javax.naming.ldap.Rdn;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.lang.StringUtils;
+import org.apache.hadoop.hive.serde2.lazybinary.LazyBinaryUtils.VLong;
+import org.apache.hive.com.esotericsoftware.minlog.Log;
+import org.apache.log4j.Logger;
+import org.apache.ranger.common.AppConstants;
+import org.apache.ranger.common.ContextUtil;
+import org.apache.ranger.common.DateUtil;
+import org.apache.ranger.common.JSONUtil;
+import org.apache.ranger.common.MessageEnums;
+import org.apache.ranger.common.PropertiesUtil;
+import org.apache.ranger.common.SearchCriteria;
+import org.apache.ranger.common.StringUtil;
+import org.apache.ranger.common.TimedEventUtil;
+import org.apache.ranger.common.UserSessionBase;
+import org.apache.ranger.common.XACommonEnums;
+import org.apache.ranger.common.XAConstants;
+import org.apache.ranger.db.XADaoManager;
+import org.apache.ranger.entity.XXAsset;
+import org.apache.ranger.entity.XXAuditMap;
+import org.apache.ranger.entity.XXGroup;
+import org.apache.ranger.entity.XXPermMap;
+import org.apache.ranger.entity.XXPolicyExportAudit;
+import org.apache.ranger.entity.XXPortalUser;
+import org.apache.ranger.entity.XXPortalUserRole;
+import org.apache.ranger.entity.XXResource;
+import org.apache.ranger.entity.XXTrxLog;
+import org.apache.ranger.entity.XXUser;
+import org.apache.ranger.hadoop.client.HadoopFS;
+import org.apache.ranger.hadoop.client.exceptions.HadoopException;
+import org.apache.ranger.hbase.client.HBaseClient;
+import org.apache.ranger.hive.client.HiveClient;
+import org.apache.ranger.knox.client.KnoxClient;
+import org.apache.ranger.service.XAccessAuditService;
+import org.apache.ranger.service.XAuditMapService;
+import org.apache.ranger.service.XGroupService;
+import org.apache.ranger.service.XPermMapService;
+import org.apache.ranger.service.XPolicyService;
+import org.apache.ranger.service.XTrxLogService;
+import org.apache.ranger.service.XUserService;
+import org.apache.ranger.storm.client.StormClient;
+import org.apache.ranger.util.RestUtil;
+import org.apache.ranger.view.VXAccessAuditList;
+import org.apache.ranger.view.VXAsset;
+import org.apache.ranger.view.VXAuditMap;
+import org.apache.ranger.view.VXAuditMapList;
+import org.apache.ranger.view.VXLong;
+import org.apache.ranger.view.VXMessage;
+import org.apache.ranger.view.VXPermMap;
+import org.apache.ranger.view.VXPermMapList;
+import org.apache.ranger.view.VXPolicy;
+import org.apache.ranger.view.VXPolicyExportAuditList;
+import org.apache.ranger.view.VXResource;
+import org.apache.ranger.view.VXResourceList;
+import org.apache.ranger.view.VXResponse;
+import org.apache.ranger.view.VXStringList;
+import org.apache.ranger.view.VXTrxLog;
+import org.apache.ranger.view.VXTrxLogList;
+import org.apache.ranger.view.VXUser;
+import org.codehaus.jackson.JsonGenerationException;
+import org.codehaus.jackson.map.JsonMappingException;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.stereotype.Component;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.TransactionDefinition;
+import org.springframework.transaction.TransactionStatus;
+import org.springframework.transaction.support.TransactionCallback;
+import org.springframework.transaction.support.TransactionTemplate;
+
+@Component
+public class AssetMgr extends AssetMgrBase {
+
+
+ @Autowired
+ XPermMapService xPermMapService;
+
+ @Autowired
+ XAuditMapService xAuditMapService;
+
+ @Autowired
+ JSONUtil jsonUtil;
+
+ @Autowired
+ AssetConnectionMgr assetConnectionMgr;
+
+ @Autowired
+ XABizUtil msBizUtil;
+
+ @Autowired
+ StringUtil stringUtil;
+
+ @Autowired
+ XADaoManager xADaoManager;
+
+ @Autowired
+ XUserService xUserService;
+
+ @Autowired
+ XABizUtil xaBizUtil;
+
+ @Autowired
+ XTrxLogService xTrxLogService;
+
+ @Autowired
+ XAccessAuditService xAccessAuditService;
+
+ @Autowired
+ XGroupService xGroupService;
+
+ @Autowired
+ XUserMgr xUserMgr;
+
+ @Autowired
+ @Qualifier(value = "transactionManager")
+ PlatformTransactionManager txManager;
+
+ @Autowired
+ XPolicyService xPolicyService;
+
+ static Logger logger = Logger.getLogger(AssetMgr.class);
+
+ @Override
+ public VXResource createXResource(VXResource vXResource) {
+ UserSessionBase session = ContextUtil.getCurrentUserSession();
+ if (session == null) {
+ logger.error("Trying to create/update policy without log-in.");
+ throw restErrorUtil.create403RESTException("Resource "
+ + "creation/updation not allowed");
+ }
+
+ Long assetId = vXResource.getAssetId();
+ XXAsset xAsset = xADaoManager.getXXAsset().getById(assetId);
+ if (xAsset == null) {
+ logger.error("Repository not found for assetId : " + assetId);
+ throw restErrorUtil.create403RESTException("Repository for which"
+ + " the policy is created, doesn't exist.");
+ }
+
+ if(xAsset.getActiveStatus()==XACommonEnums.ACT_STATUS_DISABLED){
+ if(!session.isUserAdmin()){
+ logger.error("Trying to create/update policy in disabled repository");
+ throw restErrorUtil.createRESTException("Resource "
+ + "creation/updation not allowed in disabled repository",MessageEnums.OPER_NO_PERMISSION);
+ }
+ }
+ // Create resource path for HIVE/Hbase policy.
+ if (xAsset.getAssetType() == AppConstants.ASSET_HIVE) {
+ createResourcePathForHive(vXResource);
+ } else if (xAsset.getAssetType() == AppConstants.ASSET_HBASE) {
+ createResourcePathForHbase(vXResource);
+ }else if (xAsset.getAssetType() == AppConstants.ASSET_KNOX) {
+ createResourcePathForKnox(vXResource);
+ }else if (xAsset.getAssetType() == AppConstants.ASSET_STORM) {
+ createResourcePathForStorm(vXResource);
+ }
+
+ String resourceName = vXResource.getName();
+ String[] orgResNameList = stringUtil.split(resourceName, ",");
+ List<String> newResNameList = new ArrayList<String>();
+ for(String resName : orgResNameList) {
+ if(resName.length() > 1 && (resName.substring(resName.length()-1).equalsIgnoreCase("/"))) {
+ resName = resName.substring(0, resName.length()-1);
+ newResNameList.add(resName);
+ logger.info("Resource Name is not valid : " +resName + " Ignoring last /");
+ } else {
+ newResNameList.add(resName);
+ }
+ }
+ String updResName = StringUtils.join(newResNameList, ",");
+ vXResource.setName(updResName);
+
+ SearchCriteria searchCriteria=new SearchCriteria();
+ searchCriteria.getParamList().put("assetId", vXResource.getAssetId());
+ searchCriteria.getParamList().put("fullname", vXResource.getName());
+
+ if (xAsset.getAssetType() == AppConstants.ASSET_HIVE) {
+ if(stringUtil.isEmpty(vXResource.getUdfs())) {
+ searchCriteria.addParam("tableType", vXResource.getTableType());
+ searchCriteria.addParam("columnType", vXResource.getColumnType());
+ } else {
+ searchCriteria.addParam("udfs", vXResource.getUdfs());
+ }
+ } else if (xAsset.getAssetType() == AppConstants.ASSET_HDFS) {
+ searchCriteria.addParam("isRecursive", vXResource.getIsRecursive());
+ }
+
+ VXResourceList vXResourceList=xResourceService.searchXResources(searchCriteria);
+ if(vXResourceList!=null && vXResourceList.getListSize()>0){
+ logger.error("policy already exist with resource "+vXResource.getName());
+ throw restErrorUtil.createRESTException("policy already exist with resource "
+ +vXResource.getName(),MessageEnums.ERROR_DUPLICATE_OBJECT);
+ }
+
+ VXResponse vXResponse = xaBizUtil.hasPermission(vXResource,
+ AppConstants.XA_PERM_TYPE_ADMIN);
+ if (vXResponse.getStatusCode() == VXResponse.STATUS_ERROR) {
+ throw restErrorUtil.createRESTException(vXResponse);
+ }
+
+ if (vXResource.getCheckParentPermission() != XAConstants.BOOL_FALSE) {
+ // check parent access for user and group
+ xResourceService.checkAccess(vXResource);
+ }
+ vXResourceList=null;
+ if(vXResource.getPolicyName()!=null && !vXResource.getPolicyName().trim().isEmpty()){
+ searchCriteria=new SearchCriteria();
+ searchCriteria.getParamList().put("fullPolicyName", vXResource.getPolicyName());
+ vXResourceList=xResourceService.searchXResourcesWithoutLogin(searchCriteria);
+ //if policyname already exist then set null to generate from system
+ if(vXResourceList!=null && vXResourceList.getListSize()>0){
+ logger.error("policy already exist with name "+vXResource.getPolicyName());
+ //logger.info("A system generated policy name shall be assigned to "+vXResource.getPolicyName());
+ //vXResource.setPolicyName(null);
+ throw restErrorUtil.createRESTException("policy already exist with name "
+ +vXResource.getPolicyName(),MessageEnums.ERROR_DUPLICATE_OBJECT);
+ }
+ }
+
+ int tempPoliciesCount=0;
+ String tempPolicyName=null;
+ vXResourceList=null;
+ if(vXResource.getPolicyName()==null ||vXResource.getPolicyName().trim().isEmpty()){
+ searchCriteria=new SearchCriteria();
+ searchCriteria.getParamList().put("assetId", vXResource.getAssetId());
+ vXResourceList=xResourceService.searchXResourcesWithoutLogin(searchCriteria);
+ if(vXResourceList!=null && vXResourceList.getListSize()>0){
+ tempPoliciesCount=vXResourceList.getListSize();
+ }
+ vXResourceList=null;
+ while(true){
+ tempPoliciesCount++;
+ tempPolicyName=xAsset.getName()+"-"+tempPoliciesCount+"-"+DateUtil.dateToString(DateUtil.getUTCDate(),"yyyyMMddHHmmss");
+ vXResource.setPolicyName(tempPolicyName);
+ searchCriteria=new SearchCriteria();
+ searchCriteria.getParamList().put("policyName", vXResource.getPolicyName());
+ vXResourceList=xResourceService.searchXResourcesWithoutLogin(searchCriteria);
+ //if policy name not exist then list will be empty and generated policyname will valid
+ if(vXResourceList==null|| vXResourceList.getListSize()==0){
+ break;
+ }
+ }
+ }
+
+
+ vXResource = xResourceService.createResource(vXResource);
+
+ List<VXPermMap> permMapList = vXResource.getPermMapList();
+ List<VXAuditMap> auditMapList = vXResource.getAuditList();
+
+ List<XXTrxLog> trxLogList = xResourceService.getTransactionLog(
+ vXResource, "create");
+ for (VXPermMap vXPermMap : permMapList) {
+ trxLogList.addAll(xPermMapService.getTransactionLog(vXPermMap,
+ "create"));
+ }
+ for (VXAuditMap vXAuditMap : auditMapList) {
+ trxLogList.addAll(xAuditMapService.getTransactionLog(vXAuditMap,
+ "create"));
+ }
+
+ xaBizUtil.createTrxLog(trxLogList);
+
+ return vXResource;
+ }
+
+ @Override
+ public VXResource updateXResource(VXResource vXResource) {
+
+ UserSessionBase currentUserSession = ContextUtil
+ .getCurrentUserSession();
+ if (currentUserSession == null) {
+ throw restErrorUtil.createRESTException("Resource updation not "
+ + "allowed",MessageEnums.OPER_NO_PERMISSION);
+ }
+
+ Long assetId = vXResource.getAssetId();
+ XXAsset xAsset = xADaoManager.getXXAsset().getById(assetId);
+ if (xAsset == null) {
+ throw restErrorUtil.createRESTException("The repository for which "
+ + "you're updating policy, doesn't exist.",
+ MessageEnums.INVALID_INPUT_DATA);
+ }
+
+ if(xAsset.getActiveStatus()==XACommonEnums.STATUS_DISABLED){
+ if(!currentUserSession.isUserAdmin()){
+ logger.error("Trying to update policy in disabled repository");
+ throw restErrorUtil.createRESTException("Resource "
+ + "updation not allowed in disabled repository",MessageEnums.OPER_NO_PERMISSION);
+ }
+ }
+
+ if (xAsset.getAssetType() == AppConstants.ASSET_HIVE) {
+ createResourcePathForHive(vXResource);
+ } else if (xAsset.getAssetType() == AppConstants.ASSET_HBASE) {
+ createResourcePathForHbase(vXResource);
+ }else if (xAsset.getAssetType() == AppConstants.ASSET_KNOX) {
+ createResourcePathForKnox(vXResource);
+ }else if (xAsset.getAssetType() == AppConstants.ASSET_STORM) {
+ createResourcePathForStorm(vXResource);
+ }
+
+ SearchCriteria searchCriteria = new SearchCriteria();
+ searchCriteria.getParamList().put("assetId", vXResource.getAssetId());
+ searchCriteria.getParamList().put("fullname", vXResource.getName());
+
+ if (xAsset.getAssetType() == AppConstants.ASSET_HIVE) {
+ if(stringUtil.isEmpty(vXResource.getUdfs())) {
+ searchCriteria.addParam("tableType", vXResource.getTableType());
+ searchCriteria.addParam("columnType", vXResource.getColumnType());
+ } else {
+ searchCriteria.addParam("udfs", vXResource.getUdfs());
+ }
+ } else if (xAsset.getAssetType() == AppConstants.ASSET_HDFS) {
+ searchCriteria.addParam("isRecursive", vXResource.getIsRecursive());
+ }
+
+ VXResourceList vXResourceList=xResourceService.searchXResourcesWithoutLogin(searchCriteria);
+ if(vXResourceList!=null && vXResourceList.getListSize()>0){
+ if(vXResource!=null && vXResource.getId()!=null){
+ for(VXResource vXResourceTemp :vXResourceList.getList()){
+ if(vXResourceTemp!=null && !(vXResource.getId().equals(vXResourceTemp.getId()))){
+ logger.error("policy already exists with name "+vXResource.getName());
+ throw restErrorUtil.createRESTException("policy already exists with name "
+ +vXResource.getName(),MessageEnums.ERROR_DUPLICATE_OBJECT);
+ }
+ }
+ }
+ }
+
+ VXResponse vXResponse = xaBizUtil.hasPermission(vXResource,
+ AppConstants.XA_PERM_TYPE_ADMIN);
+ if (vXResponse.getStatusCode() == VXResponse.STATUS_ERROR) {
+ throw restErrorUtil.createRESTException(vXResponse);
+ }
+
+ if (vXResource.getCheckParentPermission() != XAConstants.BOOL_FALSE) {
+ // check parent access for user and group
+ xResourceService.checkAccess(vXResource);
+ }
+
+ //policyName creation and validation logic start here
+ if(vXResource.getPolicyName()!=null && !vXResource.getPolicyName().trim().isEmpty()){
+ searchCriteria=new SearchCriteria();
+ searchCriteria.getParamList().put("fullPolicyName", vXResource.getPolicyName());
+ vXResourceList=xResourceService.searchXResourcesWithoutLogin(searchCriteria);
+ if(vXResourceList!=null && vXResourceList.getListSize()>0){
+ if(vXResource!=null && vXResource.getId()!=null){
+ for (VXResource newVXResource : vXResourceList.getList()) {
+ if(newVXResource!=null && newVXResource.getId()!=null){
+ if(!vXResource.getId().equals(newVXResource.getId()) && vXResource.getPolicyName().trim().equalsIgnoreCase((newVXResource.getPolicyName()!=null?newVXResource.getPolicyName().trim():newVXResource.getPolicyName()))){
+ logger.error("policy already exists with name "+vXResource.getPolicyName());
+// logger.info("A system generated policy name shall be assigned to "+vXResource.getPolicyName());
+// vXResource.setPolicyName(null);
+// break;
+ throw restErrorUtil.createRESTException("policy already exists with name "
+ +vXResource.getPolicyName(),MessageEnums.ERROR_DUPLICATE_OBJECT);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ int tempPoliciesCount=0;
+ int totalPoliciesCount=1;
+ String tempPolicyName=null;
+ vXResourceList=null;
+ if(vXResource!=null && (vXResource.getPolicyName()==null ||vXResource.getPolicyName().trim().isEmpty())){
+ searchCriteria=new SearchCriteria();
+ searchCriteria.getParamList().put("assetId", vXResource.getAssetId());
+ vXResourceList=xResourceService.searchXResourcesWithoutLogin(searchCriteria);
+ if(vXResourceList!=null && vXResourceList.getListSize()>0){
+ totalPoliciesCount=vXResourceList.getListSize();
+ tempPoliciesCount++;
+ for(VXResource newVXResource : vXResourceList.getList()) {
+ if(newVXResource!=null && newVXResource.getId()!=null){
+ if(vXResource.getId().equals(newVXResource.getId())){
+ break;
+ }
+ }
+ tempPoliciesCount++;
+ }
+ tempPolicyName=xAsset.getName()+"-"+tempPoliciesCount+"-"+DateUtil.dateToString(DateUtil.getUTCDate(),"yyyyMMddHHmmss");
+ vXResource.setPolicyName(tempPolicyName);
+ vXResourceList=null;
+ }else{
+ tempPoliciesCount++;
+ tempPolicyName=xAsset.getName()+"-"+tempPoliciesCount+"-"+DateUtil.dateToString(DateUtil.getUTCDate(),"yyyyMMddHHmmss");
+ vXResource.setPolicyName(tempPolicyName);
+ }
+ while(true){
+ searchCriteria=new SearchCriteria();
+ searchCriteria.getParamList().put("policyName", vXResource.getPolicyName());
+ vXResourceList=xResourceService.searchXResourcesWithoutLogin(searchCriteria);
+ if(vXResourceList==null || vXResourceList.getListSize()==0){
+ break;
+ }else{
+ tempPolicyName=xAsset.getName()+"-"+totalPoliciesCount+"-"+DateUtil.dateToString(DateUtil.getUTCDate(),"yyyyMMddHHmmss");
+ vXResource.setPolicyName(tempPolicyName);
+ }
+ }
+
+ }
+
+ //policyName creation and validation logic end here
+
+ XXResource xResouce = xADaoManager.getXXResource().getById(
+ vXResource.getId());
+
+ List<XXTrxLog> trxLogList = xResourceService.getTransactionLog(
+ vXResource, xResouce, "update");
+
+ VXResource resource = super.updateXResource(vXResource);
+
+ List<VXPermMap> newPermMapList = vXResource.getPermMapList();
+ searchCriteria = new SearchCriteria();
+ searchCriteria.addParam("resourceId", vXResource.getId());
+ VXPermMapList prevPermMaps = xPermMapService
+ .searchXPermMaps(searchCriteria);
+ List<VXPermMap> prevPermMapList = new ArrayList<VXPermMap>();
+ if (prevPermMaps != null) {
+ prevPermMapList = prevPermMaps.getVXPermMaps();
+ }
+
+ List<VXPermMap> permMaps = new ArrayList<VXPermMap>();
+ List<VXAuditMap> auditMaps = new ArrayList<VXAuditMap>();
+
+ List<VXPermMap> permMapsToDelete = new ArrayList<VXPermMap>();
+ List<VXAuditMap> auditMapsToDelete = new ArrayList<VXAuditMap>();
+
+ // Create and update permissions
+ if (newPermMapList != null) {
+ for (VXPermMap newObj : newPermMapList) {
+ if (newObj.getUserId() == null && newObj.getGroupId() == null
+ && !stringUtil.isEmpty(newObj.getUserName())) {
+ XXUser xxUser = xADaoManager.getXXUser().findByUserName(
+ newObj.getUserName());
+ if (xxUser != null) {
+ newObj.setUserId(xxUser.getId());
+ } else {
+ VXUser vxUser = new VXUser();
+ vxUser.setName(newObj.getUserName());
+ vxUser.setDescription(newObj.getUserName());
+ vxUser = xUserService.createResource(vxUser);
+ newObj.setUserId(vxUser.getId());
+ }
+ }
+ newObj.setResourceId(resource.getId());
+ if (newObj.getId() != null) {
+ /**
+ * Considering the new objects won't have id however the
+ * existing ones will have id.
+ */
+ for (VXPermMap oldObj : prevPermMapList) {
+ if (oldObj.getId().equals(newObj.getId())) {
+ if (oldObj.getPermType() != newObj.getPermType()) {
+ // This should never be the case because we're
+ // not supporting perm map update.
+ // doNothing...
+ logger.error(
+ "Invalid use case: shouldn't be happening, need to debug.",
+ new IllegalStateException());
+ break;
+ } else {
+ xPermMapService.updateResource(newObj);
+ trxLogList.addAll(xPermMapService
+ .getTransactionLog(newObj, oldObj,
+ "update"));
+ }
+ }
+ }
+ // newObj = xPermMapService.updateResource(newObj);
+ } else {
+ newObj = xPermMapService.createResource(newObj);
+ trxLogList.addAll(xPermMapService.getTransactionLog(newObj,
+ "create"));
+ }
+ permMaps.add(newObj);
+ }
+ }
+
+ // Delete old removed permissions
+ if (prevPermMapList != null) {
+ for (VXPermMap oldObj : prevPermMapList) {
+ boolean found = false;
+ if (newPermMapList != null) {
+ for (VXPermMap newObj : newPermMapList) {
+ if (newObj.getId() != null
+ && newObj.getId().equals(oldObj.getId())) {
+ found = true;
+ break;
+ }
+ }
+ }
+ if (!found) {
+ trxLogList.addAll(xPermMapService.getTransactionLog(oldObj,
+ "delete"));
+ permMapsToDelete.add(oldObj);
+ // xPermMapService.deleteResource(oldObj.getId());
+ }
+ }
+ }
+
+ List<VXAuditMap> newAuditMapList = vXResource.getAuditList();
+ VXAuditMapList vXAuditMaps = xAuditMapService
+ .searchXAuditMaps(searchCriteria);
+ List<VXAuditMap> prevAuditMapList = new ArrayList<VXAuditMap>();
+ if (vXAuditMaps != null && vXAuditMaps.getResultSize() != 0) {
+ prevAuditMapList = vXAuditMaps.getList();
+ }
+
+ // Create and update permissions
+ if (newAuditMapList != null) {
+ for (VXAuditMap newObj : newAuditMapList) {
+ if (newObj.getId() != null) {
+ /**
+ * Considering the new objects won't have id however the
+ * existing ones will have id.
+ */
+ for (VXAuditMap oldObj : prevAuditMapList) {
+ if (oldObj.getId().equals(newObj.getId())
+ && oldObj.getAuditType() != newObj
+ .getAuditType()) {
+ // This should never be the case because we're not
+ // supporting perm map update.
+ // doNothing...
+ logger.error(
+ "Invalid use case: shouldn't be happening, need to debug.",
+ new IllegalStateException());
+ break;
+ // } else {
+ // trxLogList.addAll(xAuditMapService.getTransactionLog(newObj,
+ // oldObj, "update"));
+ }
+ }
+ // newObj = xAuditMapService.updateResource(newObj);
+ } else {
+ newObj = xAuditMapService.createResource(newObj);
+ trxLogList.addAll(xAuditMapService.getTransactionLog(
+ newObj, "create"));
+ }
+ auditMaps.add(newObj);
+ }
+ }
+
+ // Delete old removed permissions
+ if (prevAuditMapList != null) {
+ for (VXAuditMap oldObj : prevAuditMapList) {
+ boolean found = false;
+ if (newAuditMapList != null) {
+ for (VXAuditMap newObj : newAuditMapList) {
+ if (newObj.getId() != null
+ && newObj.getId().equals(oldObj.getId())) {
+ found = true;
+ break;
+ }
+ }
+ }
+
+ if (!found) {
+ trxLogList.addAll(xAuditMapService.getTransactionLog(
+ oldObj, "delete"));
+ auditMapsToDelete.add(oldObj);
+ // xAuditMapService.deleteResource(oldObj.getId());
+ }
+ }
+ }
+
+ xaBizUtil.createTrxLog(trxLogList);
+
+ for (VXPermMap permMap : permMapsToDelete) {
+ xPermMapService.deleteResource(permMap.getId());
+ }
+
+ for (VXAuditMap auditMap : auditMapsToDelete) {
+ xAuditMapService.deleteResource(auditMap.getId());
+ }
+ resource.setPermMapList(permMaps);
+ resource.setAuditList(auditMaps);
+ return resource;
+ }
+
+ @Override
+ public void deleteXResource(Long id, boolean force) {
+
+ VXResource vResource = xResourceService.readResource(id);
+ UserSessionBase currentUserSession = ContextUtil
+ .getCurrentUserSession();
+ if (currentUserSession == null) {
+ throw restErrorUtil.createRESTException("Resource deletion not "
+ + "allowed",MessageEnums.OPER_NO_PERMISSION);
+ }
+
+ Long assetId = vResource.getAssetId();
+ XXAsset xAsset = xADaoManager.getXXAsset().getById(assetId);
+ if (xAsset == null) {
+ throw restErrorUtil.createRESTException("The repository for which "
+ + "you're deleting policy, doesn't exist.",
+ MessageEnums.INVALID_INPUT_DATA);
+ }
+
+ if(xAsset.getActiveStatus()==XACommonEnums.STATUS_DISABLED){
+ if(!currentUserSession.isUserAdmin()){
+ logger.error("Trying to delete policy in disabled repository");
+ throw restErrorUtil.createRESTException("Resource "
+ + "deletion not allowed in disabled repository",MessageEnums.OPER_NO_PERMISSION);
+ }
+ }
+
+ SearchCriteria searchCriteria = new SearchCriteria();
+ searchCriteria.addParam("resourceId", id);
+
+ VXPermMapList permMaps = xPermMapService
+ .searchXPermMaps(searchCriteria);
+ VXAuditMapList vXAuditMapsList = xAuditMapService
+ .searchXAuditMaps(searchCriteria);
+
+ List<XXTrxLog> trxLogList = xResourceService.getTransactionLog(
+ vResource, "delete");
+
+ for (VXPermMap vxPermMap : permMaps.getVXPermMaps()) {
+ trxLogList.addAll(xPermMapService.getTransactionLog(vxPermMap,
+ "delete"));
+ }
+
+ for (VXAuditMap vXAuditMaps : vXAuditMapsList.getVXAuditMaps()) {
+ trxLogList.addAll(xAuditMapService.getTransactionLog(vXAuditMaps,
+ "delete"));
+ }
+
+ xaBizUtil.createTrxLog(trxLogList);
+
+ for (VXPermMap vxPermMap : permMaps.getVXPermMaps()) {
+ xPermMapService.deleteResource(vxPermMap.getId());
+ }
+
+ for (VXAuditMap vXAuditMaps : vXAuditMapsList.getVXAuditMaps()) {
+ xAuditMapService.deleteResource(vXAuditMaps.getId());
+ }
+
+ xResourceService.deleteResource(id);
+ }
+
+ public File getXResourceFile(Long id, String fileType) {
+ VXResource xResource = xResourceService.readResource(id);
+ if (xResource == null) {
+ throw this.restErrorUtil.createRESTException(
+ "serverMsg.datasourceIdEmpty" + "id " + id,
+ MessageEnums.DATA_NOT_FOUND, id, "dataSourceId",
+ "DataSource not found with " + "id " + id);
+ }
+ File file = null;
+ try {
+ if (fileType != null) {
+ if (fileType.equalsIgnoreCase("json")) {
+ file = jsonUtil.writeJsonToFile(xResource,
+ xResource.getName());
+ } else {
+ throw restErrorUtil.createRESTException(
+ "Please send the supported filetype.",
+ MessageEnums.INVALID_INPUT_DATA);
+ }
+ } else {
+ throw restErrorUtil
+ .createRESTException(
+ "Please send the file format in which you want to export.",
+ MessageEnums.DATA_NOT_FOUND);
+ }
+ } catch (JsonGenerationException e) {
+ throw this.restErrorUtil.createRESTException(
+ "serverMsg.jsonGeneration" + " : " + e.getMessage(),
+ MessageEnums.ERROR_SYSTEM);
+ } catch (JsonMappingException e) {
+ throw this.restErrorUtil.createRESTException(
+ "serverMsg.jsonMapping" + " : " + e.getMessage(),
+ MessageEnums.ERROR_SYSTEM);
+ } catch (IOException e) {
+ throw this.restErrorUtil.createRESTException(
+ "serverMsg.ioException" + " : " + e.getMessage(),
+ MessageEnums.ERROR_SYSTEM);
+ }
+
+ return file;
+ }
+
+ public VXStringList getHdfsResources(final String dataSourceName,
+ String baseDir) {
+ if (dataSourceName != null && baseDir != null) {
+ List<String> strList = new ArrayList<String>();
+ try {
+ String wildCardToMatch;
+ final HadoopFS hdfsClient = assetConnectionMgr
+ .getHadoopConnection(dataSourceName);
+
+ if (hdfsClient != null) {
+ Integer lastIndex = baseDir.lastIndexOf("/");
+ if (lastIndex < 0) {
+ wildCardToMatch = baseDir + "*";
+ baseDir = "/";
+ } else if (lastIndex == 0 && baseDir.length() == 1) {
+ wildCardToMatch = null;
+ baseDir = "/";
+ } else if ((lastIndex + 1) == baseDir.length()) {
+ wildCardToMatch = null;
+ baseDir = baseDir.substring(0, lastIndex + 1);
+ } else {
+ wildCardToMatch = baseDir.substring(lastIndex + 1)
+ + "*";
+ baseDir = baseDir.substring(0, lastIndex + 1);
+ }
+
+ final String finalBaseDir = baseDir;
+ final String finalWildCardToMatch = wildCardToMatch;
+ final Callable<List<String>> callableObj = new Callable<List<String>>() {
+
+ @Override
+ public List<String> call() throws Exception {
+ return hdfsClient.listFiles(finalBaseDir,
+ finalWildCardToMatch);
+ }
+
+ };
+
+ strList = TimedEventUtil.timedTask(callableObj, 5,
+ TimeUnit.SECONDS); // If
+ // strList = hdfsClient.listFiles(finalBaseDir,
+ // finalWildCardToMatch);
+ logger.debug("Resource dir : " + baseDir
+ + " wild card to match : " + wildCardToMatch
+ + "\n Matching resources : " + strList);
+ }
+ } catch (Exception e) {
+ logger.error("Unable to get hdfs resources.", e);
+ }
+
+ return msBizUtil.mapStringListToVStringList(strList);
+ } else {
+ return new VXStringList();
+ }
+ }
+
+ public String getLatestRepoPolicy(String repository,
+ X509Certificate[] certchain, boolean httpEnabled, String epoch,
+ String ipAddress, boolean isSecure, String count, String agentId) {
+
+ XXAsset xAsset = xADaoManager.getXXAsset().findByAssetName(repository);
+ if(xAsset==null){
+ logger.error("Requested repository not found");
+ throw restErrorUtil.createRESTException("No Data Found.",
+ MessageEnums.DATA_NOT_FOUND);
+ }
+ if(xAsset.getActiveStatus()==XACommonEnums.ACT_STATUS_DISABLED){
+ logger.error("Requested repository is disabled");
+ throw restErrorUtil.createRESTException("Unauthorized access.",
+ MessageEnums.OPER_NO_EXPORT);
+ }
+
+ XXPolicyExportAudit policyExportAudit = new XXPolicyExportAudit();
+ policyExportAudit.setRepositoryName(repository);
+
+ if (agentId != null && !agentId.isEmpty()) {
+ policyExportAudit.setAgentId(agentId);
+ }
+
+ policyExportAudit.setClientIP(ipAddress);
+
+ if (epoch != null && !epoch.trim().isEmpty() && !epoch.equalsIgnoreCase("null")) {
+ policyExportAudit.setRequestedEpoch(Long.parseLong(epoch));
+ } else {
+ policyExportAudit.setRequestedEpoch(0l);
+ }
+
+ if (!httpEnabled) {
+ if (!isSecure) {
+ policyExportAudit
+ .setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST);
+ createPolicyAudit(policyExportAudit);
+
+ throw restErrorUtil.createRESTException("Unauthorized access -"
+ + " only https allowed",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+
+ if (certchain == null || certchain.length == 0) {
+
+ policyExportAudit
+ .setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST);
+ createPolicyAudit(policyExportAudit);
+
+ throw restErrorUtil.createRESTException("Unauthorized access -"
+ + " unable to get client certificate",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ }
+
+ Long policyCount = restErrorUtil.parseLong(count, "Invalid value for "
+ + "policyCount", MessageEnums.INVALID_INPUT_DATA, null,
+ "policyCount");
+
+ String commonName = null;
+
+ if (certchain != null) {
+ X509Certificate clientCert = certchain[0];
+ String dn = clientCert.getSubjectX500Principal().getName();
+
+ try {
+ LdapName ln = new LdapName(dn);
+ for (Rdn rdn : ln.getRdns()) {
+ if (rdn.getType().equalsIgnoreCase("CN")) {
+ commonName = rdn.getValue() + "";
+ break;
+ }
+ }
+ if (commonName == null) {
+ policyExportAudit
+ .setHttpRetCode(javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST);
+ createPolicyAudit(policyExportAudit);
+
+ throw restErrorUtil.createRESTException(
+ "Unauthorized access - Unable to find Common Name from ["
+ + dn + "]",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ } catch (InvalidNameException e) {
+ policyExportAudit
+ .setHttpRetCode(javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST);
+ createPolicyAudit(policyExportAudit);
+
+ logger.error("Invalid Common Name.", e);
+ throw restErrorUtil.createRESTException(
+ "Unauthorized access - Invalid Common Name",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ }
+
+ if (repository == null || repository.isEmpty()) {
+
+ policyExportAudit
+ .setHttpRetCode(javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST);
+ createPolicyAudit(policyExportAudit);
+
+ logger.error("Repository name not provided");
+ throw restErrorUtil.createRESTException("Unauthorized access.",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+
+
+
+ if (xAsset == null) {
+ policyExportAudit
+ .setHttpRetCode(javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST);
+ createPolicyAudit(policyExportAudit);
+
+ logger.error("Requested repository doesn't exist");
+ throw restErrorUtil.createRESTException("Unauthorized access.",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+
+ if (policyCount == null) {
+ policyCount = 0l;
+ }
+
+ if (commonName != null) {
+ String config = xAsset.getConfig();
+ Map<String, String> configMap = jsonUtil.jsonToMap(config);
+ String cnFromConfig = configMap.get("commonNameForCertificate");
+
+ if (cnFromConfig == null
+ || !commonName.equalsIgnoreCase(cnFromConfig)) {
+ policyExportAudit
+ .setHttpRetCode(javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST);
+ createPolicyAudit(policyExportAudit);
+
+ throw restErrorUtil.createRESTException(
+ "Unauthorized access. expected [" + cnFromConfig
+ + "], found [" + commonName + "]",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ }
+
+ // //////////////////////////////////////
+ // Get latest updated time of repository
+ // //////////////////////////////////////
+ Timestamp luTime = xADaoManager.getXXResource()
+ .getMaxUpdateTimeForAssetName(repository);
+
+ HashMap<String, Object> updatedRepo = new HashMap<String, Object>();
+ updatedRepo.put("repository_name", repository);
+
+ Long updatedTime = 0l;
+ List<HashMap<String, Object>> resourceList = new ArrayList<HashMap<String, Object>>();
+
+ if (luTime != null) {
+ updatedTime = luTime.getTime();
+ }
+
+ {
+ List<XXResource> xResourceList = new ArrayList<XXResource>();
+
+ long epochTime = epoch != null ? Long.parseLong(epoch) : 0;
+
+ if(epochTime == updatedTime) {
+ //TODO: instead of getting entire list, get just count(*) for the given repository
+ xResourceList = xADaoManager.getXXResource().findUpdatedResourcesByAssetName(repository, new Date(0L));
+
+ int resourceListSz = (xResourceList == null) ? 0 : xResourceList.size() ;
+
+ if (policyCount == resourceListSz) {
+ policyExportAudit
+ .setHttpRetCode(javax.servlet.http.HttpServletResponse.SC_NOT_MODIFIED);
+ createPolicyAudit(policyExportAudit);
+
+ throw restErrorUtil.createRESTException(
+ HttpServletResponse.SC_NOT_MODIFIED,
+ "No change since last update", false);
+ }
+
+ } else {
+ xResourceList = xADaoManager.getXXResource().findUpdatedResourcesByAssetName(repository, new Date(0L));
+ }
+
+
+ // HDFS Repository
+ if (xAsset.getAssetType() == AppConstants.ASSET_HDFS) {
+ for (XXResource xResource : xResourceList) {
+ HashMap<String, Object> resourceMap = new HashMap<String, Object>();
+ resourceMap.put("id", xResource.getId());
+ resourceMap.put("resource", xResource.getName());
+ resourceMap.put("isRecursive",
+ getBooleanValue(xResource.getIsRecursive()));
+ resourceMap.put("policyStatus", XACommonEnums
+ .getLabelFor_ActiveStatus(xResource
+ .getResourceStatus()));
+ // resourceMap.put("isEncrypt",
+ // AKAConstants.getLabelFor_BooleanValue(xResource.getIsEncrypt()));
+ populatePermMap(xResource, resourceMap, AppConstants.ASSET_HDFS);
+ List<XXAuditMap> xAuditMaps = xADaoManager.getXXAuditMap()
+ .findByResourceId(xResource.getId());
+ if (xAuditMaps.size() != 0) {
+ resourceMap.put("audit", 1);
+ } else {
+ resourceMap.put("audit", 0);
+ }
+
+ resourceList.add(resourceMap);
+ }
+ } else if (xAsset.getAssetType() == AppConstants.ASSET_HIVE) {
+ for (XXResource xResource : xResourceList) {
+ HashMap<String, Object> resourceMap = new HashMap<String, Object>();
+ resourceMap.put("id", xResource.getId());
+ resourceMap.put("database_name", xResource.getDatabases());
+ resourceMap.put("policyStatus", XACommonEnums
+ .getLabelFor_ActiveStatus(xResource
+ .getResourceStatus()));
+ resourceMap.put("tablePolicyType", AppConstants
+ .getLabelFor_PolicyType(xResource.getTableType()));
+ resourceMap.put("columnPolicyType", AppConstants
+ .getLabelFor_PolicyType(xResource.getColumnType()));
+ int resourceType = xResource.getResourceType();
+ if (resourceType == AppConstants.RESOURCE_UDF) {
+ resourceMap.put("udf_name", xResource.getUdfs());
+ } else if (resourceType == AppConstants.RESOURCE_COLUMN) {
+ resourceMap.put("table_name", xResource.getTables());
+ resourceMap.put("column_name", xResource.getColumns());
+ } else if (resourceType == AppConstants.RESOURCE_TABLE) {
+ resourceMap.put("table_name", xResource.getTables());
+ }
+
+ populatePermMap(xResource, resourceMap, AppConstants.ASSET_HIVE);
+ List<XXAuditMap> xAuditMaps = xADaoManager.getXXAuditMap()
+ .findByResourceId(xResource.getId());
+ if (xAuditMaps.size() != 0) {
+ resourceMap.put("audit", 1);
+ } else {
+ resourceMap.put("audit", 0);
+ }
+ resourceList.add(resourceMap);
+ }
+ }
+
+ else if (xAsset.getAssetType() == AppConstants.ASSET_HBASE) {
+ for (XXResource xResource : xResourceList) {
+ HashMap<String, Object> resourceMap = new HashMap<String, Object>();
+
+ resourceMap.put("id", xResource.getId());
+ resourceMap.put("table_name", xResource.getTables());
+ resourceMap.put("column_name", xResource.getColumns());
+ resourceMap.put("column_families",
+ xResource.getColumnFamilies());
+ resourceMap.put("policyStatus", XACommonEnums
+ .getLabelFor_ActiveStatus(xResource
+ .getResourceStatus()));
+ if (xResource.getIsEncrypt() == 1) {
+ resourceMap.put("encrypt", 1);
+ } else {
+ resourceMap.put("encrypt", 0);
+ }
+ // resourceMap.put("isEncrypt",
+ // AKAConstants.getLabelFor_BooleanValue(xResource.getIsEncrypt()));
+ populatePermMap(xResource, resourceMap, AppConstants.ASSET_HBASE);
+ List<XXAuditMap> xAuditMaps = xADaoManager.getXXAuditMap()
+ .findByResourceId(xResource.getId());
+ if (xAuditMaps.size() != 0) {
+ resourceMap.put("audit", 1);
+ } else {
+ resourceMap.put("audit", 0);
+ }
+ resourceList.add(resourceMap);
+ }
+ }
+ else if (xAsset.getAssetType() == AppConstants.ASSET_KNOX) {
+ for (XXResource xResource : xResourceList) {
+ HashMap<String, Object> resourceMap = new HashMap<String, Object>();
+
+ resourceMap.put("id", xResource.getId());
+ resourceMap.put("topology_name", xResource.getTopologies()) ;
+ resourceMap.put("service_name", xResource.getServices()) ;
+ resourceMap.put("policyStatus", XACommonEnums
+ .getLabelFor_ActiveStatus(xResource
+ .getResourceStatus()));
+ if (xResource.getIsEncrypt() == 1) {
+ resourceMap.put("encrypt", 1);
+ } else {
+ resourceMap.put("encrypt", 0);
+ }
+ // resourceMap.put("isEncrypt",
+ // AKAConstants.getLabelFor_BooleanValue(xResource.getIsEncrypt()));
+ populatePermMap(xResource, resourceMap, AppConstants.ASSET_KNOX);
+ List<XXAuditMap> xAuditMaps = xADaoManager.getXXAuditMap()
+ .findByResourceId(xResource.getId());
+ if (xAuditMaps.size() != 0) {
+ resourceMap.put("audit", 1);
+ } else {
+ resourceMap.put("audit", 0);
+ }
+ resourceList.add(resourceMap);
+ }
+
+ }
+ else if (xAsset.getAssetType() == AppConstants.ASSET_STORM) {
+ for (XXResource xResource : xResourceList) {
+ HashMap<String, Object> resourceMap = new HashMap<String, Object>();
+
+ resourceMap.put("id", xResource.getId());
+ resourceMap.put("topology_name", xResource.getTopologies()) ;
+ resourceMap.put("policyStatus", XACommonEnums
+ .getLabelFor_ActiveStatus(xResource
+ .getResourceStatus()));
+ if (xResource.getIsEncrypt() == 1) {
+ resourceMap.put("encrypt", 1);
+ } else {
+ resourceMap.put("encrypt", 0);
+ }
+ populatePermMap(xResource, resourceMap, AppConstants.ASSET_STORM);
+ List<XXAuditMap> xAuditMaps = xADaoManager.getXXAuditMap()
+ .findByResourceId(xResource.getId());
+ if (xAuditMaps.size() != 0) {
+ resourceMap.put("audit", 1);
+ } else {
+ resourceMap.put("audit", 0);
+ }
+ resourceList.add(resourceMap);
+ }
+ } else {
+ policyExportAudit
+ .setHttpRetCode(javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST);
+ createPolicyAudit(policyExportAudit);
+ throw restErrorUtil.createRESTException(
+ "The operation isn't yet supported for the repository",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ }
+
+ policyCount = Long.valueOf(resourceList.size());
+ updatedRepo.put("last_updated", updatedTime);
+ updatedRepo.put("policyCount", policyCount);
+ updatedRepo.put("acl", resourceList);
+
+ String updatedPolicyStr = jsonUtil.readMapToString(updatedRepo);
+
+// File file = null;
+// try {
+// file = jsonUtil.writeMapToFile(updatedRepo, repository);
+// } catch (JsonGenerationException e) {
+// logger.error("Error exporting policies for repository : "
+// + repository, e);
+// } catch (JsonMappingException e) {
+// logger.error("Error exporting policies for repository : "
+// + repository, e);
+// } catch (IOException e) {
+// logger.error("Error exporting policies for repository : "
+// + repository, e);
+// }
+
+ policyExportAudit
+ .setHttpRetCode(javax.servlet.http.HttpServletResponse.SC_OK);
+ createPolicyAudit(policyExportAudit);
+
+ return updatedPolicyStr;
+ }
+
+ public VXStringList getHiveResources(final String dataSourceName,
+ String databaseName, String tableName, String columnName) {
+
+ List<String> resultList = new ArrayList<String>();
+ if (dataSourceName != null) {
+ final HiveClient hiveClient = assetConnectionMgr
+ .getHiveConnection(dataSourceName);
+
+ try {
+ final Callable<List<String>> callableObj;
+ final String finalDbName;
+ final String finalColName;
+ final String finalTableName;
+
+ if (hiveClient != null && databaseName != null
+ && !databaseName.isEmpty()) {
+ if (tableName != null && !tableName.isEmpty()) {
+ if (columnName != null && !columnName.isEmpty()) {
+ columnName += "*";
+ finalColName = columnName;
+ finalDbName = databaseName;
+ finalTableName = tableName;
+
+ callableObj = new Callable<List<String>>() {
+ @Override
+ public List<String> call() {
+ return hiveClient.getColumnList(
+ finalDbName, finalTableName,
+ finalColName);
+ }
+ };
+ } else {
+ tableName += "*";
+ finalTableName = tableName;
+ finalDbName = databaseName;
+ callableObj = new Callable<List<String>>() {
+
+ @Override
+ public List<String> call() {
+ return hiveClient.getTableList(finalDbName,
+ finalTableName);
+ }
+
+ };
+ }
+ } else {
+ databaseName += "*";
+ finalDbName = databaseName;
+ callableObj = new Callable<List<String>>() {
+ @Override
+ public List<String> call() {
+ return hiveClient.getDatabaseList(finalDbName);
+ }
+ };
+
+ }
+
+ synchronized (hiveClient) {
+ resultList = TimedEventUtil.timedTask(callableObj, 5,
+ TimeUnit.SECONDS);
+ }
+
+ }
+ } catch (Exception e) {
+ logger.error("Unable to get hive resources.", e);
+ }
+ }
+
+ return msBizUtil.mapStringListToVStringList(resultList);
+ }
+
+ @Override
+ public VXAsset createXAsset(VXAsset vXAsset) {
+ UserSessionBase usb = ContextUtil.getCurrentUserSession();
+ if (usb != null && usb.isUserAdmin()) {
+
+ String defaultConfig = vXAsset.getConfig();
+ defaultConfig=xAssetService.getConfigWithEncryptedPassword(defaultConfig,false);
+ vXAsset.setConfig(defaultConfig);
+ VXAsset createdVXAsset = (VXAsset) xAssetService
+ .createResource(vXAsset);
+ String udpatedConfig = vXAsset.getConfig();
+ createdVXAsset.setConfig(defaultConfig);
+
+ createDefaultPolicy(createdVXAsset, vXAsset.getConfig());
+ createDefaultUDFPolicy(createdVXAsset, vXAsset.getConfig());
+ createdVXAsset.setConfig(udpatedConfig);
+
+ List<XXTrxLog> trxLogList = xAssetService.getTransactionLog(
+ createdVXAsset, "create");
+ xaBizUtil.createTrxLog(trxLogList);
+ return createdVXAsset;
+ } else {
+ logger.debug("User id : " + usb.getUserId() + " doesn't have "
+ + "admin access to create repository.");
+ throw restErrorUtil
+ .createRESTException(
+ "Sorry, you don't have permission to perform the operation",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ }
+
+ private void createDefaultPolicy(VXAsset vXAsset, String config) {
+ int assetType = vXAsset.getAssetType();
+
+ Map<String, String> configMap = jsonUtil.jsonToMap(config);
+ String userName = stringUtil.getValidUserName(configMap.get("username"));
+
+ VXResource vXResource = new VXResource();
+ vXResource.setAssetId(vXAsset.getId());
+ vXResource.setAssetName(vXAsset.getName());
+ vXResource.setResourceStatus(AppConstants.STATUS_ENABLED);
+ String tempPolicyName=vXAsset.getName()+"-"+1+"-"+DateUtil.dateToString(DateUtil.getUTCDate(),"yyyyMMddHHmmss");
+ vXResource.setPolicyName(tempPolicyName);
+ if (assetType == AppConstants.ASSET_HDFS) {
+ vXResource.setName("/");
+ vXResource.setIsRecursive(AppConstants.BOOL_TRUE);
+ vXResource.setResourceType(AppConstants.RESOURCE_PATH);
+ } else if (assetType == AppConstants.ASSET_HIVE) {
+ vXResource.setDatabases("*");
+ vXResource.setTables("*");
+ vXResource.setColumns("*");
+ vXResource.setName("/*/*/*");
+ vXResource.setResourceType(AppConstants.RESOURCE_COLUMN);
+ } else if (assetType == AppConstants.ASSET_HBASE) {
+ vXResource.setTables("*");
+ vXResource.setColumnFamilies("*");
+ vXResource.setColumns("*");
+ vXResource.setName("/*/*/*");
+ vXResource.setResourceType(AppConstants.RESOURCE_COLUMN);
+ } else if (assetType == AppConstants.ASSET_KNOX) {
+ vXResource.setTopologies("*");
+ vXResource.setServices("*");
+ vXResource.setName("/*/*");
+ vXResource.setResourceType(AppConstants.RESOURCE_SERVICE_NAME);
+ } else if (assetType == AppConstants.ASSET_STORM) {
+ vXResource.setTopologies("*");
+ vXResource.setName("/*");
+ vXResource.setResourceType(AppConstants.RESOURCE_TOPOLOGY);
+ }
+
+ vXResource = xResourceService.createResource(vXResource);
+
+ if (userName != null && !userName.isEmpty()) {
+ XXUser xxUser = xADaoManager.getXXUser().findByUserName(userName);
+ VXUser vXUser;
+ if (xxUser != null) {
+ vXUser = xUserService.populateViewBean(xxUser);
+ } else {
+ vXUser = new VXUser();
+ vXUser.setName(userName);
+ vXUser.setUserSource(XACommonEnums.USER_EXTERNAL);
+ vXUser=xUserMgr.createXUser(vXUser);
+ //vXUser = xUserService.createResource(vXUser);
+ }
+
+ Random rand = new Random();
+ String permGrp = new Date() + " : " + rand.nextInt(9999);
+
+ VXPermMap vXPermMap = new VXPermMap();
+ vXPermMap.setUserId(vXUser.getId());
+ vXPermMap.setResourceId(vXResource.getId());
+ vXPermMap.setPermGroup(permGrp);
+ xPermMapService.createResource(vXPermMap);
+
+ if (assetType == AppConstants.ASSET_KNOX) {
+ String permGroup = new Date() + " : " + rand.nextInt(9999);
+
+ VXPermMap permAdmin = new VXPermMap();
+ permAdmin.setPermFor(AppConstants.XA_PERM_FOR_USER);
+ permAdmin.setPermType(AppConstants.XA_PERM_TYPE_ADMIN);
+ permAdmin.setUserId(vXUser.getId());
+ permAdmin.setPermGroup(permGroup);
+ permAdmin.setResourceId(vXResource.getId());
+ xPermMapService.createResource(permAdmin);
+
+ VXPermMap permAllow = new VXPermMap();
+ permAllow.setPermFor(AppConstants.XA_PERM_FOR_USER);
+ permAllow.setPermType(AppConstants.XA_PERM_TYPE_ALLOW);
+ permAllow.setUserId(vXUser.getId());
+ permAllow.setPermGroup(permGroup);
+ permAllow.setResourceId(vXResource.getId());
+ xPermMapService.createResource(permAllow);
+ }
+ }
+
+ VXAuditMap vXAuditMap = new VXAuditMap();
+ vXAuditMap.setAuditType(AppConstants.XA_AUDIT_TYPE_ALL);
+ vXAuditMap.setResourceId(vXResource.getId());
+ vXAuditMap = xAuditMapService.createResource(vXAuditMap);
+ vXResource=xResourceService.readResource(vXResource.getId());
+ List<VXPermMap> permMapList = vXResource.getPermMapList();
+ List<VXAuditMap> auditMapList = vXResource.getAuditList();
+
+ List<XXTrxLog> trxLogList = xResourceService.getTransactionLog(
+ vXResource, "create");
+ for (VXPermMap vXPermMap : permMapList) {
+ trxLogList.addAll(xPermMapService.getTransactionLog(vXPermMap,
+ "create"));
+ }
+ for (VXAuditMap vXAuditMapObj : auditMapList) {
+ trxLogList.addAll(xAuditMapService.getTransactionLog(vXAuditMapObj,
+ "create"));
+ }
+
+ xaBizUtil.createTrxLog(trxLogList);
+
+
+ }
+
+ @Override
+ public VXAsset updateXAsset(VXAsset vXAsset) {
+ UserSessionBase usb = ContextUtil.getCurrentUserSession();
+ if (usb != null && usb.isUserAdmin()) {
+ String newConfig=vXAsset.getConfig();
+ HashMap<String, String> configMap = (HashMap<String, String>) jsonUtil
+ .jsonToMap(newConfig);
+ String password = configMap.get("password");
+ String hiddenPasswordString = PropertiesUtil.getProperty(
+ "xa.password.hidden", "*****");
+ if (password != null && !password.equals(hiddenPasswordString)) {
+ String defaultConfig = vXAsset.getConfig();
+ defaultConfig=xAssetService.getConfigWithEncryptedPassword(defaultConfig,true);
+ vXAsset.setConfig(defaultConfig);
+ }
+ XXAsset xAsset = xADaoManager.getXXAsset()
+ .getById(vXAsset.getId());
+
+ if (xAsset.getActiveStatus() == XACommonEnums.STATUS_DELETED) {
+ logger.error("Trying to update Asset which is soft deleted");
+ throw restErrorUtil.createRESTException(
+ "Repository that you want to update does not exist.",
+ MessageEnums.DATA_NOT_FOUND, xAsset.getId(), null,
+ "Repository not exist for this Id : " + xAsset.getId());
+ }
+
+ List<XXTrxLog> trxLogList = xAssetService.getTransactionLog(
+ vXAsset, xAsset, "update");
+ vXAsset = (VXAsset) xAssetService.updateResource(vXAsset);
+ // update default policy permission and user
+ updateDefaultPolicy(vXAsset, vXAsset.getConfig());
+ // TODO this should reset the connection
+ assetConnectionMgr.destroyConnection(vXAsset);
+ // TODO : Log in transaction log table
+ xaBizUtil.createTrxLog(trxLogList);
+ return vXAsset;
+ } else {
+ throw restErrorUtil.createRESTException(
+ "serverMsg.modelMgrBaseUpdateModel",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ }
+
+ @Override
+ public void deleteXAsset(Long id, boolean force) {
+ UserSessionBase usb = ContextUtil.getCurrentUserSession();
+ if (usb != null && usb.isUserAdmin() && force) {
+ VXAsset vxAsset = xAssetService.readResource(id);
+
+ if (vxAsset.getActiveStatus() == XACommonEnums.STATUS_DELETED) {
+ logger.error("Trying to delete Asset which is already soft deleted");
+ throw restErrorUtil.createRESTException(
+ "Repository not found or its already deleted, for Id : "
+ + id, MessageEnums.DATA_NOT_FOUND, id, null,
+ "Repository not exist for this Id : " + id);
+ }
+
+ SearchCriteria searchCriteria = new SearchCriteria();
+ searchCriteria.addParam("assetId", id);
+ VXResourceList resources = searchXResources(searchCriteria);
+ if (resources != null && resources.getResultSize() != 0) {
+ for (VXResource resource : resources.getList()) {
+ deleteXResource(resource.getId(), true);
+ }
+ }
+ vxAsset.setActiveStatus(XACommonEnums.STATUS_DELETED);
+ xAssetService.updateResource(vxAsset);
+ List<XXTrxLog> trxLogList = xAssetService.getTransactionLog(
+ vxAsset, "delete");
+ xaBizUtil.createTrxLog(trxLogList);
+ } else {
+ throw restErrorUtil.createRESTException(
+ "serverMsg.modelMgrBaseDeleteModel",
+ MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ }
+ }
+
+ public VXStringList getHBaseResources(final String dataSourceName,
+ String tableName, String columnFamilies) {
+
+ List<String> resultList = new ArrayList<String>();
+ if (dataSourceName != null) {
+ final HBaseClient hBaseClient = assetConnectionMgr
+ .getHBaseConnection(dataSourceName);
+
+ try {
+ final Callable<List<String>> callableObj;
+ if (hBaseClient != null && tableName != null
+ && !tableName.isEmpty()) {
+ final String finalColFamilies;
+ final String finalTableName;
+
+ if (columnFamilies != null && !columnFamilies.isEmpty()) {
+ if (!columnFamilies.endsWith("*")) {
+ columnFamilies += "*";
+ }
+
+ columnFamilies = columnFamilies.replaceAll("\\*",
+ ".\\*");
+ finalColFamilies = columnFamilies;
+ finalTableName = tableName;
+
+ callableObj = new Callable<List<String>>() {
+ @Override
+ public List<String> call() {
+ return hBaseClient.getColumnFamilyList(
+ finalTableName, finalColFamilies);
+ }
+ };
+
+ } else {
+ if (!tableName.endsWith("*")) {
+ tableName += "*";
+ }
+
+ tableName = tableName.replaceAll("\\*", ".\\*");
+ finalTableName = tableName;
+
+ callableObj = new Callable<List<String>>() {
+ @Override
+ public List<String> call() {
+ return hBaseClient.getTableList(finalTableName);
+ }
+ };
+
+ }
+ resultList = TimedEventUtil.timedTask(callableObj, 5,
+ TimeUnit.SECONDS);
+ }
+
+ } catch (Exception e) {
+ logger.error("Unable to get hbase resources.", e);
+ }
+ }
+
+ return msBizUtil.mapStringListToVStringList(resultList);
+ }
+
+ public VXStringList getKnoxResources(
+ String knoxUrl,String knoxAdminUser, String knoxAdminPassword,
+ String topologyName, String serviceName) {
+ List<String> resultList = new ArrayList<String>();
+ if (knoxUrl == null || knoxUrl.isEmpty()) {
+ logger.error("Unable to get knox resources: knoxUrl is empty");
+ return msBizUtil.mapStringListToVStringList(resultList);
+ } else if (knoxAdminUser == null || knoxAdminUser.isEmpty()) {
+ logger.error("Unable to get knox resources: knoxAdminUser is empty");
+ return msBizUtil.mapStringListToVStringList(resultList);
+ } else if (knoxAdminPassword == null || knoxAdminPassword.isEmpty()) {
+ logger.error("Unable to get knox resources: knoxAdminPassword is empty");
+ return msBizUtil.mapStringListToVStringList(resultList);
+ }
+
+ final KnoxClient knoxClient = assetConnectionMgr
+ .getKnoxClient(knoxUrl, knoxAdminUser, knoxAdminPassword);
+ VXStringList knoxResources = getKnoxResources(knoxClient, topologyName, serviceName);
+ return knoxResources;
+ }
+
+ public VXStringList getKnoxResources(final String dataSourceName,
+ String topologyName, String serviceName) {
+ List<String> resultList = new ArrayList<String>();
+ if (dataSourceName == null || dataSourceName.isEmpty()) {
+ logger.error("Unable to get knox resources: dataSourceName is null");
+ return msBizUtil.mapStringListToVStringList(resultList);
+ }
+
+ final KnoxClient knoxClient = assetConnectionMgr
+ .getKnoxClient(dataSourceName);
+ VXStringList knoxResources = getKnoxResources(knoxClient, topologyName, serviceName);
+ return knoxResources;
+ }
+
+
+ public VXStringList getKnoxResources(final KnoxClient knoxClient,
+ String topologyName, String serviceName) {
+
+ List<String> resultList = new ArrayList<String>();
+
+ try {
+ if (knoxClient == null) {
+ logger.error("Unable to get knox resources: knoxClient is null");
+ return msBizUtil.mapStringListToVStringList(resultList);
+ }
+
+ final Callable<List<String>> callableObj;
+ if (serviceName != null) {
+ final String finalServiceNameMatching = serviceName.trim();
+ final String finalTopologyName = topologyName;
+ callableObj = new Callable<List<String>>() {
+ @Override
+ public List<String> call() {
+ return knoxClient.getServiceList(finalTopologyName,
+ finalServiceNameMatching);
+ }
+ };
+
+ } else {
+ final String finalTopologyNameMatching = (topologyName == null) ?
+ "" : topologyName.trim();
+ callableObj = new Callable<List<String>>() {
+ @Override
+ public List<String> call() {
+ return knoxClient.getTopologyList(finalTopologyNameMatching);
+ }
+ };
+ }
+ resultList = TimedEventUtil.timedTask(callableObj, 5,
+ TimeUnit.SECONDS);
+
+ } catch (Exception e) {
+ logger.error("Unable to get knox resources.", e);
+ }
+
+ return msBizUtil.mapStringListToVStringList(resultList);
+ }
+
+ public VXResponse testConfig(VXAsset vXAsset) {
+
+ if (vXAsset.getActiveStatus() == XACommonEnums.STATUS_DELETED) {
+ logger.error("Trying to test Asset which is soft deleted");
+ throw restErrorUtil.createRESTException(
+ "Repository not found, Repository Name : " + vXAsset.getName(),
+ MessageEnums.DATA_NOT_FOUND, vXAsset.getId(), null,
+ "Repository not exist for this Id : " + vXAsset.getId());
+ }
+
+ int assetType = vXAsset.getAssetType();
+
+ VXResponse testResponse = new VXResponse();
+ HashMap<String, Object> responseData = new HashMap<String, Object>();
+
+ HashMap<String, String> configMap = (HashMap<String, String>) jsonUtil
+ .jsonToMap(vXAsset.getConfig());
+ String password = configMap.get("password");
+ String hiddenPasswordString = PropertiesUtil.getProperty(
+ "xa.password.hidden", "*****");
+
+ if (password != null && password.equals(hiddenPasswordString)) {
+ String assetName = vXAsset.getName();
+ if (assetName != null) {
+ XXAsset existingVXAsset = xADaoManager.getXXAsset()
+ .findByAssetName(assetName);
+ if (existingVXAsset != null
+ && existingVXAsset.getConfig() != null) {
+ String existingConfig = existingVXAsset.getConfig();
+ existingConfig=xAssetService.getConfigWithDecryptedPassword(existingConfig);
+ HashMap<String, String> existingConfigMap = (HashMap<String, String>) jsonUtil
+ .jsonToMap(existingConfig);
+ String existingPassword = existingConfigMap.get("password");
+ if (existingPassword != null) {
+ configMap.put("password", existingPassword);
+ }
+ }
+ }
+ }
+
+ try {
+ String dataSource = vXAsset.getName();
+ if (assetType == AppConstants.ASSET_HDFS) {
+ // HadoopFS connectionObj = new HadoopFS(vXAsset.getName(),
+ // configMap);
+ // if (connectionObj != null) {
+ // List<String> testResult = connectionObj
+ // .listFiles("/", null);
+ // if (testResult != null && testResult.size() != 0) {
+ // connectivityStatus = true;
+ // }
+ // }
+ responseData = HadoopFS.testConnection(dataSource, configMap);
+ } else if (assetType == AppConstants.ASSET_HIVE) {
+ // HiveClient connectionObj = new HiveClient(vXAsset.getName(),
+ // configMap);
+ // if (connectionObj != null) {
+ // List<String> testResult = connectionObj
+ // .getDatabaseList("*");
+ // if (testResult != null && testResult.size() != 0) {
+ // connectivityStatus = true;
+ // }
+ // }
+ // connectionObj.close();
+ responseData = HiveClient.testConnection(dataSource, configMap);
+ } else if (assetType == AppConstants.ASSET_HBASE) {
+ // HBaseClient connectionObj = new
+ // HBaseClient(vXAsset.getName(),
+ // configMap);
+ // if (connectionObj != null) {
+ // connectivityStatus = connectionObj.getHBaseStatus();
+ // } else {
+ // Log.error("testConfig: Not able to create HBaseClient");
+ // }
+ responseData = HBaseClient
+ .testConnection(dataSource, configMap);
+ } else if (assetType == AppConstants.ASSET_KNOX) {
+ // KnoxClient knoxClient = assetConnectionMgr.getKnoxClient(
+ // vXAsset.getName(), configMap);
+ // VXStringList vxStringList = getKnoxResources(knoxClient, "",
+ // null);
+ // if (vxStringList != null && (vxStringList.getListSize() !=
+ // 0)) {
+ // connectivityStatus = true;
+ // }
+ responseData = KnoxClient.testConnection(dataSource, configMap);
+ } else if (assetType == AppConstants.ASSET_STORM) {
+ responseData = StormClient.testConnection(dataSource, configMap);
+ } else {
+ throw restErrorUtil.createRESTException(
+ "Invalid repository type.",
+ MessageEnums.INVALID_INPUT_DATA);
+ }
+ testResponse = generateResponseForTestConn(responseData, "");
+
+ } catch (Exception e) {
+
+ String msg = "Unable to connect repository with given config for "
+ + vXAsset.getName();
+ HashMap<String, Object> respData = new HashMap<String, Object>();
+ String message = "";
+ if (e instanceof HadoopException) {
+ respData = ((HadoopException) e).responseData;
+ message = (respData != null && respData.get("message") != null) ? respData.get(
+ "message").toString() : msg;
+ }
+ if(respData == null) {
+ respData = new HashMap<String, Object>();
+ }
+ testResponse = generateResponseForTestConn(respData, message);
+ logger.error(msg, e);
+ }
+ return testResponse;
+ }
+
+ private VXResponse generateResponseForTestConn(
+ HashMap<String, Object> responseData, String msg) {
+ VXResponse vXResponse = new VXResponse();
+
+ Long objId = (responseData.get("objectId") != null) ? Long
+ .parseLong(responseData.get("objectId").toString()) : null;
+ boolean connectivityStatus = (responseData.get("connectivityStatus") != null) ? Boolean
+ .parseBoolean(responseData.get("connectivityStatus").toString())
+ : false;
+ int statusCode = (connectivityStatus) ? VXResponse.STATUS_SUCCESS
+ : VXResponse.STATUS_ERROR;
+ String message = (responseData.get("message") != null) ? responseData
+ .get("message").toString() : msg;
+ String description = (responseData.get("description") != null) ? responseData
+ .get("description").toString() : msg;
+ String fieldName = (responseData.get("fieldName") != null) ? responseData
+ .get("fieldName").toString() : null;
+
+ VXMessage vXMsg = new VXMessage();
+ List<VXMessage> vXMsgList = new ArrayList<VXMessage>();
+ vXMsg.setFieldName(fieldName);
+ vXMsg.setMessage(message);
+ vXMsg.setObjectId(objId);
+ vXMsgList.add(vXMsg);
+
+ vXResponse.setMessageList(vXMsgList);
+ vXResponse.setMsgDesc(description);
+ vXResponse.setStatusCode(statusCode);
+ return vXResponse;
+ }
+
+ private void createResourcePathForHive(VXResource vXResource) {
+
+ String[] databases = (vXResource.getDatabases() == null || vXResource
+ .getDatabases().equalsIgnoreCase("")) ? null : stringUtil
+ .split(vXResource.getDatabases(), ",");
+ String[] tables = (vXResource.getTables() == null || vXResource
+ .getTables().equalsIgnoreCase("")) ? null : stringUtil.split(
+ vXResource.getTables(), ",");
+ String[] udfs = (vXResource.getUdfs() == null || vXResource.getUdfs()
+ .equalsIgnoreCase("")) ? null : stringUtil.split(
+ vXResource.getUdfs(), ",");
+ String[] columns = (vXResource.getColumns() == null || vXResource
+ .getColumns().equalsIgnoreCase("")) ? null : stringUtil.split(
+ vXResource.getColumns(), ",");
+
+ StringBuilder stringBuilder = new StringBuilder();
+
+// int resourceType = vXResource.getResourceType();
+ int resourceType = xPolicyService.getResourceType(vXResource);
+
+ if (databases == null) {
+ logger.error("Invalid resources for hive policy.");
+ throw restErrorUtil.createRESTException("Please provide the"
+ + " valid resources.", MessageEnums.INVALID_INPUT_DATA);
+ }
+
+ switch (resourceType) {
+
+ case AppConstants.RESOURCE_COLUMN:
+ for (String column : columns) {
+ for (String table : tables) {
+ for (String database : databases) {
+ stringBuilder.append("/" + database + "/" + table + "/"
+ + column + ",");
+ }
+ }
+ }
+ break;
+
+ case AppConstants.RESOURCE_TABLE:
+ for (String table : tables) {
+ for (String database : databases) {
+ stringBuilder.append("/" + database + "/" + table + ",");
+ }
+ }
+ break;
+
+ case AppConstants.RESOURCE_UDF:
+ for (String udf : udfs) {
+ for (String database : databases) {
+ stringBuilder.append("/" + database + "/" + udf + ",");
+ }
+ }
+ break;
+
+ case AppConstants.RESOURCE_DB:
+ for (String database : databases) {
+ stringBuilder.append("/" + database + ",");
+ }
+ break;
+
+ default:
+ logger.error("Invalid resource type : " + resourceType
+ + " for hive policy.");
+ throw restErrorUtil.createRESTException("Please provide the"
+ + " valid resource type.", MessageEnums.INVALID_INPUT_DATA);
+ }
+
+ int lastIndexOfSeperator = stringBuilder.lastIndexOf(",");
+ if (lastIndexOfSeperator > 0) {
+ String name = stringBuilder.substring(0,
+ stringBuilder.lastIndexOf(","));
+ vXResource.setName(name);
+ } else {
+ vXResource.setName(stringBuilder.toString());
+ }
+ }
+
+ private void createResourcePathForHbase(VXResource vXResource) {
+
+ String[] tables = (vXResource.getTables() == null || vXResource
+ .getTables().equalsIgnoreCase("")) ? null : stringUtil.split(
+ vXResource.getTables(), ",");
+ String[] columnFamilies = (vXResource.getColumnFamilies() == null || vXResource
+ .getColumnFamilies().equalsIgnoreCase("")) ? null : stringUtil
+ .split(vXResource.getColumnFamilies(), ",");
+ String[] columns = (vXResource.getColumns() == null || vXResource
+ .getColumns().equalsIgnoreCase("")) ? null : stringUtil.split(
+ vXResource.getColumns(), ",");
+
+ StringBuilder stringBuilder = new StringBuilder();
+
+// int resourceType = vXResource.getResourceType();
+ int resourceType = xPolicyService.getResourceType(vXResource);
+
+ if (tables == null) {
+ logger.error("Invalid resources for hbase policy.");
+ throw restErrorUtil.createRESTException("Please provide the"
+ + " valid resources.", MessageEnums.INVALID_INPUT_DATA);
+ }
+
+ switch (resourceType) {
+
+ case AppConstants.RESOURCE_COLUMN:
+ for (String column : columns) {
+ for (String columnFamily : columnFamilies) {
+ for (String table : tables) {
+ stringBuilder.append("/" + table + "/" + columnFamily
+ + "/" + column + ",");
+ }
+ }
+ }
+ break;
+
+ case AppConstants.RESOURCE_COL_FAM:
+ for (String columnFamily : columnFamilies) {
+ for (String table : tables) {
+ stringBuilder
+ .append("/" + table + "/" + columnFamily + ",");
+ }
+ }
+ break;
+
+ case AppConstants.RESOURCE_TABLE:
+ for (String table : tables) {
+ stringBuilder.append("/" + table + ",");
+ }
+ break;
+
+ default:
+ logger.error("Invalid resource type : " + resourceType
+ + " for hbase policy.");
+ throw restErrorUtil.createRESTException("Please provide the"
+ + " valid resource type.", MessageEnums.INVALID_INPUT_DATA);
+ }
+
+ int lastIndexOfSeperator = stringBuilder.lastIndexOf(",");
+ if (lastIndexOfSeperator > 0) {
+ String name = stringBuilder.substring(0,
+ stringBuilder.lastIndexOf(","));
+ vXResource.setName(name);
+ } else {
+ vXResource.setName(stringBuilder.toString());
+ }
+ }
+ private void createResourcePathForKnox(VXResource vXResource) {
+
+ String[] topologies = (vXResource.getTopologies() == null || vXResource
+ .getTopologies().equalsIgnoreCase("")) ? null : stringUtil.split(
+ vXResource.getTopologies(), ",");
+ String[] serviceNames = (vXResource.getServices() == null || vXResource
+ .getServices().equalsIgnoreCase("")) ? null : stringUtil
+ .split(vXResource.getServices(), ",");
+
+ StringBuilder stringBuilder = new StringBuilder();
+
+// int resourceType = vXResource.getResourceType();
+ int resourceType = xPolicyService.getResourceType(vXResource);
+
+ if (topologies == null) {
+ logger.error("Invalid resources for knox policy.");
+ throw restErrorUtil.createRESTException("Please provide the"
+ + " valid resources.", MessageEnums.INVALID_INPUT_DATA);
+ }
+
+ switch (resourceType) {
+
+ case AppConstants.RESOURCE_SERVICE_NAME:
+ for (String serviceName : serviceNames) {
+ for (String topology : topologies) {
+ stringBuilder
+ .append("/" + topology + "/" + serviceName + ",");
+ }
+ }
+ break;
+
+ case AppConstants.RESOURCE_TOPOLOGY:
+ for (String topology : topologies) {
+ stringBuilder.append("/" + topology + ",");
+ }
+ break;
+
+ default:
+ logger.error("Invalid resource type : " + resourceType
+ + " for hbase policy.");
+ throw restErrorUtil.createRESTException("Please provide the"
+ + " valid resource type.", MessageEnums.INVALID_INPUT_DATA);
+ }
+
+ int lastIndexOfSeperator = stringBuilder.lastIndexOf(",");
+ if (lastIndexOfSeperator > 0) {
+ String name = stringBuilder.substring(0,
+ stringBuilder.lastIndexOf(","));
+ vXResource.setName(name);
+ } else {
+ vXResource.setName(stringBuilder.toString());
+ }
+ }
+ private void createResourcePathForStorm(VXResource vXResource) {
+
+ String[] topologies = (vXResource.getTopologies() == null || vXResource
+ .getTopologies().equalsIgnoreCase("")) ? null : stringUtil.split(
+ vXResource.getTopologies(), ",");
+
+ String[] serviceNames = (vXResource.getServices() == null || vXResource
+ .getServices().equalsIgnoreCase("")) ? null : stringUtil
+ .split(vXResource.getServices(), ",");
+
+ StringBuilder stringBuilder = new StringBuilder();
+
+// int resourceType = vXResource.getResourceType();
+ int resourceType = xPolicyService.getResourceType(vXResource);
+
+ if (topologies == null) {
+ logger.error("Invalid resources for Storm policy.");
+ throw restErrorUtil.createRESTException("Please provide the"
+ + " valid resources.", MessageEnums.INVALID_INPUT_DATA);
+ }
+
+ switch (resourceType) {
+
+ case AppConstants.RESOURCE_TOPOLOGY:
+ for (String topology : topologies) {
+ stringBuilder.append("/" + topology + ",");
+ }
+ break;
+
+ case AppConstants.RESOURCE_SERVICE_NAME:
+ for (String serviceName : serviceNames) {
+ for (String topology : topologies) {
+ stringBuilder.append("/" + topology + "/" + serviceName + ",");
+ }
+ }
+ break;
+
+ default:
+ logger.error("Invalid resource type : " + resourceType
+ + " for Storm policy.");
+ throw restErrorUtil.createRESTException("Please provide the"
+ + " valid resource type.", MessageEnums.INVALID_INPUT_DATA);
+ }
+
+ int lastIndexOfSeperator = stringBuilder.lastIndexOf(",");
+ if (lastIndexOfSeperator > 0) {
+ String name = stringBuilder.substring(0,
+ stringBuilder.lastIndexOf(","));
+ vXResource.setName(name);
+ } else {
+ vXResource.setName(stringBuilder.toString());
+ }
+ }
+ @SuppressWarnings("unchecked")
+ private HashMap<String, Object> populatePermMap(XXResource xResource,
+ HashMap<String, Object> resourceMap, int assetType) {
+ List<XXPermMap> xPermMapList = xADaoManager.getXXPermMap()
+ .findByResourceId(xResource.getId());
+
+ Set<Long> groupList = new HashSet<Long>();
+ for (XXPermMap xPermMap : xPermMapList) {
+ groupList.add(xPermMap.getId());
+ }
+
+ List<HashMap<String, Object>> sortedPermMapGroupList = new ArrayList<HashMap<String, Object>>();
+
+ // Loop for adding group perms
+ for (XXPermMap xPermMap : xPermMapList) {
+ String groupKey = xPermMap.getPermGroup();
+ if (groupKey != null) {
+ boolean found = false;
+ for (HashMap<String, Object> sortedPermMap : sortedPermMapGroupList) {
+ if (sortedPermMap.containsValue(groupKey)) {
+ found = true;
+
+ Long groupId = xPermMap.getGroupId();
+ Long userId = xPermMap.getUserId();
+
+ if (groupId != null) {
+ Set<String> groups = (Set<String>) sortedPermMap
+ .get("groups");
+ XXGroup xGroup = xADaoManager.getXXGroup()
+ .getById(groupId);
+ if(xGroup!=null && groups != null){
+ groups.add(xGroup.getName());
+ sortedPermMap.put("groups", groups);
+ }
+ } else if (userId != null) {
+ Set<String> users = (Set<String>) sortedPermMap
+ .get("users");
+ XXUser xUser = xADaoManager.getXXUser().getById(
+ userId);
+ if (users != null && xUser != null) {
+ users.add(xUser.getName());
+ sortedPermMap.put("users", users);
+ }
+ }
+
+ Set<String> access = (Set<String>) sortedPermMap
+ .get("access");
+ String perm = AppConstants
+ .getLabelFor_XAPermType(xPermMap.getPermType());
+ access.add(perm);
+ sortedPermMap.put("access", access);
+ }
+ }
+ if (!found) {
+ HashMap<String, Object> sortedPermMap = new HashMap<String, Object>();
+ sortedPermMap.put("groupKey", xPermMap.getPermGroup());
+
+ Set<String> permSet = new HashSet<String>();
+ String perm = AppConstants.getLabelFor_XAPermType(xPermMap
+ .getPermType());
+ permSet.add(perm);
+
+ sortedPermMap.put("access", permSet);
+
+ if(assetType == AppConstants.ASSET_KNOX){
+ String[] ipAddrList = new String[0];
+ if(xPermMap.getIpAddress() != null){
+ ipAddrList = xPermMap.getIpAddress().split(",");
+ sortedPermMap.put("ipAddress", ipAddrList);
+ }else
+ sortedPermMap.put("ipAddress",ipAddrList);
+ }
+
+ Long groupId = xPermMap.getGroupId();
+ Long userId = xPermMap.getUserId();
+
+ if (groupId != null) {
+ Set<String> groupSet = new HashSet<String>();
+ XXGroup xGroup = xADaoManager.getXXGroup().getById(
+ xPermMap.getGroupId());
+ String group = xGroup.getName();
+ groupSet.add(group);
+ sortedPermMap.put("groups", groupSet);
+ } else if (userId != null) {
+ Set<String> userSet = new HashSet<String>();
+ XXUser xUser = xADaoManager.getXXUser()
+ .getById(userId);
+ String user = xUser.getName();
+ userSet.add(user);
+ sortedPermMap.put("users", userSet);
+ }
+
+ sortedPermMapGroupList.add(sortedPermMap);
+ }
+ }
+ }
+
+ for (HashMap<String, Object> sortedPermMap : sortedPermMapGroupList) {
+ sortedPermMap.remove("groupKey");
+ }
+
+ for (HashMap<String, Object> sortedPermMap : sortedPermMapGroupList) {
+ sortedPermMap.remove("groupKey");
+ }
+
+ resourceMap.put("permission", sortedPermMapGroupList);
+ return resourceMap;
+ }
+
+ private String getBooleanValue(int elementValue) {
+ if (elementValue == 1) {
+ return "1"; // BOOL_TRUE
+ }
+ return "0"; // BOOL_FALSE
+ }
+
+ public void updateDefaultPolicy(VXAsset vXAsset, String config) {
+ int assetType = vXAsset.getAssetType();
+ Map<String, String> configMap = jsonUtil.jsonToMap(config);
+ String userName = stringUtil.getValidUserName(configMap.get("username"));
+ VXResource vxResource = fetchDefaultPolicyForAsset(vXAsset.getId(),
+ assetType);
+ if (vxResource != null) {
+ UpdateDefaultPolicyUserAndPerm(vxResource, userName);
+ }
+ }
+
+ public void UpdateDefaultPolicyUserAndPerm(VXResource vXResource,
+ String userName) {
+ if (userName != null && !userName.isEmpty()) {
+ XXUser xxUser = xADaoManager.getXXUser().findByUserName(userName);
+ VXUser vXUser;
+ if (xxUser != null) {
+ vXUser = xUserService.populateViewBean(xxUser);
+ } else {
+ vXUser = new VXUser();
+ vXUser.setName(userName);
+ // FIXME hack : unnecessary.
+ vXUser.setDescription(userName);
+ vXUser = xUserService.createResource(vXUser);
+ }
+ // fetch old permission and consider only one permission for default
+ // policy
+ List<XXPermMap> xxPermMapList = xADaoManager.getXXPermMap()
+ .findByResourceId(vXResource.getId());
+ VXPermMap vXPermMap = null;
+ if (xxPermMapList != null && xxPermMapList.size() != 0) {
+ vXPermMap = xPermMapService.populateViewBean(xxPermMapList
+ .get(0));
+ }
+
+ if (vXPermMap == null) {
+ // create new permission
+ vXPermMap = new VXPermMap();
+ vXPermMap.setUserId(vXUser.getId());
+ vXPermMap.setResourceId(vXResource.getId());
+ } else {
+ // update old permission after updating userid
+ vXPermMap.setUserId(vXUser.getId());
+ xPermMapService.updateResource(vXPermMap);
+ }
+
+ }
+
+ }
+
+ public VXResource fetchDefaultPolicyForAsset(Long assetId, int assetType) {
+ String resourceName = "";
+ List<XXResource> xxResourceList = new ArrayList<XXResource>();
+ if (assetType == AppConstants.ASSET_HDFS) {
+ resourceName = "/*";
+ xxResourceList = xADaoManager.getXXResource()
+ .findByResourceNameAndAssetIdAndRecursiveFlag(resourceName,
+ assetId, AppConstants.BOOL_TRUE);
+ } else if (assetType == AppConstants.ASSET_HIVE) {
+ resourceName = "/*/*/*";
+ xxResourceList = xADaoManager.getXXResource()
+ .findByResourceNameAndAssetIdAndResourceType(resourceName,
+ assetId, AppConstants.RESOURCE_UNKNOWN);
+ } else if (assetType == AppConstants.ASSET_HBASE) {
+ resourceName = "/*/*/*";
+ xxResourceList = xADaoManager.getXXResource()
+ .findByResourceNameAndAssetIdAndResourceType(resourceName,
+ assetId, AppConstants.RESOURCE_UNKNOWN);
+ }
+ XXResource xxResource = null;
+ for (XXResource resource : xxResourceList) {
+ if (resource.getName().equals(resourceName)) {
+ xxResource = resource;
+ break;
+ }
+ }
+
+ if (xxResource != null) {
+ return xResourceService.populateViewBean(xxResource);
+ }
+ return null;
+
+ }
+
+ public XXPolicyExportAudit createPolicyAudit(
+ final XXPolicyExportAudit xXPolicyExportAudit) {
+ TransactionTemplate txTemplate = new TransactionTemplate(txManager);
+ txTemplate
+ .setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
+ XXPolicyExportAudit policyExportAudit = (XXPolicyExportAudit) txTemplate
+ .execute(new TransactionCallback<Object>() {
+ public Object doInTransaction(TransactionStatus status) {
+ if (xXPolicyExportAudit.getHttpRetCode() == HttpServletResponse.SC_NOT_MODIFIED) {
+ boolean logNotModified = PropertiesUtil
+ .getBooleanProperty(
+ "xa.log.SC_NOT_MODIFIED", false);
+ if (!logNotModified) {
+ logger.info("Not logging HttpServletResponse."
+ + "SC_NOT_MODIFIED, to enable, update "
+ + ": xa.log.SC_NOT_MODIFIED");
+ return null;
+ }
+ }
+ return xADaoManager.getXXPolicyExportAudit().create(
+ xXPolicyExportAudit);
+ }
+ });
+ return policyExportAudit;
+ }
+
+ public VXTrxLogList getReportLogs(SearchCriteria searchCriteria) {
+ if (!xaBizUtil.isAdmin()) {
+ throw restErrorUtil.create403RESTException("Permission Denied !");
+ }
+
+ if (searchCriteria != null && searchCriteria.getParamList() != null
+ && searchCriteria.getParamList().size() > 0) {
+ int clientTimeOffsetInMinute = RestUtil.getClientTimeOffset();
+ java.util.Date temp = null;
+ DateUtil dateUtil = new DateUtil();
+ if (searchCriteria.getParamList().containsKey("startDate")) {
+ temp = (java.util.Date) searchCriteria.getParamList().get(
+ "startDate");
+ temp = dateUtil.getDateFromGivenDate(temp, 0, 0, 0, 0);
+ temp = dateUtil.addTimeOffset(temp, clientTimeOffsetInMinute);
+ searchCriteria.getParamList().put("startDate", temp);
+ }
+ if (searchCriteria.getParamList().containsKey("endDate")) {
+ temp = (java.util.Date) searchCriteria.getParamList().get(
+ "endDate");
+ temp = dateUtil.getDateFromGivenDate(temp, 0, 23, 59, 59);
+ temp = dateUtil.addTimeOffset(temp, clientTimeOffsetInMinute);
+ searchCriteria.getParamList().put("endDate", temp);
+ }
+ if (searchCriteria.getParamList().containsKey("owner")) {
+ XXPortalUser xXPortalUser= xADaoManager.getXXPortalUser().findByLoginId(
+ (searchCriteria.getParamList().get("owner").toString()));
+ if(xXPortalUser!=null){
+ searchCriteria.getParamList().put("owner", xXPortalUser.getId());
+ }else{
+ searchCriteria.getParamList().put("owner", 0);
+ }
+
+ }
+
+ }
+
+ VXTrxLogList vXTrxLogList = xTrxLogService
+ .searchXTrxLogs(searchCriteria);
+ Long count=xTrxLogService
+ .searchXTrxLogsCount(searchCriteria);
+ vXTrxLogList.setTotalCount(count);
+ return vXTrxLogList;
+ }
+
+ public VXAccessAuditList getAccessLogs(SearchCriteria searchCriteria) {
+
+ if (searchCriteria != null && searchCriteria.getParamList() != null
+ && searchCriteria.getParamList().size() > 0) {
+ int clientTimeOffsetInMinute = RestUtil.getClientTimeOffset();
+ java.util.Date temp = null;
+ DateUtil dateUtil = new DateUtil();
+ if (searchCriteria.getParamList().containsKey("startDate")) {
+ temp = (java.util.Date) searchCriteria.getParamList().get(
+ "startDate");
+ temp = dateUtil.getDateFromGivenDate(temp, 0, 0, 0, 0);
+ temp = dateUtil.addTimeOffset(temp, clientTimeOffsetInMinute);
+ searchCriteria.getParamList().put("startDate", temp);
+ }
+ if (searchCriteria.getParamList().containsKey("endDate")) {
+ temp = (java.util.Date) searchCriteria.getParamList().get(
+ "endDate");
+ temp = dateUtil.getDateFromGivenDate(temp, 0, 23, 59, 59);
+ temp = dateUtil.addTimeOffset(temp, clientTimeOffsetInMinute);
+ searchCriteria.getParamList().put("endDate", temp);
+ }
+
+ }
+ if(searchCriteria.getSortType()==null){
+ searchCriteria.setSortType("desc");
+ }else if(!searchCriteria.getSortType().equalsIgnoreCase("asc")&& !searchCriteria.getSortType().equalsIgnoreCase("desc")){
+ searchCriteria.setSortType("desc");
+ }
+ return xAccessAuditService.searchXAccessAudits(searchCriteria);
+ }
+
+ public VXTrxLogList getTransactionReport(String transactionId) {
+ List<XXTrxLog> xTrxLogList = xADaoManager.getXXTrxLog()
+ .findByTransactionId(transactionId);
+ VXTrxLogList vXTrxLogList = new VXTrxLogList();
+ List<VXTrxLog> vXTrxLogs = vXTrxLogList.getVXTrxLogs();
+ for (XXTrxLog xTrxLog : xTrxLogList) {
+ VXTrxLog vXTrxLog = xTrxLogService.populateViewBean(xTrxLog);
+ if(vXTrxLog.getPreviousValue()==null || vXTrxLog.getPreviousValue().equalsIgnoreCase("null")){
+ vXTrxLog.setPreviousValue("");
+ }
+ if(vXTrxLog.getAttributeName()!=null && vXTrxLog.getAttributeName().equalsIgnoreCase("Password")){
+ vXTrxLog.setPreviousValue("*********");
+ vXTrxLog.setNewValue("***********");
+ }
+ if(vXTrxLog.getAttributeName()!=null && vXTrxLog.getAttributeName().equalsIgnoreCase("Connection Configurations")){
+ if(vXTrxLog.getPreviousValue()!=null && vXTrxLog.getPreviousValue().contains("password")){
+ String tempPreviousStr=vXTrxLog.getPreviousValue();
+ String tempPreviousArr[]=vXTrxLog.getPreviousValue().split(",");
+ for(int i=0;i<tempPreviousArr.length;i++){
+ if(tempPreviousArr[i].contains("{\"password")){
+ vXTrxLog.setPreviousValue(tempPreviousStr.replace(tempPreviousArr[i], "{\"password\":\"*****\"}"));
+ break;
+ }else if(tempPreviousArr[i].contains("\"password") && tempPreviousArr[i].contains("}")){
+ vXTrxLog.setPreviousValue(tempPreviousStr.replace(tempPreviousArr[i], "\"password\":\"******\"}"));
+ break;
+ }else if(tempPreviousArr[i].contains("\"password")){
+ vXTrxLog.setPreviousValue(tempPreviousStr.replace(tempPreviousArr[i], "\"password\":\"******\""));
+ break;
+ }
+ }
+ }
+ if(vXTrxLog.getNewValue()!=null && vXTrxLog.getNewValue().contains("password")){
+ String tempNewStr=vXTrxLog.getNewValue();
+ String tempNewArr[]=vXTrxLog.getNewValue().split(",");
+ for(int i=0;i<tempNewArr.length;i++){
+ if(tempNewArr[i].contains("{\"password")){
+ vXTrxLog.setNewValue(tempNewStr.replace(tempNewArr[i], "{\"password\":\"*****\"}"));
+ break;
+ }else if(tempNewArr[i].contains("\"password") && tempNewArr[i].contains("}")){
+ vXTrxLog.setNewValue(tempNewStr.replace(tempNewArr[i], "\"password\":\"******\"}"));
+ break;
+ }else if(tempNewArr[i].contains("\"password")){
+ vXTrxLog.setNewValue(tempNewStr.replace(tempNewArr[i], "\"password\":\"******\""));
+ break;
+ }
+ }
+ }
+ }
+ vXTrxLogs.add(vXTrxLog);
+ }
+ vXTrxLogList.setVXTrxLogs(vXTrxLogs);
+ return vXTrxLogList;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.apache.ranger.biz.AssetMgrBase#searchXPolicyExportAudits(org.apache.ranger.
+ * common.SearchCriteria)
+ */
+ @Override
+ public VXPolicyExportAuditList searchXPolicyExportAudits(
+ SearchCriteria searchCriteria) {
+ if (searchCriteria != null && searchCriteria.getParamList() != null
+ && searchCriteria.getParamList().size() > 0) {
+
+ int clientTimeOffsetInMinute = RestUtil.getClientTimeOffset();
+ java.util.Date temp = null;
+ DateUtil dateUtil = new DateUtil();
+ if (searchCriteria.getParamList().containsKey("startDate")) {
+ temp = (java.util.Date) searchCriteria.getParamList().get(
+ "startDate");
+ temp = dateUtil.getDateFromGivenDate(temp, 0, 0, 0, 0);
+ temp = dateUtil.addTimeOffset(temp, clientTimeOffsetInMinute);
+ searchCriteria.getParamList().put("startDate", temp);
+ }
+ if (searchCriteria.getParamList().containsKey("endDate")) {
+ temp = (java.util.Date) searchCriteria.getParamList().get(
+ "endDate");
+ temp = dateUtil.getDateFromGivenDate(temp, 0, 23, 59, 59);
+ temp = dateUtil.addTimeOffset(temp, clientTimeOffsetInMinute);
+ searchCriteria.getParamList().put("endDate", temp);
+ }
+ }
+
+ return xPolicyExportAuditService.searchXPolicyExportAudits(searchCriteria);
+ }
+
+ public VXAsset getXAsset(Long id){
+ UserSessionBase currentUserSession = ContextUtil
+ .getCurrentUserSession();
+ VXAsset vXAsset=null;
+ if (currentUserSession.isUserAdmin()) {
+ vXAsset = xAssetService.readResource(id);
+ if (vXAsset.getActiveStatus() == XACommonEnums.STATUS_DELETED) {
+ logger.error("Trying to read Asset which is soft deleted");
+ throw restErrorUtil.createRESTException(
+ "Repository not found for this Id : " + id,
+ MessageEnums.DATA_NOT_FOUND, id, null,
+ "Repository does not exist for this Id : " + id);
+ }
+ }else{
+ XXAsset xXAsset=xADaoManager.getXXAsset().getById(id);
+
+ if (xXAsset.getActiveStatus() == XACommonEnums.STATUS_DELETED) {
+ logger.error("Trying to read Asset which is soft deleted");
+ throw restErrorUtil.createRESTException(
+ "Repository not found for this Id : " + id,
+ MessageEnums.DATA_NOT_FOUND, id, null,
+ "Repository does not exist for this Id : " + id);
+ }
+
+ vXAsset=xAssetService.populateViewBean(xXAsset);
+ /*List<XXResource> xXResourceList=xADaoManager
+ .getXXResource().findByAssetId(id);
+ for (XXResource xXResource : xXResourceList) {
+ VXResponse vXResponse = xaBizUtil.hasPermission(xResourceService.populateViewBean(xXResource),
+ AppConstants.XA_PERM_TYPE_ADMIN);
+ if(vXResponse.getStatusCode() == VXResponse.STATUS_SUCCESS){
+ XXAsset xXAsset=xADaoManager.getXXAsset().getById(id);
+ vXAsset=xAssetService.populateViewBean(xXAsset);
+ break;
+ }
+ }*/
+ }
+ return vXAsset;
+ }
+
+ private void createDefaultUDFPolicy(VXAsset vXAsset, String config) {
+ int assetType = vXAsset.getAssetType();
+ if (assetType != AppConstants.ASSET_HIVE) {
+ return ;
+ }
+ Map<String, String> configMap = jsonUtil.jsonToMap(config);
+ String userName = stringUtil.getValidUserName(configMap.get("username"));
+ VXResource vXResource = new VXResource();
+ vXResource.setAssetId(vXAsset.getId());
+ vXResource.setAssetName(vXAsset.getName());
+ vXResource.setResourceStatus(AppConstants.STATUS_ENABLED);
+ String tempPolicyName=vXAsset.getName()+"-"+2+"-"+DateUtil.dateToString(DateUtil.getUTCDate(),"yyyyMMddH
<TRUNCATED>
[32/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hdfs-agent/src/test/java/com/xasecure/authorization/hadoop/agent/TestXaSecureFSPermissionChecker.java
----------------------------------------------------------------------
diff --git a/hdfs-agent/src/test/java/com/xasecure/authorization/hadoop/agent/TestXaSecureFSPermissionChecker.java b/hdfs-agent/src/test/java/com/xasecure/authorization/hadoop/agent/TestXaSecureFSPermissionChecker.java
deleted file mode 100644
index 68ea92c..0000000
--- a/hdfs-agent/src/test/java/com/xasecure/authorization/hadoop/agent/TestXaSecureFSPermissionChecker.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * 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 com.xasecure.authorization.hadoop.agent;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.fail;
-
-import java.util.Set;
-
-import org.apache.hadoop.fs.permission.FsAction;
-import org.apache.hadoop.hdfs.server.namenode.INode;
-import org.apache.hadoop.hdfs.server.namenode.XaSecureFSPermissionChecker;
-import org.apache.hadoop.security.UserGroupInformation;
-import org.junit.Test;
-
-import com.xasecure.authorization.hadoop.exceptions.XaSecureAccessControlException;
-
-public class TestXaSecureFSPermissionChecker {
-
- @Test
- public void nullUgiToCheckReturnsFalse() {
-
- UserGroupInformation ugi = null;
- INode inode = null;
- FsAction access = null;
- try {
- boolean result = XaSecureFSPermissionChecker.check(ugi, inode, access);
- assertFalse(result);
- } catch (XaSecureAccessControlException e) {
- fail("Unexpected exception!");
- }
- }
-
- @Test
- public void authorizeAccess() {
- String aPathName = null;
- String aPathOwnerName = null;
- String user = null;
- Set<String> groups = null;
- FsAction access = null;
- try {
- // null access returns false!
- assertFalse(XaSecureFSPermissionChecker.AuthorizeAccessForUser(aPathName, aPathOwnerName, access, user, groups));
- // None access type returns true!
- access = FsAction.NONE;
- assertFalse(XaSecureFSPermissionChecker.AuthorizeAccessForUser(aPathName, aPathOwnerName, access, user, groups));
- } catch (XaSecureAccessControlException e) {
- e.printStackTrace();
- fail("Unexpected exception!");
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hdfs-agent/src/test/java/org/apache/ranger/authorization/hadoop/agent/TestRangerFSPermissionChecker.java
----------------------------------------------------------------------
diff --git a/hdfs-agent/src/test/java/org/apache/ranger/authorization/hadoop/agent/TestRangerFSPermissionChecker.java b/hdfs-agent/src/test/java/org/apache/ranger/authorization/hadoop/agent/TestRangerFSPermissionChecker.java
new file mode 100644
index 0000000..1405bf3
--- /dev/null
+++ b/hdfs-agent/src/test/java/org/apache/ranger/authorization/hadoop/agent/TestRangerFSPermissionChecker.java
@@ -0,0 +1,67 @@
+/*
+ * 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.authorization.hadoop.agent;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.fail;
+
+import java.util.Set;
+
+import org.apache.hadoop.fs.permission.FsAction;
+import org.apache.hadoop.hdfs.server.namenode.INode;
+import org.apache.hadoop.hdfs.server.namenode.RangerFSPermissionChecker;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.ranger.authorization.hadoop.exceptions.RangerAccessControlException;
+import org.junit.Test;
+
+public class TestRangerFSPermissionChecker {
+
+ @Test
+ public void nullUgiToCheckReturnsFalse() {
+
+ UserGroupInformation ugi = null;
+ INode inode = null;
+ FsAction access = null;
+ try {
+ boolean result = RangerFSPermissionChecker.check(ugi, inode, access);
+ assertFalse(result);
+ } catch (RangerAccessControlException e) {
+ fail("Unexpected exception!");
+ }
+ }
+
+ @Test
+ public void authorizeAccess() {
+ String aPathName = null;
+ String aPathOwnerName = null;
+ String user = null;
+ Set<String> groups = null;
+ FsAction access = null;
+ try {
+ // null access returns false!
+ assertFalse(RangerFSPermissionChecker.AuthorizeAccessForUser(aPathName, aPathOwnerName, access, user, groups));
+ // None access type returns true!
+ access = FsAction.NONE;
+ assertFalse(RangerFSPermissionChecker.AuthorizeAccessForUser(aPathName, aPathOwnerName, access, user, groups));
+ } catch (RangerAccessControlException e) {
+ e.printStackTrace();
+ fail("Unexpected exception!");
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hive-agent/conf/hiveserver2-site-changes.cfg
----------------------------------------------------------------------
diff --git a/hive-agent/conf/hiveserver2-site-changes.cfg b/hive-agent/conf/hiveserver2-site-changes.cfg
index fed28df..e4aab8c 100644
--- a/hive-agent/conf/hiveserver2-site-changes.cfg
+++ b/hive-agent/conf/hiveserver2-site-changes.cfg
@@ -14,7 +14,7 @@
# limitations under the License.
# hive.server2.authentication KERBEROS mod create-if-not-exists
hive.security.authorization.enabled true mod create-if-not-exists
-hive.security.authorization.manager com.xasecure.authorization.hive.authorizer.XaSecureHiveAuthorizerFactory mod create-if-not-exists
+hive.security.authorization.manager org.apache.ranger.authorization.hive.authorizer.RangerHiveAuthorizerFactory mod create-if-not-exists
hive.security.authenticator.manager org.apache.hadoop.hive.ql.security.SessionStateUserAuthenticator mod create-if-not-exists
# hive.conf.restricted.list hive.server2.authentication append create-if-not-exists ,
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hive-agent/conf/xasecure-hive-security-changes.cfg
----------------------------------------------------------------------
diff --git a/hive-agent/conf/xasecure-hive-security-changes.cfg b/hive-agent/conf/xasecure-hive-security-changes.cfg
index 5c4b072..75fbdea 100644
--- a/hive-agent/conf/xasecure-hive-security-changes.cfg
+++ b/hive-agent/conf/xasecure-hive-security-changes.cfg
@@ -16,7 +16,7 @@
# Change the original policy parameter to work with policy manager based.
#
#
-hive.authorization.verifier.classname com.xasecure.pdp.hive.XASecureAuthorizer mod create-if-not-exists
+hive.authorization.verifier.classname org.apache.ranger.pdp.hive.RangerAuthorizer mod create-if-not-exists
xasecure.hive.policymgr.url %POLICY_MGR_URL%/service/assets/policyList/%REPOSITORY_NAME% mod create-if-not-exists
xasecure.hive.policymgr.url.saveAsFile /tmp/hive_%REPOSITORY_NAME%_json mod create-if-not-exists
xasecure.hive.policymgr.url.laststoredfile %POLICY_CACHE_FILE_PATH%/hive_%REPOSITORY_NAME%_json mod create-if-not-exists
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hive-agent/conf/xasecure-hive-security.xml
----------------------------------------------------------------------
diff --git a/hive-agent/conf/xasecure-hive-security.xml b/hive-agent/conf/xasecure-hive-security.xml
index b8cca10..ebc0b92 100644
--- a/hive-agent/conf/xasecure-hive-security.xml
+++ b/hive-agent/conf/xasecure-hive-security.xml
@@ -22,7 +22,7 @@
<!-- The following property is used to select appropriate XASecure Authorizer Module (filebased, policymanager based) -->
<property>
<name>hive.authorization.verifier.classname</name>
- <value>com.xasecure.pdp.hive.XASecureAuthorizer</value>
+ <value>org.apache.ranger.pdp.hive.RangerAuthorizer</value>
<description>
Class Name of the authorization Module
</description>
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hive-agent/scripts/install.sh
----------------------------------------------------------------------
diff --git a/hive-agent/scripts/install.sh b/hive-agent/scripts/install.sh
index 59b9cb9..9c6bb3a 100644
--- a/hive-agent/scripts/install.sh
+++ b/hive-agent/scripts/install.sh
@@ -297,7 +297,7 @@ do
if [ $? -eq 0 ]
then
cp="${install_dir}/installer/lib/*:${hdp_dir}/*:${hdp_lib_dir}/*"
- java -cp "${cp}" com.xasecure.utils.install.XmlConfigChanger -i ${archivefn} -o ${newfn} -c ${f} ${PROP_ARGS}
+ java -cp "${cp}" org.apache.ranger.utils.install.XmlConfigChanger -i ${archivefn} -o ${newfn} -c ${f} ${PROP_ARGS}
if [ $? -eq 0 ]
then
diff -w ${newfn} ${fullpathorgfn} > /dev/null 2>&1
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hive-agent/src/main/java/com/xasecure/authorization/hive/XaHiveAccessContext.java
----------------------------------------------------------------------
diff --git a/hive-agent/src/main/java/com/xasecure/authorization/hive/XaHiveAccessContext.java b/hive-agent/src/main/java/com/xasecure/authorization/hive/XaHiveAccessContext.java
deleted file mode 100644
index 570456c..0000000
--- a/hive-agent/src/main/java/com/xasecure/authorization/hive/XaHiveAccessContext.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * 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 com.xasecure.authorization.hive;
-
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzContext;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzSessionContext;
-
-
-public class XaHiveAccessContext {
- private String mClientIpAddress;
- private String mClientType;
- private String mCommandString;
- private String mSessionString;
-
- public XaHiveAccessContext(HiveAuthzContext context, HiveAuthzSessionContext sessionContext) {
- if(context != null) {
- mClientIpAddress = context.getIpAddress();
- mCommandString = context.getCommandString();
- }
-
- if(sessionContext != null) {
- mClientType = sessionContext.getClientType().name();
- mSessionString = sessionContext.getSessionString();
- }
- }
-
- public String getClientIpAddress() {
- return mClientIpAddress;
- }
-
- public void setClientIpAddress(String clientIpAddress) {
- this.mClientIpAddress = clientIpAddress;
- }
-
- public String getClientType() {
- return mClientType;
- }
-
- public void setClientType(String clientType) {
- this.mClientType = clientType;
- }
-
- public String getCommandString() {
- return mCommandString;
- }
-
- public void setCommandString(String commandString) {
- this.mCommandString = commandString;
- }
-
- public String getSessionString() {
- return mSessionString;
- }
-
- public void setSessionString(String sessionString) {
- this.mSessionString = sessionString;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hive-agent/src/main/java/com/xasecure/authorization/hive/XaHiveAccessVerifier.java
----------------------------------------------------------------------
diff --git a/hive-agent/src/main/java/com/xasecure/authorization/hive/XaHiveAccessVerifier.java b/hive-agent/src/main/java/com/xasecure/authorization/hive/XaHiveAccessVerifier.java
deleted file mode 100644
index 2dcf5f9..0000000
--- a/hive-agent/src/main/java/com/xasecure/authorization/hive/XaHiveAccessVerifier.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * 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 com.xasecure.authorization.hive;
-
-import org.apache.hadoop.security.UserGroupInformation;
-
-
-public interface XaHiveAccessVerifier {
- public boolean isAccessAllowed(UserGroupInformation ugi, XaHiveObjectAccessInfo objAccessInfo) ;
-
- public boolean isAudited(XaHiveObjectAccessInfo objAccessInfo) ;
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hive-agent/src/main/java/com/xasecure/authorization/hive/XaHiveAccessVerifierFactory.java
----------------------------------------------------------------------
diff --git a/hive-agent/src/main/java/com/xasecure/authorization/hive/XaHiveAccessVerifierFactory.java b/hive-agent/src/main/java/com/xasecure/authorization/hive/XaHiveAccessVerifierFactory.java
deleted file mode 100644
index 057b930..0000000
--- a/hive-agent/src/main/java/com/xasecure/authorization/hive/XaHiveAccessVerifierFactory.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * 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 com.xasecure.authorization.hive;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import com.xasecure.authorization.hadoop.config.XaSecureConfiguration;
-import com.xasecure.authorization.hadoop.constants.XaSecureHadoopConstants;
-
-public class XaHiveAccessVerifierFactory {
-
- private static final Log LOG = LogFactory.getLog(XaHiveAccessVerifierFactory.class) ;
-
- private static XaHiveAccessVerifier hiveAccessVerififer = null ;
-
- public static XaHiveAccessVerifier getInstance() {
- if (hiveAccessVerififer == null) {
- synchronized(XaHiveAccessVerifierFactory.class) {
- XaHiveAccessVerifier temp = hiveAccessVerififer ;
- if (temp == null) {
- String hiveAccessVerifierClassName = XaSecureConfiguration.getInstance().get(XaSecureHadoopConstants.HIVE_ACCESS_VERIFIER_CLASS_NAME_PROP, XaSecureHadoopConstants.HIVE_ACCESS_VERIFIER_CLASS_NAME_DEFAULT_VALUE ) ;
-
- if (hiveAccessVerifierClassName != null) {
- LOG.info("Hive Access Verification class [" + hiveAccessVerifierClassName + "] - Being built");
- try {
- hiveAccessVerififer = (XaHiveAccessVerifier) (Class.forName(hiveAccessVerifierClassName).newInstance()) ;
- LOG.info("Created a new instance of class: [" + hiveAccessVerifierClassName + "] for Hive Access verification.");
- } catch (InstantiationException e) {
- LOG.error("Unable to create HiveAccess Verifier: [" + hiveAccessVerifierClassName + "]", e);
- } catch (IllegalAccessException e) {
- LOG.error("Unable to create HiveAccess Verifier: [" + hiveAccessVerifierClassName + "]", e);
- } catch (ClassNotFoundException e) {
- LOG.error("Unable to create HiveAccess Verifier: [" + hiveAccessVerifierClassName + "]", e);
- } catch (Throwable t) {
- LOG.error("Unable to create HiveAccess Verifier: [" + hiveAccessVerifierClassName + "]", t);
- }
- finally {
- LOG.info("Created a new instance of class: [" + hiveAccessVerifierClassName + "] for Hive Access verification. (" + hiveAccessVerififer + ")");
- }
- }
- }
- else {
- LOG.error("Unable to obtain hiveAccessVerifier [" + XaSecureHadoopConstants.HIVE_ACCESS_VERIFIER_CLASS_NAME_PROP + "]");
- }
- }
- }
- return hiveAccessVerififer ;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hive-agent/src/main/java/com/xasecure/authorization/hive/XaHiveObjectAccessInfo.java
----------------------------------------------------------------------
diff --git a/hive-agent/src/main/java/com/xasecure/authorization/hive/XaHiveObjectAccessInfo.java b/hive-agent/src/main/java/com/xasecure/authorization/hive/XaHiveObjectAccessInfo.java
deleted file mode 100644
index 36a6a42..0000000
--- a/hive-agent/src/main/java/com/xasecure/authorization/hive/XaHiveObjectAccessInfo.java
+++ /dev/null
@@ -1,240 +0,0 @@
-/*
- * 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 com.xasecure.authorization.hive;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.xasecure.authorization.utils.StringUtil;
-
-public class XaHiveObjectAccessInfo {
- public enum HiveObjectType { NONE, DATABASE, TABLE, VIEW, PARTITION, INDEX, COLUMN, FUNCTION, URI };
- public enum HiveAccessType { NONE, CREATE, ALTER, DROP, INDEX, LOCK, SELECT, UPDATE, USE, ALL, ADMIN };
-
- private String mOperType = null;
- private XaHiveAccessContext mContext = null;
- private HiveAccessType mAccessType = HiveAccessType.NONE;
- private HiveObjectType mObjectType = HiveObjectType.NONE;
- private String mDatabase = null;
- private String mTable = null;
- private String mView = null;
- private String mPartition = null;
- private String mIndex = null;
- private List<String> mColumns = null;
- private String mFunction = null;
- private String mUri = null;
- private String mDeniedObjectName = null;
-
- public XaHiveObjectAccessInfo(String operType, XaHiveAccessContext context, HiveAccessType accessType, String dbName) {
- this(operType, context, accessType, dbName, null, HiveObjectType.DATABASE, dbName);
- }
-
- public XaHiveObjectAccessInfo(String operType, XaHiveAccessContext context, HiveAccessType accessType, String dbName, String tblName) {
- this(operType, context, accessType, dbName, tblName, HiveObjectType.TABLE, tblName);
- }
-
- public XaHiveObjectAccessInfo(String operType, XaHiveAccessContext context, HiveAccessType accessType, String dbName, HiveObjectType objType, String objName) {
- this(operType, context, accessType, dbName, null, objType, objName);
- }
-
- public XaHiveObjectAccessInfo(String operType, XaHiveAccessContext context, HiveAccessType accessType, HiveObjectType objType, String objName) {
- this(operType, context, accessType, null, null, objType, objName);
- }
-
- public XaHiveObjectAccessInfo(String operType, XaHiveAccessContext context, HiveAccessType accessType, String dbName, String tblOrViewName, List<String> columns) {
- mOperType = operType;
- mContext = context;
- mAccessType = accessType;
- mObjectType = HiveObjectType.COLUMN;
- mDatabase = dbName;
- mTable = tblOrViewName;
- mView = tblOrViewName;
- mColumns = columns;
- }
-
- public XaHiveObjectAccessInfo(String operType, XaHiveAccessContext context, HiveAccessType accessType, String dbName, String tblName, HiveObjectType objType, String objName) {
- mOperType = operType;
- mContext = context;
- mAccessType = accessType;
- mObjectType = objType;
- mDatabase = dbName;
- mTable = tblName;
- mView = tblName;
-
- if(objName != null && ! objName.trim().isEmpty()) {
- switch(objType) {
- case DATABASE:
- mDatabase = objName;
- break;
-
- case TABLE:
- mTable = objName;
- break;
-
- case VIEW:
- mView = objName;
- break;
-
- case PARTITION:
- mPartition = objName;
- break;
-
- case INDEX:
- mIndex = objName;
- break;
-
- case COLUMN:
- mColumns = new ArrayList<String>();
- mColumns.add(objName);
- break;
-
- case FUNCTION:
- mFunction = objName;
- break;
-
- case URI:
- mUri = objName;
- break;
-
- case NONE:
- break;
- }
- }
- }
-
- public String getOperType() {
- return mOperType;
- }
-
- public XaHiveAccessContext getContext() {
- return mContext;
- }
-
- public HiveAccessType getAccessType() {
- return mAccessType;
- }
-
- public HiveObjectType getObjectType() {
- return mObjectType;
- }
-
- public String getDatabase() {
- return mDatabase;
- }
-
- public String getTable() {
- return mTable;
- }
-
- public String getView() {
- return mView;
- }
-
- public String getPartition() {
- return mPartition;
- }
-
- public String getIndex() {
- return mIndex;
- }
-
- public List<String> getColumns() {
- return mColumns;
- }
-
- public String getFunction() {
- return mFunction;
- }
-
- public String getUri() {
- return mUri;
- }
-
- public void setDeinedObjectName(String deniedObjectName) {
- mDeniedObjectName = deniedObjectName;
- }
-
- public String getDeinedObjectName() {
- return mDeniedObjectName;
- }
-
- public String getObjectName() {
- String objName = null;
-
- if(this.mObjectType == HiveObjectType.URI) {
- objName = mUri;
- } else {
- String tblName = null;
- String colName = null;
-
- if(! StringUtil.isEmpty(mTable))
- tblName = mTable;
- else if(! StringUtil.isEmpty(mView))
- tblName = mView;
- else if(! StringUtil.isEmpty(mFunction))
- tblName = mFunction;
-
- if(! StringUtil.isEmpty(mColumns))
- colName = StringUtil.toString(mColumns);
- else if(! StringUtil.isEmpty(mIndex))
- colName = mIndex;
-
- objName = getObjectName(mDatabase, tblName, colName);
- }
-
- return objName;
- }
-
- public static String getObjectName(String dbName, String tblName, String colName) {
- String objName = StringUtil.isEmpty(dbName) ? "" : dbName;
-
- if(!StringUtil.isEmpty(tblName)) {
- objName += ("/" + tblName);
-
- if(!StringUtil.isEmpty(colName)) {
- objName += ("/" + colName);
- }
- }
-
- return objName;
- }
-
- @Override
- public boolean equals(Object obj) {
- boolean ret = false;
-
- if(obj != null && obj instanceof XaHiveObjectAccessInfo) {
- XaHiveObjectAccessInfo that = (XaHiveObjectAccessInfo)obj;
-
- ret = StringUtil.equalsIgnoreCase(mOperType, that.mOperType)
- && mAccessType == that.mAccessType
- && mObjectType == that.mObjectType
- && StringUtil.equalsIgnoreCase(mDatabase, that.mDatabase)
- && StringUtil.equalsIgnoreCase(mTable, that.mTable)
- && StringUtil.equalsIgnoreCase(mView, that.mView)
- && StringUtil.equalsIgnoreCase(mPartition, that.mPartition)
- && StringUtil.equalsIgnoreCase(mIndex, that.mIndex)
- && StringUtil.equalsIgnoreCase(mColumns, that.mColumns)
- ;
- }
-
- return ret;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hive-agent/src/main/java/com/xasecure/authorization/hive/authorizer/XaSecureHiveAuthorizer.java
----------------------------------------------------------------------
diff --git a/hive-agent/src/main/java/com/xasecure/authorization/hive/authorizer/XaSecureHiveAuthorizer.java b/hive-agent/src/main/java/com/xasecure/authorization/hive/authorizer/XaSecureHiveAuthorizer.java
deleted file mode 100644
index 2c2dd80..0000000
--- a/hive-agent/src/main/java/com/xasecure/authorization/hive/authorizer/XaSecureHiveAuthorizer.java
+++ /dev/null
@@ -1,850 +0,0 @@
-/*
- * 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 com.xasecure.authorization.hive.authorizer;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.fs.FileStatus;
-import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.fs.permission.FsAction;
-import org.apache.hadoop.hive.common.FileUtils;
-import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.ql.security.HiveAuthenticationProvider;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAccessControlException;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzContext;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzPluginException;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzSessionContext;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveMetastoreClientFactory;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveOperationType;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HivePrincipal;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HivePrivilege;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HivePrivilegeObject;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HivePrivilegeObject.HivePrivObjectActionType;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HivePrivilegeObject.HivePrivilegeObjectType;
-import org.apache.hadoop.security.UserGroupInformation;
-
-import com.xasecure.admin.client.XaAdminRESTClient;
-import com.xasecure.admin.client.datatype.GrantRevokeData;
-import com.xasecure.audit.model.EnumRepositoryType;
-import com.xasecure.audit.model.HiveAuditEvent;
-import com.xasecure.audit.provider.AuditProviderFactory;
-import com.xasecure.authorization.hadoop.config.XaSecureConfiguration;
-import com.xasecure.authorization.hadoop.constants.XaSecureHadoopConstants;
-import com.xasecure.authorization.hive.XaHiveAccessContext;
-import com.xasecure.authorization.hive.XaHiveAccessVerifier;
-import com.xasecure.authorization.hive.XaHiveAccessVerifierFactory;
-import com.xasecure.authorization.hive.XaHiveObjectAccessInfo;
-import com.xasecure.authorization.hive.XaHiveObjectAccessInfo.HiveAccessType;
-import com.xasecure.authorization.hive.XaHiveObjectAccessInfo.HiveObjectType;
-import com.xasecure.authorization.utils.StringUtil;
-
-public class XaSecureHiveAuthorizer extends XaSecureHiveAuthorizerBase {
- private static final Log LOG = LogFactory.getLog(XaSecureHiveAuthorizer.class) ;
-
- private static final String XaSecureModuleName = XaSecureConfiguration.getInstance().get(XaSecureHadoopConstants.AUDITLOG_XASECURE_MODULE_ACL_NAME_PROP , XaSecureHadoopConstants.DEFAULT_XASECURE_MODULE_ACL_NAME) ;
- private static final String repositoryName = XaSecureConfiguration.getInstance().get(XaSecureHadoopConstants.AUDITLOG_REPOSITORY_NAME_PROP);
- private static final boolean UpdateXaPoliciesOnGrantRevoke = XaSecureConfiguration.getInstance().getBoolean(XaSecureHadoopConstants.HIVE_UPDATE_XAPOLICIES_ON_GRANT_REVOKE_PROP, XaSecureHadoopConstants.HIVE_UPDATE_XAPOLICIES_ON_GRANT_REVOKE_DEFAULT_VALUE);
-
- private XaHiveAccessVerifier mHiveAccessVerifier = null ;
-
-
- public XaSecureHiveAuthorizer(HiveMetastoreClientFactory metastoreClientFactory,
- HiveConf hiveConf,
- HiveAuthenticationProvider hiveAuthenticator,
- HiveAuthzSessionContext sessionContext) {
- super(metastoreClientFactory, hiveConf, hiveAuthenticator, sessionContext);
-
- LOG.debug("XaSecureHiveAuthorizer.XaSecureHiveAuthorizer()");
-
- mHiveAccessVerifier = XaHiveAccessVerifierFactory.getInstance() ;
-
- if(!XaSecureConfiguration.getInstance().isAuditInitDone()) {
- if(sessionContext != null) {
- AuditProviderFactory.ApplicationType appType = AuditProviderFactory.ApplicationType.Unknown;
-
- switch(sessionContext.getClientType()) {
- case HIVECLI:
- appType = AuditProviderFactory.ApplicationType.HiveCLI;
- break;
-
- case HIVESERVER2:
- appType = AuditProviderFactory.ApplicationType.HiveServer2;
- break;
- }
-
- XaSecureConfiguration.getInstance().initAudit(appType);
- }
- }
- }
-
-
- /**
- * Grant privileges for principals on the object
- * @param hivePrincipals
- * @param hivePrivileges
- * @param hivePrivObject
- * @param grantorPrincipal
- * @param grantOption
- * @throws HiveAuthzPluginException
- * @throws HiveAccessControlException
- */
- @Override
- public void grantPrivileges(List<HivePrincipal> hivePrincipals,
- List<HivePrivilege> hivePrivileges,
- HivePrivilegeObject hivePrivObject,
- HivePrincipal grantorPrincipal,
- boolean grantOption)
- throws HiveAuthzPluginException, HiveAccessControlException {
- if(! UpdateXaPoliciesOnGrantRevoke) {
- throw new HiveAuthzPluginException("GRANT/REVOKE not supported in Argus HiveAuthorizer. Please use Argus Security Admin to setup access control.");
- }
-
- boolean isSuccess = false;
- XaHiveObjectAccessInfo objAccessInfo = getObjectAccessInfo(HiveOperationType.GRANT_PRIVILEGE, hivePrivObject, new XaHiveAccessContext(null, getHiveAuthzSessionContext()), true);
-
- try {
- GrantRevokeData grData = createGrantRevokeData(objAccessInfo, hivePrincipals, hivePrivileges, getGrantorUsername(grantorPrincipal), grantOption);
-
- if(LOG.isDebugEnabled()) {
- LOG.debug("grantPrivileges(): " + grData.toJson());
- }
-
- XaAdminRESTClient xaAdmin = new XaAdminRESTClient();
-
- xaAdmin.grantPrivilege(grData);
-
- isSuccess = true;
- } catch(Exception excp) {
- throw new HiveAccessControlException(excp);
- } finally {
- if(mHiveAccessVerifier.isAudited(objAccessInfo)) {
- UserGroupInformation ugi = this.getCurrentUserGroupInfo();
-
- // Note: failed return from REST call will be logged as 'DENIED'
- logAuditEvent(ugi, objAccessInfo, isSuccess);
- }
- }
- }
-
- /**
- * Revoke privileges for principals on the object
- * @param hivePrincipals
- * @param hivePrivileges
- * @param hivePrivObject
- * @param grantorPrincipal
- * @param grantOption
- * @throws HiveAuthzPluginException
- * @throws HiveAccessControlException
- */
- @Override
- public void revokePrivileges(List<HivePrincipal> hivePrincipals,
- List<HivePrivilege> hivePrivileges,
- HivePrivilegeObject hivePrivObject,
- HivePrincipal grantorPrincipal,
- boolean grantOption)
- throws HiveAuthzPluginException, HiveAccessControlException {
- if(! UpdateXaPoliciesOnGrantRevoke) {
- throw new HiveAuthzPluginException("GRANT/REVOKE not supported in Argus HiveAuthorizer. Please use Argus Security Admin to setup access control.");
- }
-
- boolean isSuccess = false;
- XaHiveObjectAccessInfo objAccessInfo = getObjectAccessInfo(HiveOperationType.REVOKE_PRIVILEGE, hivePrivObject, new XaHiveAccessContext(null, getHiveAuthzSessionContext()), true);
-
- try {
- GrantRevokeData grData = createGrantRevokeData(objAccessInfo, hivePrincipals, hivePrivileges, getGrantorUsername(grantorPrincipal), grantOption);
-
- if(LOG.isDebugEnabled()) {
- LOG.debug("revokePrivileges(): " + grData.toJson());
- }
-
- XaAdminRESTClient xaAdmin = new XaAdminRESTClient();
-
- xaAdmin.revokePrivilege(grData);
-
- isSuccess = true;
- } catch(Exception excp) {
- throw new HiveAccessControlException(excp);
- } finally {
- if(mHiveAccessVerifier.isAudited(objAccessInfo)) {
- UserGroupInformation ugi = this.getCurrentUserGroupInfo();
-
- // Note: failed return from REST call will be logged as 'DENIED'
- logAuditEvent(ugi, objAccessInfo, isSuccess);
- }
- }
- }
-
- /**
- * Check if user has privileges to do this action on these objects
- * @param hiveOpType
- * @param inputsHObjs
- * @param outputHObjs
- * @param context
- * @throws HiveAuthzPluginException
- * @throws HiveAccessControlException
- */
- @Override
- public void checkPrivileges(HiveOperationType hiveOpType,
- List<HivePrivilegeObject> inputHObjs,
- List<HivePrivilegeObject> outputHObjs,
- HiveAuthzContext context)
- throws HiveAuthzPluginException, HiveAccessControlException {
-
- UserGroupInformation ugi = this.getCurrentUserGroupInfo();
-
- if(ugi == null) {
- throw new HiveAccessControlException("Permission denied: user information not available");
- }
-
- XaHiveAccessContext hiveContext = this.getAccessContext(context);
-
- if(LOG.isDebugEnabled()) {
- LOG.debug(toString(hiveOpType, inputHObjs, outputHObjs, hiveContext));
- }
-
- if(hiveOpType == HiveOperationType.DFS) {
- handleDfsCommand(hiveOpType, inputHObjs, outputHObjs, hiveContext);
-
- return;
- }
-
- List<XaHiveObjectAccessInfo> objAccessList = getObjectAccessInfo(hiveOpType, inputHObjs, outputHObjs, hiveContext);
-
- for(XaHiveObjectAccessInfo objAccessInfo : objAccessList) {
- boolean ret = false;
-
- if(objAccessInfo.getObjectType() == HiveObjectType.URI) {
- ret = isURIAccessAllowed(ugi, objAccessInfo.getAccessType(), objAccessInfo.getUri(), getHiveConf());
- } else if(objAccessInfo.getAccessType() != HiveAccessType.ADMIN) {
- ret = mHiveAccessVerifier.isAccessAllowed(ugi, objAccessInfo);
- }
-
- if(! ret) {
- if(mHiveAccessVerifier.isAudited(objAccessInfo)) {
- logAuditEvent(ugi, objAccessInfo, false);
- }
-
- String deniedObjectName = objAccessInfo.getDeinedObjectName();
-
- if(StringUtil.isEmpty(deniedObjectName)) {
- deniedObjectName = objAccessInfo.getObjectName();
- }
-
- throw new HiveAccessControlException(String.format("Permission denied: user [%s] does not have [%s] privilege on [%s]",
- ugi.getShortUserName(), objAccessInfo.getAccessType().name(), deniedObjectName));
- }
- }
-
- // access is allowed; audit all accesses
- for(XaHiveObjectAccessInfo objAccessInfo : objAccessList) {
- if(mHiveAccessVerifier.isAudited(objAccessInfo)) {
- logAuditEvent(ugi, objAccessInfo, true);
- }
- }
- }
-
- private List<XaHiveObjectAccessInfo> getObjectAccessInfo(HiveOperationType hiveOpType,
- List<HivePrivilegeObject> inputsHObjs,
- List<HivePrivilegeObject> outputHObjs,
- XaHiveAccessContext context) {
- List<XaHiveObjectAccessInfo> ret = new ArrayList<XaHiveObjectAccessInfo>();
-
- if(inputsHObjs != null) {
- for(HivePrivilegeObject hiveObj : inputsHObjs) {
- XaHiveObjectAccessInfo hiveAccessObj = getObjectAccessInfo(hiveOpType, hiveObj, context, true);
-
- if( hiveAccessObj != null
- && hiveAccessObj.getAccessType() != HiveAccessType.ADMIN // access check is performed at the Argus policy server, as a part of updating the permissions
- && !ret.contains(hiveAccessObj)) {
- ret.add(hiveAccessObj);
- }
- }
- }
-
- if(outputHObjs != null) {
- for(HivePrivilegeObject hiveObj : outputHObjs) {
- XaHiveObjectAccessInfo hiveAccessObj = getObjectAccessInfo(hiveOpType, hiveObj, context, false);
-
- if( hiveAccessObj != null
- && hiveAccessObj.getAccessType() != HiveAccessType.ADMIN // access check is performed at the Argus policy server, as a part of updating the permissions
- && !ret.contains(hiveAccessObj)) {
- ret.add(hiveAccessObj);
- }
- }
- }
-
- if(ret.size() == 0 && LOG.isDebugEnabled()) {
- LOG.debug("getObjectAccessInfo(): no objects found for access check! " + toString(hiveOpType, inputsHObjs, outputHObjs, context));
- }
-
- return ret;
- }
-
- private XaHiveObjectAccessInfo getObjectAccessInfo(HiveOperationType hiveOpType, HivePrivilegeObject hiveObj, XaHiveAccessContext context, boolean isInput) {
- XaHiveObjectAccessInfo ret = null;
-
- HiveObjectType objectType = getObjectType(hiveObj, hiveOpType);
- HiveAccessType accessType = getAccessType(hiveObj, hiveOpType, isInput);
- String operType = hiveOpType.name();
-
- switch(objectType) {
- case DATABASE:
- ret = new XaHiveObjectAccessInfo(operType, context, accessType, hiveObj.getDbname());
- break;
-
- case TABLE:
- ret = new XaHiveObjectAccessInfo(operType, context, accessType, hiveObj.getDbname(), HiveObjectType.TABLE, hiveObj.getObjectName());
- break;
-
- case VIEW:
- ret = new XaHiveObjectAccessInfo(operType, context, accessType, hiveObj.getDbname(), HiveObjectType.VIEW, hiveObj.getObjectName());
- break;
-
- case PARTITION:
- ret = new XaHiveObjectAccessInfo(operType, context, accessType, hiveObj.getDbname(), HiveObjectType.PARTITION, hiveObj.getObjectName());
- break;
-
- case INDEX:
- String indexName = "?"; // TODO:
- ret = new XaHiveObjectAccessInfo(operType, context, accessType, hiveObj.getDbname(), hiveObj.getObjectName(), HiveObjectType.INDEX, indexName);
- break;
-
- case COLUMN:
- ret = new XaHiveObjectAccessInfo(operType, context, accessType, hiveObj.getDbname(), hiveObj.getObjectName(), hiveObj.getColumns());
- break;
-
- case FUNCTION:
- ret = new XaHiveObjectAccessInfo(operType, context, accessType, hiveObj.getDbname(), HiveObjectType.FUNCTION, hiveObj.getObjectName());
- break;
-
- case URI:
- ret = new XaHiveObjectAccessInfo(operType, context, accessType, HiveObjectType.URI, hiveObj.getObjectName());
- break;
-
- case NONE:
- break;
- }
-
- return ret;
- }
-
- private HiveObjectType getObjectType(HivePrivilegeObject hiveObj, HiveOperationType hiveOpType) {
- HiveObjectType objType = HiveObjectType.NONE;
-
- switch(hiveObj.getType()) {
- case DATABASE:
- objType = HiveObjectType.DATABASE;
- break;
-
- case PARTITION:
- objType = HiveObjectType.PARTITION;
- break;
-
- case TABLE_OR_VIEW:
- String hiveOpTypeName = hiveOpType.name().toLowerCase();
- if(hiveOpTypeName.contains("index")) {
- objType = HiveObjectType.INDEX;
- } else if(! StringUtil.isEmpty(hiveObj.getColumns())) {
- objType = HiveObjectType.COLUMN;
- } else if(hiveOpTypeName.contains("view")) {
- objType = HiveObjectType.VIEW;
- } else {
- objType = HiveObjectType.TABLE;
- }
- break;
-
- case FUNCTION:
- objType = HiveObjectType.FUNCTION;
- break;
-
- case DFS_URI:
- case LOCAL_URI:
- objType = HiveObjectType.URI;
- break;
-
- case COMMAND_PARAMS:
- case GLOBAL:
- break;
-
- case COLUMN:
- // Thejas: this value is unused in Hive; the case should not be hit.
- break;
- }
-
- return objType;
- }
-
- private HiveAccessType getAccessType(HivePrivilegeObject hiveObj, HiveOperationType hiveOpType, boolean isInput) {
- HiveAccessType accessType = HiveAccessType.NONE;
- HivePrivObjectActionType objectActionType = hiveObj.getActionType();
-
- switch(objectActionType) {
- case INSERT:
- case INSERT_OVERWRITE:
- case UPDATE:
- case DELETE:
- accessType = HiveAccessType.UPDATE;
- break;
- case OTHER:
- switch(hiveOpType) {
- case CREATEDATABASE:
- if(hiveObj.getType() == HivePrivilegeObjectType.DATABASE) {
- accessType = HiveAccessType.CREATE;
- }
- break;
-
- case CREATEFUNCTION:
- if(hiveObj.getType() == HivePrivilegeObjectType.FUNCTION) {
- accessType = HiveAccessType.CREATE;
- }
- break;
-
- case CREATETABLE:
- case CREATEVIEW:
- case CREATETABLE_AS_SELECT:
- if(hiveObj.getType() == HivePrivilegeObjectType.TABLE_OR_VIEW) {
- accessType = isInput ? HiveAccessType.SELECT : HiveAccessType.CREATE;
- }
- break;
-
- case ALTERDATABASE:
- case ALTERDATABASE_OWNER:
- case ALTERINDEX_PROPS:
- case ALTERINDEX_REBUILD:
- case ALTERPARTITION_BUCKETNUM:
- case ALTERPARTITION_FILEFORMAT:
- case ALTERPARTITION_LOCATION:
- case ALTERPARTITION_MERGEFILES:
- case ALTERPARTITION_PROTECTMODE:
- case ALTERPARTITION_SERDEPROPERTIES:
- case ALTERPARTITION_SERIALIZER:
- case ALTERTABLE_ADDCOLS:
- case ALTERTABLE_ADDPARTS:
- case ALTERTABLE_ARCHIVE:
- case ALTERTABLE_BUCKETNUM:
- case ALTERTABLE_CLUSTER_SORT:
- case ALTERTABLE_COMPACT:
- case ALTERTABLE_DROPPARTS:
- case ALTERTABLE_FILEFORMAT:
- case ALTERTABLE_LOCATION:
- case ALTERTABLE_MERGEFILES:
- case ALTERTABLE_PARTCOLTYPE:
- case ALTERTABLE_PROPERTIES:
- case ALTERTABLE_PROTECTMODE:
- case ALTERTABLE_RENAME:
- case ALTERTABLE_RENAMECOL:
- case ALTERTABLE_RENAMEPART:
- case ALTERTABLE_REPLACECOLS:
- case ALTERTABLE_SERDEPROPERTIES:
- case ALTERTABLE_SERIALIZER:
- case ALTERTABLE_SKEWED:
- case ALTERTABLE_TOUCH:
- case ALTERTABLE_UNARCHIVE:
- case ALTERTABLE_UPDATEPARTSTATS:
- case ALTERTABLE_UPDATETABLESTATS:
- case ALTERTBLPART_SKEWED_LOCATION:
- case ALTERVIEW_AS:
- case ALTERVIEW_PROPERTIES:
- case ALTERVIEW_RENAME:
- case DROPVIEW_PROPERTIES:
- accessType = HiveAccessType.ALTER;
- break;
-
- case DROPFUNCTION:
- case DROPINDEX:
- case DROPTABLE:
- case DROPVIEW:
- case DROPDATABASE:
- accessType = HiveAccessType.DROP;
- break;
-
- case CREATEINDEX:
- accessType = HiveAccessType.INDEX;
- break;
-
- case IMPORT:
- case EXPORT:
- case LOAD:
- accessType = isInput ? HiveAccessType.SELECT : HiveAccessType.UPDATE;
- break;
-
- case LOCKDB:
- case LOCKTABLE:
- case UNLOCKDB:
- case UNLOCKTABLE:
- accessType = HiveAccessType.LOCK;
- break;
-
- case QUERY:
- case SHOW_TABLESTATUS:
- case SHOW_CREATETABLE:
- case SHOWCOLUMNS:
- case SHOWINDEXES:
- case SHOWPARTITIONS:
- case SHOW_TBLPROPERTIES:
- case DESCTABLE:
- case ANALYZE_TABLE:
- accessType = HiveAccessType.SELECT;
- break;
-
- case SWITCHDATABASE:
- case DESCDATABASE:
- accessType = HiveAccessType.USE;
- break;
-
- case TRUNCATETABLE:
- accessType = HiveAccessType.UPDATE;
- break;
-
- case GRANT_PRIVILEGE:
- case REVOKE_PRIVILEGE:
- accessType = HiveAccessType.ADMIN;
- break;
-
- case ADD:
- case DELETE:
- case COMPILE:
- case CREATEMACRO:
- case CREATEROLE:
- case DESCFUNCTION:
- case DFS:
- case DROPMACRO:
- case DROPROLE:
- case EXPLAIN:
- case GRANT_ROLE:
- case MSCK:
- case REVOKE_ROLE:
- case RESET:
- case SET:
- case SHOWCONF:
- case SHOWDATABASES:
- case SHOWFUNCTIONS:
- case SHOWLOCKS:
- case SHOWTABLES:
- case SHOW_COMPACTIONS:
- case SHOW_GRANT:
- case SHOW_ROLES:
- case SHOW_ROLE_GRANT:
- case SHOW_ROLE_PRINCIPALS:
- case SHOW_TRANSACTIONS:
- break;
- }
- break;
- }
-
- return accessType;
- }
-
- private boolean isURIAccessAllowed(UserGroupInformation ugi, HiveAccessType accessType, String uri, HiveConf conf) {
- boolean ret = false;
-
- FsAction action = FsAction.NONE;
-
- switch(accessType) {
- case ALTER:
- case CREATE:
- case UPDATE:
- case DROP:
- case INDEX:
- case LOCK:
- case ADMIN:
- case ALL:
- action = FsAction.WRITE;
- break;
-
- case SELECT:
- case USE:
- action = FsAction.READ;
- break;
-
- case NONE:
- break;
- }
-
- if(action == FsAction.NONE) {
- ret = true;
- } else {
- try {
- Path filePath = new Path(uri);
- FileSystem fs = FileSystem.get(filePath.toUri(), conf);
- Path path = FileUtils.getPathOrParentThatExists(fs, filePath);
- FileStatus fileStatus = fs.getFileStatus(path);
- String userName = ugi.getShortUserName();
-
- if (FileUtils.isOwnerOfFileHierarchy(fs, fileStatus, userName)) {
- ret = true;
- } else {
- ret = FileUtils.isActionPermittedForFileHierarchy(fs, fileStatus, userName, action);
- }
- } catch(Exception excp) {
- LOG.error("Error getting permissions for " + uri, excp);
- }
- }
-
- return ret;
- }
-
- private void handleDfsCommand(HiveOperationType hiveOpType,
- List<HivePrivilegeObject> inputHObjs,
- List<HivePrivilegeObject> outputHObjs,
- XaHiveAccessContext context)
- throws HiveAuthzPluginException, HiveAccessControlException {
-
- String dfsCommandParams = null;
-
- if(inputHObjs != null) {
- for(HivePrivilegeObject hiveObj : inputHObjs) {
- if(hiveObj.getType() == HivePrivilegeObjectType.COMMAND_PARAMS) {
- dfsCommandParams = StringUtil.toString(hiveObj.getCommandParams());
-
- if(! StringUtil.isEmpty(dfsCommandParams)) {
- break;
- }
- }
- }
- }
-
- UserGroupInformation ugi = this.getCurrentUserGroupInfo();
-
- logAuditEventForDfs(ugi, dfsCommandParams, false);
-
- throw new HiveAccessControlException(String.format("Permission denied: user [%s] does not have privilege for [%s] command",
- ugi.getShortUserName(), hiveOpType.name()));
- }
-
- private String getGrantorUsername(HivePrincipal grantorPrincipal) {
- String grantor = grantorPrincipal != null ? grantorPrincipal.getName() : null;
-
- if(StringUtil.isEmpty(grantor)) {
- UserGroupInformation ugi = this.getCurrentUserGroupInfo();
-
- grantor = ugi != null ? ugi.getShortUserName() : null;
- }
-
- return grantor;
- }
-
- private GrantRevokeData createGrantRevokeData(XaHiveObjectAccessInfo objAccessInfo,
- List<HivePrincipal> hivePrincipals,
- List<HivePrivilege> hivePrivileges,
- String grantor,
- boolean grantOption)
- throws HiveAccessControlException {
- if(objAccessInfo == null ||
- ! ( objAccessInfo.getObjectType() == HiveObjectType.DATABASE
- || objAccessInfo.getObjectType() == HiveObjectType.TABLE
- || objAccessInfo.getObjectType() == HiveObjectType.VIEW
- || objAccessInfo.getObjectType() == HiveObjectType.COLUMN
- )
- ) {
- throw new HiveAccessControlException("grantPrivileges(): unexpected object type '" + objAccessInfo.getObjectType().name());
- }
-
- String database = objAccessInfo.getDatabase();
- String table = objAccessInfo.getObjectType() == HiveObjectType.VIEW ? objAccessInfo.getView() : objAccessInfo.getTable();
- String columns = StringUtil.toString(objAccessInfo.getColumns());
-
- GrantRevokeData.PermMap permMap = new GrantRevokeData.PermMap ();
-
- for(HivePrivilege privilege : hivePrivileges) {
- String privName = privilege.getName();
-
- if(StringUtil.equalsIgnoreCase(privName, HiveAccessType.ALL.name())) {
- permMap.addPerm(HiveAccessType.ALL.name());
- } else if(StringUtil.equalsIgnoreCase(privName, HiveAccessType.ALTER.name())) {
- permMap.addPerm(HiveAccessType.ALTER.name());
- } else if(StringUtil.equalsIgnoreCase(privName, HiveAccessType.CREATE.name())) {
- permMap.addPerm(HiveAccessType.CREATE.name());
- } else if(StringUtil.equalsIgnoreCase(privName, HiveAccessType.DROP.name())) {
- permMap.addPerm(HiveAccessType.DROP.name());
- } else if(StringUtil.equalsIgnoreCase(privName, HiveAccessType.INDEX.name())) {
- permMap.addPerm(HiveAccessType.INDEX.name());
- } else if(StringUtil.equalsIgnoreCase(privName, HiveAccessType.LOCK.name())) {
- permMap.addPerm(HiveAccessType.LOCK.name());
- } else if(StringUtil.equalsIgnoreCase(privName, HiveAccessType.SELECT.name())) {
- permMap.addPerm(HiveAccessType.SELECT.name());
- } else if(StringUtil.equalsIgnoreCase(privName, HiveAccessType.UPDATE.name())) {
- permMap.addPerm(HiveAccessType.UPDATE.name());
- }
- }
-
- if(grantOption) {
- permMap.addPerm(HiveAccessType.ADMIN.name());
- }
-
- for(HivePrincipal principal : hivePrincipals) {
- switch(principal.getType()) {
- case USER:
- permMap.addUser(principal.getName());
- break;
-
- case GROUP:
- case ROLE:
- permMap.addGroup(principal.getName());
- break;
-
- default:
- break;
- }
- }
-
- GrantRevokeData grData = new GrantRevokeData();
-
- grData.setHiveData(grantor, repositoryName, database, table, columns, permMap);
-
- return grData;
- }
-
- private void logAuditEventForDfs(UserGroupInformation ugi, String dfsCommand, boolean accessGranted) {
- HiveAuditEvent auditEvent = new HiveAuditEvent();
-
- try {
- auditEvent.setAclEnforcer(XaSecureModuleName);
- auditEvent.setResourceType("@dfs"); // to be consistent with earlier release
- auditEvent.setAccessType("DFS");
- auditEvent.setAction("DFS");
- auditEvent.setUser(ugi.getShortUserName());
- auditEvent.setAccessResult((short)(accessGranted ? 1 : 0));
- auditEvent.setEventTime(StringUtil.getUTCDate());
- auditEvent.setRepositoryType(EnumRepositoryType.HIVE);
- auditEvent.setRepositoryName(repositoryName) ;
- auditEvent.setRequestData(dfsCommand);
-
- auditEvent.setResourcePath(dfsCommand);
-
- if(LOG.isDebugEnabled()) {
- LOG.debug("logAuditEvent [" + auditEvent + "] - START");
- }
-
- AuditProviderFactory.getAuditProvider().log(auditEvent);
-
- if(LOG.isDebugEnabled()) {
- LOG.debug("logAuditEvent [" + auditEvent + "] - END");
- }
- }
- catch(Throwable t) {
- LOG.error("ERROR logEvent [" + auditEvent + "]", t);
- }
- }
-
- private void logAuditEvent(UserGroupInformation ugi, XaHiveObjectAccessInfo objAccessInfo, boolean accessGranted) {
- HiveAuditEvent auditEvent = new HiveAuditEvent();
-
- try {
- auditEvent.setAclEnforcer(XaSecureModuleName);
- auditEvent.setSessionId(objAccessInfo.getContext().getSessionString());
- auditEvent.setResourceType("@" + StringUtil.toLower(objAccessInfo.getObjectType().name())); // to be consistent with earlier release
- auditEvent.setAccessType(objAccessInfo.getAccessType().toString());
- auditEvent.setAction(objAccessInfo.getOperType());
- auditEvent.setUser(ugi.getShortUserName());
- auditEvent.setAccessResult((short)(accessGranted ? 1 : 0));
- auditEvent.setClientIP(objAccessInfo.getContext().getClientIpAddress());
- auditEvent.setClientType(objAccessInfo.getContext().getClientType());
- auditEvent.setEventTime(StringUtil.getUTCDate());
- auditEvent.setRepositoryType(EnumRepositoryType.HIVE);
- auditEvent.setRepositoryName(repositoryName) ;
- auditEvent.setRequestData(objAccessInfo.getContext().getCommandString());
-
- if(! accessGranted && !StringUtil.isEmpty(objAccessInfo.getDeinedObjectName())) {
- auditEvent.setResourcePath(objAccessInfo.getDeinedObjectName());
- } else {
- auditEvent.setResourcePath(objAccessInfo.getObjectName());
- }
-
- if(LOG.isDebugEnabled()) {
- LOG.debug("logAuditEvent [" + auditEvent + "] - START");
- }
-
- AuditProviderFactory.getAuditProvider().log(auditEvent);
-
- if(LOG.isDebugEnabled()) {
- LOG.debug("logAuditEvent [" + auditEvent + "] - END");
- }
- }
- catch(Throwable t) {
- LOG.error("ERROR logEvent [" + auditEvent + "]", t);
- }
- }
-
- private String toString(HiveOperationType hiveOpType,
- List<HivePrivilegeObject> inputHObjs,
- List<HivePrivilegeObject> outputHObjs,
- XaHiveAccessContext context) {
- StringBuilder sb = new StringBuilder();
-
- sb.append("'checkPrivileges':{");
- sb.append("'hiveOpType':").append(hiveOpType);
-
- sb.append(", 'inputHObjs':[");
- toString(inputHObjs, sb);
- sb.append("]");
-
- sb.append(", 'outputHObjs':[");
- toString(outputHObjs, sb);
- sb.append("]");
-
- sb.append(", 'context':{");
- if(context != null) {
- sb.append("'clientType':").append(context.getClientType());
- sb.append(", 'commandString':").append(context.getCommandString());
- sb.append(", 'ipAddress':").append(context.getClientIpAddress());
- sb.append(", 'sessionString':").append(context.getSessionString());
- }
- sb.append("}");
-
- sb.append(", 'user':").append(this.getCurrentUserGroupInfo().getUserName());
- sb.append(", 'groups':[").append(StringUtil.toString(this.getCurrentUserGroupInfo().getGroupNames())).append("]");
-
- sb.append("}");
-
- return sb.toString();
- }
-
- private StringBuilder toString(List<HivePrivilegeObject> privObjs, StringBuilder sb) {
- if(privObjs != null && privObjs.size() > 0) {
- toString(privObjs.get(0), sb);
- for(int i = 1; i < privObjs.size(); i++) {
- sb.append(",");
- toString(privObjs.get(i), sb);
- }
- }
-
- return sb;
- }
-
- private StringBuilder toString(HivePrivilegeObject privObj, StringBuilder sb) {
- sb.append("'HivePrivilegeObject':{");
- sb.append("'type':").append(privObj.getType().toString());
- sb.append(", 'dbName':").append(privObj.getDbname());
- sb.append(", 'objectType':").append(privObj.getType());
- sb.append(", 'objectName':").append(privObj.getObjectName());
- sb.append(", 'columns':[").append(StringUtil.toString(privObj.getColumns())).append("]");
- sb.append(", 'partKeys':[").append(StringUtil.toString(privObj.getPartKeys())).append("]");
- sb.append(", 'commandParams':[").append(StringUtil.toString(privObj.getCommandParams())).append("]");
- sb.append(", 'actionType':").append(privObj.getActionType().toString());
- sb.append("}");
-
- return sb;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hive-agent/src/main/java/com/xasecure/authorization/hive/authorizer/XaSecureHiveAuthorizerBase.java
----------------------------------------------------------------------
diff --git a/hive-agent/src/main/java/com/xasecure/authorization/hive/authorizer/XaSecureHiveAuthorizerBase.java b/hive-agent/src/main/java/com/xasecure/authorization/hive/authorizer/XaSecureHiveAuthorizerBase.java
deleted file mode 100644
index 8a63035..0000000
--- a/hive-agent/src/main/java/com/xasecure/authorization/hive/authorizer/XaSecureHiveAuthorizerBase.java
+++ /dev/null
@@ -1,231 +0,0 @@
-/*
- * 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 com.xasecure.authorization.hive.authorizer;
-
-import java.util.List;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
-import org.apache.hadoop.hive.ql.security.HiveAuthenticationProvider;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.DisallowTransformHook;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAccessControlException;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthorizer;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzContext;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzPluginException;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzSessionContext;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzSessionContext.CLIENT_TYPE;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveMetastoreClientFactory;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HivePrincipal;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HivePrivilegeInfo;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HivePrivilegeObject;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveRoleGrant;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.SettableConfigUpdater;
-import org.apache.hadoop.security.UserGroupInformation;
-
-import com.xasecure.authorization.hive.XaHiveAccessContext;
-import com.xasecure.authorization.utils.StringUtil;
-
-public abstract class XaSecureHiveAuthorizerBase implements HiveAuthorizer {
-
- private static final Log LOG = LogFactory.getLog(XaSecureHiveAuthorizerBase.class);
-
- private HiveMetastoreClientFactory mMetastoreClientFactory;
- private HiveConf mHiveConf;
- private HiveAuthenticationProvider mHiveAuthenticator;
- private HiveAuthzSessionContext mSessionContext;
- private UserGroupInformation mUgi;
-
- public XaSecureHiveAuthorizerBase(HiveMetastoreClientFactory metastoreClientFactory,
- HiveConf hiveConf,
- HiveAuthenticationProvider hiveAuthenticator,
- HiveAuthzSessionContext context) {
- mMetastoreClientFactory = metastoreClientFactory;
- mHiveConf = hiveConf;
- mHiveAuthenticator = hiveAuthenticator;
- mSessionContext = context;
-
- String userName = mHiveAuthenticator == null ? null : mHiveAuthenticator.getUserName();
-
- mUgi = userName == null ? null : UserGroupInformation.createRemoteUser(userName);
-
- if(mHiveAuthenticator == null) {
- LOG.warn("XaSecureHiveAuthorizerBase.XaSecureHiveAuthorizerBase(): hiveAuthenticator is null");
- } else if(StringUtil.isEmpty(userName)) {
- LOG.warn("XaSecureHiveAuthorizerBase.XaSecureHiveAuthorizerBase(): hiveAuthenticator.getUserName() returned null/empty");
- } else if(mUgi == null) {
- LOG.warn(String.format("XaSecureHiveAuthorizerBase.XaSecureHiveAuthorizerBase(): UserGroupInformation.createRemoteUser(%s) returned null", userName));
- }
- }
-
- public HiveMetastoreClientFactory getMetastoreClientFactory() {
- return mMetastoreClientFactory;
- }
-
- public HiveConf getHiveConf() {
- return mHiveConf;
- }
-
- public HiveAuthenticationProvider getHiveAuthenticator() {
- return mHiveAuthenticator;
- }
-
- public HiveAuthzSessionContext getHiveAuthzSessionContext() {
- return mSessionContext;
- }
-
- public UserGroupInformation getCurrentUserGroupInfo() {
- return mUgi;
- }
-
- public XaHiveAccessContext getAccessContext(HiveAuthzContext context) {
- return new XaHiveAccessContext(context, mSessionContext);
- }
-
- @Override
- public void applyAuthorizationConfigPolicy(HiveConf hiveConf) throws HiveAuthzPluginException {
- LOG.debug("XaSecureHiveAuthorizerBase.applyAuthorizationConfigPolicy()");
-
- // from SQLStdHiveAccessController.applyAuthorizationConfigPolicy()
- if (mSessionContext != null && mSessionContext.getClientType() == CLIENT_TYPE.HIVESERVER2) {
- // Configure PREEXECHOOKS with DisallowTransformHook to disallow transform queries
- String hooks = hiveConf.getVar(ConfVars.PREEXECHOOKS).trim();
- if (hooks.isEmpty()) {
- hooks = DisallowTransformHook.class.getName();
- } else {
- hooks = hooks + "," + DisallowTransformHook.class.getName();
- }
-
- hiveConf.setVar(ConfVars.PREEXECHOOKS, hooks);
-
- SettableConfigUpdater.setHiveConfWhiteList(hiveConf);
- }
- }
-
- /**
- * Show privileges for given principal on given object
- * @param principal
- * @param privObj
- * @return
- * @throws HiveAuthzPluginException
- * @throws HiveAccessControlException
- */
- @Override
- public List<HivePrivilegeInfo> showPrivileges(HivePrincipal principal, HivePrivilegeObject privObj)
- throws HiveAuthzPluginException, HiveAccessControlException {
- LOG.debug("XaSecureHiveAuthorizerBase.showPrivileges()");
-
- throwNotImplementedException("showPrivileges");
-
- return null;
- }
-
- @Override
- public void createRole(String roleName, HivePrincipal adminGrantor)
- throws HiveAuthzPluginException, HiveAccessControlException {
- LOG.debug("XaSecureHiveAuthorizerBase.createRole()");
-
- throwNotImplementedException("createRole");
- }
-
- @Override
- public void dropRole(String roleName)
- throws HiveAuthzPluginException, HiveAccessControlException {
- LOG.debug("XaSecureHiveAuthorizerBase.dropRole()");
-
- throwNotImplementedException("dropRole");
- }
-
- @Override
- public List<String> getAllRoles()
- throws HiveAuthzPluginException, HiveAccessControlException {
- LOG.debug("XaSecureHiveAuthorizerBase.getAllRoles()");
-
- throwNotImplementedException("getAllRoles");
-
- return null;
- }
-
- @Override
- public List<String> getCurrentRoleNames() throws HiveAuthzPluginException {
- LOG.debug("XaSecureHiveAuthorizerBase.getCurrentRoleNames()");
-
- throwNotImplementedException("getCurrentRoleNames");
-
- return null;
- }
-
- @Override
- public List<HiveRoleGrant> getPrincipalGrantInfoForRole(String roleName)
- throws HiveAuthzPluginException, HiveAccessControlException {
- LOG.debug("XaSecureHiveAuthorizerBase.getPrincipalGrantInfoForRole()");
-
- throwNotImplementedException("getPrincipalGrantInfoForRole");
-
- return null;
- }
-
- @Override
- public List<HiveRoleGrant> getRoleGrantInfoForPrincipal(HivePrincipal principal)
- throws HiveAuthzPluginException, HiveAccessControlException {
- LOG.debug("XaSecureHiveAuthorizerBase.getRoleGrantInfoForPrincipal()");
-
- throwNotImplementedException("getRoleGrantInfoForPrincipal");
-
- return null;
- }
-
- @Override
- public VERSION getVersion() {
- return VERSION.V1;
- }
-
- @Override
- public void grantRole(List<HivePrincipal> hivePrincipals, List<String> roles,
- boolean grantOption, HivePrincipal grantorPrinc)
- throws HiveAuthzPluginException, HiveAccessControlException {
- LOG.debug("XaSecureHiveAuthorizerBase.grantRole()");
-
- throwNotImplementedException("grantRole");
- }
-
- @Override
- public void revokeRole(List<HivePrincipal> hivePrincipals, List<String> roles,
- boolean grantOption, HivePrincipal grantorPrinc)
- throws HiveAuthzPluginException, HiveAccessControlException {
- LOG.debug("XaSecureHiveAuthorizerBase.revokeRole()");
-
- throwNotImplementedException("revokeRole");
- }
-
- @Override
- public void setCurrentRole(String roleName)
- throws HiveAccessControlException, HiveAuthzPluginException {
- LOG.debug("XaSecureHiveAuthorizerBase.setCurrentRole()");
-
- throwNotImplementedException("setCurrentRole");
- }
-
- private void throwNotImplementedException(String method) throws HiveAuthzPluginException {
- throw new HiveAuthzPluginException(method + "() not implemented in Argus HiveAuthorizer");
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hive-agent/src/main/java/com/xasecure/authorization/hive/authorizer/XaSecureHiveAuthorizerFactory.java
----------------------------------------------------------------------
diff --git a/hive-agent/src/main/java/com/xasecure/authorization/hive/authorizer/XaSecureHiveAuthorizerFactory.java b/hive-agent/src/main/java/com/xasecure/authorization/hive/authorizer/XaSecureHiveAuthorizerFactory.java
deleted file mode 100644
index 50fd55c..0000000
--- a/hive-agent/src/main/java/com/xasecure/authorization/hive/authorizer/XaSecureHiveAuthorizerFactory.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * 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 com.xasecure.authorization.hive.authorizer;
-
-import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.ql.security.HiveAuthenticationProvider;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthorizer;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthorizerFactory;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzPluginException;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveMetastoreClientFactory;
-import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzSessionContext;
-
-public class XaSecureHiveAuthorizerFactory implements HiveAuthorizerFactory {
- @Override
- public HiveAuthorizer createHiveAuthorizer(HiveMetastoreClientFactory metastoreClientFactory,
- HiveConf conf,
- HiveAuthenticationProvider hiveAuthenticator,
- HiveAuthzSessionContext sessionContext)
- throws HiveAuthzPluginException {
- return new XaSecureHiveAuthorizer(metastoreClientFactory, conf, hiveAuthenticator, sessionContext);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hive-agent/src/main/java/com/xasecure/authorization/hive/constants/XaSecureHiveConstants.java
----------------------------------------------------------------------
diff --git a/hive-agent/src/main/java/com/xasecure/authorization/hive/constants/XaSecureHiveConstants.java b/hive-agent/src/main/java/com/xasecure/authorization/hive/constants/XaSecureHiveConstants.java
deleted file mode 100644
index 45fbce0..0000000
--- a/hive-agent/src/main/java/com/xasecure/authorization/hive/constants/XaSecureHiveConstants.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * 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 com.xasecure.authorization.hive.constants;
-
-public final class XaSecureHiveConstants {
- public static final String WILDCARD_OBJECT = "*" ;
- public static final String HAS_ANY_PERMISSION = "any" ;
- public static final String SHOW_META_INFO_PERMISSION = "show" ;
- public static final String PUBLIC_ACCESS_ROLE = "public" ;
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hive-agent/src/main/java/org/apache/ranger/authorization/hive/RangerHiveAccessContext.java
----------------------------------------------------------------------
diff --git a/hive-agent/src/main/java/org/apache/ranger/authorization/hive/RangerHiveAccessContext.java b/hive-agent/src/main/java/org/apache/ranger/authorization/hive/RangerHiveAccessContext.java
new file mode 100644
index 0000000..50b0aa0
--- /dev/null
+++ b/hive-agent/src/main/java/org/apache/ranger/authorization/hive/RangerHiveAccessContext.java
@@ -0,0 +1,75 @@
+/*
+ * 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.authorization.hive;
+
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzContext;
+import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzSessionContext;
+
+
+public class RangerHiveAccessContext {
+ private String mClientIpAddress;
+ private String mClientType;
+ private String mCommandString;
+ private String mSessionString;
+
+ public RangerHiveAccessContext(HiveAuthzContext context, HiveAuthzSessionContext sessionContext) {
+ if(context != null) {
+ mClientIpAddress = context.getIpAddress();
+ mCommandString = context.getCommandString();
+ }
+
+ if(sessionContext != null) {
+ mClientType = sessionContext.getClientType().name();
+ mSessionString = sessionContext.getSessionString();
+ }
+ }
+
+ public String getClientIpAddress() {
+ return mClientIpAddress;
+ }
+
+ public void setClientIpAddress(String clientIpAddress) {
+ this.mClientIpAddress = clientIpAddress;
+ }
+
+ public String getClientType() {
+ return mClientType;
+ }
+
+ public void setClientType(String clientType) {
+ this.mClientType = clientType;
+ }
+
+ public String getCommandString() {
+ return mCommandString;
+ }
+
+ public void setCommandString(String commandString) {
+ this.mCommandString = commandString;
+ }
+
+ public String getSessionString() {
+ return mSessionString;
+ }
+
+ public void setSessionString(String sessionString) {
+ this.mSessionString = sessionString;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hive-agent/src/main/java/org/apache/ranger/authorization/hive/RangerHiveAccessVerifier.java
----------------------------------------------------------------------
diff --git a/hive-agent/src/main/java/org/apache/ranger/authorization/hive/RangerHiveAccessVerifier.java b/hive-agent/src/main/java/org/apache/ranger/authorization/hive/RangerHiveAccessVerifier.java
new file mode 100644
index 0000000..ef4ad56
--- /dev/null
+++ b/hive-agent/src/main/java/org/apache/ranger/authorization/hive/RangerHiveAccessVerifier.java
@@ -0,0 +1,29 @@
+/*
+ * 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.authorization.hive;
+
+import org.apache.hadoop.security.UserGroupInformation;
+
+
+public interface RangerHiveAccessVerifier {
+ public boolean isAccessAllowed(UserGroupInformation ugi, RangerHiveObjectAccessInfo objAccessInfo) ;
+
+ public boolean isAudited(RangerHiveObjectAccessInfo objAccessInfo) ;
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hive-agent/src/main/java/org/apache/ranger/authorization/hive/RangerHiveAccessVerifierFactory.java
----------------------------------------------------------------------
diff --git a/hive-agent/src/main/java/org/apache/ranger/authorization/hive/RangerHiveAccessVerifierFactory.java b/hive-agent/src/main/java/org/apache/ranger/authorization/hive/RangerHiveAccessVerifierFactory.java
new file mode 100644
index 0000000..f02bfe8
--- /dev/null
+++ b/hive-agent/src/main/java/org/apache/ranger/authorization/hive/RangerHiveAccessVerifierFactory.java
@@ -0,0 +1,66 @@
+/*
+ * 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.authorization.hive;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.authorization.hadoop.config.RangerConfiguration;
+import org.apache.ranger.authorization.hadoop.constants.RangerHadoopConstants;
+
+public class RangerHiveAccessVerifierFactory {
+
+ private static final Log LOG = LogFactory.getLog(RangerHiveAccessVerifierFactory.class) ;
+
+ private static RangerHiveAccessVerifier hiveAccessVerififer = null ;
+
+ public static RangerHiveAccessVerifier getInstance() {
+ if (hiveAccessVerififer == null) {
+ synchronized(RangerHiveAccessVerifierFactory.class) {
+ RangerHiveAccessVerifier temp = hiveAccessVerififer ;
+ if (temp == null) {
+ String hiveAccessVerifierClassName = RangerConfiguration.getInstance().get(RangerHadoopConstants.HIVE_ACCESS_VERIFIER_CLASS_NAME_PROP, RangerHadoopConstants.HIVE_ACCESS_VERIFIER_CLASS_NAME_DEFAULT_VALUE ) ;
+
+ if (hiveAccessVerifierClassName != null) {
+ LOG.info("Hive Access Verification class [" + hiveAccessVerifierClassName + "] - Being built");
+ try {
+ hiveAccessVerififer = (RangerHiveAccessVerifier) (Class.forName(hiveAccessVerifierClassName).newInstance()) ;
+ LOG.info("Created a new instance of class: [" + hiveAccessVerifierClassName + "] for Hive Access verification.");
+ } catch (InstantiationException e) {
+ LOG.error("Unable to create HiveAccess Verifier: [" + hiveAccessVerifierClassName + "]", e);
+ } catch (IllegalAccessException e) {
+ LOG.error("Unable to create HiveAccess Verifier: [" + hiveAccessVerifierClassName + "]", e);
+ } catch (ClassNotFoundException e) {
+ LOG.error("Unable to create HiveAccess Verifier: [" + hiveAccessVerifierClassName + "]", e);
+ } catch (Throwable t) {
+ LOG.error("Unable to create HiveAccess Verifier: [" + hiveAccessVerifierClassName + "]", t);
+ }
+ finally {
+ LOG.info("Created a new instance of class: [" + hiveAccessVerifierClassName + "] for Hive Access verification. (" + hiveAccessVerififer + ")");
+ }
+ }
+ }
+ else {
+ LOG.error("Unable to obtain hiveAccessVerifier [" + RangerHadoopConstants.HIVE_ACCESS_VERIFIER_CLASS_NAME_PROP + "]");
+ }
+ }
+ }
+ return hiveAccessVerififer ;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hive-agent/src/main/java/org/apache/ranger/authorization/hive/RangerHiveObjectAccessInfo.java
----------------------------------------------------------------------
diff --git a/hive-agent/src/main/java/org/apache/ranger/authorization/hive/RangerHiveObjectAccessInfo.java b/hive-agent/src/main/java/org/apache/ranger/authorization/hive/RangerHiveObjectAccessInfo.java
new file mode 100644
index 0000000..73b5b57
--- /dev/null
+++ b/hive-agent/src/main/java/org/apache/ranger/authorization/hive/RangerHiveObjectAccessInfo.java
@@ -0,0 +1,240 @@
+/*
+ * 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.authorization.hive;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.ranger.authorization.utils.StringUtil;
+
+public class RangerHiveObjectAccessInfo {
+ public enum HiveObjectType { NONE, DATABASE, TABLE, VIEW, PARTITION, INDEX, COLUMN, FUNCTION, URI };
+ public enum HiveAccessType { NONE, CREATE, ALTER, DROP, INDEX, LOCK, SELECT, UPDATE, USE, ALL, ADMIN };
+
+ private String mOperType = null;
+ private RangerHiveAccessContext mContext = null;
+ private HiveAccessType mAccessType = HiveAccessType.NONE;
+ private HiveObjectType mObjectType = HiveObjectType.NONE;
+ private String mDatabase = null;
+ private String mTable = null;
+ private String mView = null;
+ private String mPartition = null;
+ private String mIndex = null;
+ private List<String> mColumns = null;
+ private String mFunction = null;
+ private String mUri = null;
+ private String mDeniedObjectName = null;
+
+ public RangerHiveObjectAccessInfo(String operType, RangerHiveAccessContext context, HiveAccessType accessType, String dbName) {
+ this(operType, context, accessType, dbName, null, HiveObjectType.DATABASE, dbName);
+ }
+
+ public RangerHiveObjectAccessInfo(String operType, RangerHiveAccessContext context, HiveAccessType accessType, String dbName, String tblName) {
+ this(operType, context, accessType, dbName, tblName, HiveObjectType.TABLE, tblName);
+ }
+
+ public RangerHiveObjectAccessInfo(String operType, RangerHiveAccessContext context, HiveAccessType accessType, String dbName, HiveObjectType objType, String objName) {
+ this(operType, context, accessType, dbName, null, objType, objName);
+ }
+
+ public RangerHiveObjectAccessInfo(String operType, RangerHiveAccessContext context, HiveAccessType accessType, HiveObjectType objType, String objName) {
+ this(operType, context, accessType, null, null, objType, objName);
+ }
+
+ public RangerHiveObjectAccessInfo(String operType, RangerHiveAccessContext context, HiveAccessType accessType, String dbName, String tblOrViewName, List<String> columns) {
+ mOperType = operType;
+ mContext = context;
+ mAccessType = accessType;
+ mObjectType = HiveObjectType.COLUMN;
+ mDatabase = dbName;
+ mTable = tblOrViewName;
+ mView = tblOrViewName;
+ mColumns = columns;
+ }
+
+ public RangerHiveObjectAccessInfo(String operType, RangerHiveAccessContext context, HiveAccessType accessType, String dbName, String tblName, HiveObjectType objType, String objName) {
+ mOperType = operType;
+ mContext = context;
+ mAccessType = accessType;
+ mObjectType = objType;
+ mDatabase = dbName;
+ mTable = tblName;
+ mView = tblName;
+
+ if(objName != null && ! objName.trim().isEmpty()) {
+ switch(objType) {
+ case DATABASE:
+ mDatabase = objName;
+ break;
+
+ case TABLE:
+ mTable = objName;
+ break;
+
+ case VIEW:
+ mView = objName;
+ break;
+
+ case PARTITION:
+ mPartition = objName;
+ break;
+
+ case INDEX:
+ mIndex = objName;
+ break;
+
+ case COLUMN:
+ mColumns = new ArrayList<String>();
+ mColumns.add(objName);
+ break;
+
+ case FUNCTION:
+ mFunction = objName;
+ break;
+
+ case URI:
+ mUri = objName;
+ break;
+
+ case NONE:
+ break;
+ }
+ }
+ }
+
+ public String getOperType() {
+ return mOperType;
+ }
+
+ public RangerHiveAccessContext getContext() {
+ return mContext;
+ }
+
+ public HiveAccessType getAccessType() {
+ return mAccessType;
+ }
+
+ public HiveObjectType getObjectType() {
+ return mObjectType;
+ }
+
+ public String getDatabase() {
+ return mDatabase;
+ }
+
+ public String getTable() {
+ return mTable;
+ }
+
+ public String getView() {
+ return mView;
+ }
+
+ public String getPartition() {
+ return mPartition;
+ }
+
+ public String getIndex() {
+ return mIndex;
+ }
+
+ public List<String> getColumns() {
+ return mColumns;
+ }
+
+ public String getFunction() {
+ return mFunction;
+ }
+
+ public String getUri() {
+ return mUri;
+ }
+
+ public void setDeinedObjectName(String deniedObjectName) {
+ mDeniedObjectName = deniedObjectName;
+ }
+
+ public String getDeinedObjectName() {
+ return mDeniedObjectName;
+ }
+
+ public String getObjectName() {
+ String objName = null;
+
+ if(this.mObjectType == HiveObjectType.URI) {
+ objName = mUri;
+ } else {
+ String tblName = null;
+ String colName = null;
+
+ if(! StringUtil.isEmpty(mTable))
+ tblName = mTable;
+ else if(! StringUtil.isEmpty(mView))
+ tblName = mView;
+ else if(! StringUtil.isEmpty(mFunction))
+ tblName = mFunction;
+
+ if(! StringUtil.isEmpty(mColumns))
+ colName = StringUtil.toString(mColumns);
+ else if(! StringUtil.isEmpty(mIndex))
+ colName = mIndex;
+
+ objName = getObjectName(mDatabase, tblName, colName);
+ }
+
+ return objName;
+ }
+
+ public static String getObjectName(String dbName, String tblName, String colName) {
+ String objName = StringUtil.isEmpty(dbName) ? "" : dbName;
+
+ if(!StringUtil.isEmpty(tblName)) {
+ objName += ("/" + tblName);
+
+ if(!StringUtil.isEmpty(colName)) {
+ objName += ("/" + colName);
+ }
+ }
+
+ return objName;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ boolean ret = false;
+
+ if(obj != null && obj instanceof RangerHiveObjectAccessInfo) {
+ RangerHiveObjectAccessInfo that = (RangerHiveObjectAccessInfo)obj;
+
+ ret = StringUtil.equalsIgnoreCase(mOperType, that.mOperType)
+ && mAccessType == that.mAccessType
+ && mObjectType == that.mObjectType
+ && StringUtil.equalsIgnoreCase(mDatabase, that.mDatabase)
+ && StringUtil.equalsIgnoreCase(mTable, that.mTable)
+ && StringUtil.equalsIgnoreCase(mView, that.mView)
+ && StringUtil.equalsIgnoreCase(mPartition, that.mPartition)
+ && StringUtil.equalsIgnoreCase(mIndex, that.mIndex)
+ && StringUtil.equalsIgnoreCase(mColumns, that.mColumns)
+ ;
+ }
+
+ return ret;
+ }
+}
[50/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/entity/XXHiveAuditEvent_.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/entity/XXHiveAuditEvent_.java b/agents-audit/src/main/java/com/xasecure/audit/entity/XXHiveAuditEvent_.java
deleted file mode 100644
index 328ac96..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/entity/XXHiveAuditEvent_.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * 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 com.xasecure.audit.entity;
-
-import javax.annotation.Generated;
-import javax.persistence.metamodel.SingularAttribute;
-import javax.persistence.metamodel.StaticMetamodel;
-
-@Generated(value="Dali", date="2014-02-02T14:05:13.494-0800")
-@StaticMetamodel(XXHiveAuditEvent.class)
-public class XXHiveAuditEvent_ extends XXBaseAuditEvent_ {
- public static volatile SingularAttribute<XXHiveAuditEvent, String> resourcePath;
- public static volatile SingularAttribute<XXHiveAuditEvent, String> resourceType;
- public static volatile SingularAttribute<XXHiveAuditEvent, String> requestData;
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/entity/XXKnoxAuditEvent.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/entity/XXKnoxAuditEvent.java b/agents-audit/src/main/java/com/xasecure/audit/entity/XXKnoxAuditEvent.java
deleted file mode 100644
index cea07b8..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/entity/XXKnoxAuditEvent.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/**
- * 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 com.xasecure.audit.entity;
-
-import java.io.Serializable;
-
-import javax.persistence.Column;
-import javax.persistence.DiscriminatorValue;
-import javax.persistence.Entity;
-
-import com.xasecure.audit.model.KnoxAuditEvent;
-
-/**
- * Entity implementation class for Entity: XXHiveAuditEvent
- *
- */
-@Entity
-@DiscriminatorValue("4")
-public class XXKnoxAuditEvent extends XXBaseAuditEvent implements Serializable {
- private static final long serialVersionUID = 1L;
-
- private String resourcePath;
- private String resourceType;
- private String requestData;
-
-
- public XXKnoxAuditEvent() {
- super();
- }
-
- public XXKnoxAuditEvent(KnoxAuditEvent event) {
- super(event);
-
- this.resourcePath = event.getResourcePath();
- this.resourceType = event.getResourceType();
- this.requestData = event.getRequestData();
- }
-
- @Column(name = "resource_path")
- public String getResourcePath() {
- return this.resourcePath;
- }
-
- public void setResourcePath(String resourcePath) {
- this.resourcePath = resourcePath;
- }
-
- @Column(name = "resource_type")
- public String getResourceType() {
- return this.resourceType;
- }
-
- public void setResourceType(String resourceType) {
- this.resourceType = resourceType;
- }
-
- @Column(name = "request_data")
- public String getRequestData() {
- return this.requestData;
- }
-
- public void setRequestData(String requestData) {
- this.requestData = requestData;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/entity/XXStormAuditEvent.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/entity/XXStormAuditEvent.java b/agents-audit/src/main/java/com/xasecure/audit/entity/XXStormAuditEvent.java
deleted file mode 100644
index 44fee67..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/entity/XXStormAuditEvent.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/**
- * 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 com.xasecure.audit.entity;
-
-import java.io.Serializable;
-
-import javax.persistence.Column;
-import javax.persistence.DiscriminatorValue;
-import javax.persistence.Entity;
-
-import com.xasecure.audit.model.StormAuditEvent;
-
-/**
- * Entity implementation class for Entity: XXHiveAuditEvent
- *
- */
-@Entity
-@DiscriminatorValue("5")
-public class XXStormAuditEvent extends XXBaseAuditEvent implements Serializable {
- private static final long serialVersionUID = 1L;
-
- private String resourcePath;
- private String resourceType;
- private String requestData;
-
-
- public XXStormAuditEvent() {
- super();
- }
-
- public XXStormAuditEvent(StormAuditEvent event) {
- super(event);
-
- this.resourcePath = event.getResourcePath();
- this.resourceType = event.getResourceType();
- this.requestData = event.getRequestData();
- }
-
- @Column(name = "resource_path")
- public String getResourcePath() {
- return this.resourcePath;
- }
-
- public void setResourcePath(String resourcePath) {
- this.resourcePath = resourcePath;
- }
-
- @Column(name = "resource_type")
- public String getResourceType() {
- return this.resourceType;
- }
-
- public void setResourceType(String resourceType) {
- this.resourceType = resourceType;
- }
-
- @Column(name = "request_data")
- public String getRequestData() {
- return this.requestData;
- }
-
- public void setRequestData(String requestData) {
- this.requestData = requestData;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/model/AuditEventBase.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/model/AuditEventBase.java b/agents-audit/src/main/java/com/xasecure/audit/model/AuditEventBase.java
deleted file mode 100644
index be066de..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/model/AuditEventBase.java
+++ /dev/null
@@ -1,378 +0,0 @@
-/*
- * 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 com.xasecure.audit.model;
-
-import java.util.Date;
-
-import com.google.gson.annotations.SerializedName;
-
-import com.xasecure.audit.dao.DaoManager;
-
-
-public abstract class AuditEventBase {
- protected static String FIELD_SEPARATOR = ";";
-
- protected static final int MAX_ACTION_FIELD_SIZE = 1800 ;
- protected static final int MAX_REQUEST_DATA_FIELD_SIZE = 1800 ;
-
-
- @SerializedName("agent")
- protected String agentId = null;
-
- @SerializedName("reqUser")
- protected String user = null;
-
- @SerializedName("evtTime")
- protected Date eventTime = new Date();
-
- @SerializedName("policy")
- protected long policyId = 0;
-
- @SerializedName("access")
- protected String accessType = null;
-
- @SerializedName("result")
- protected short accessResult = 0; // 0 - DENIED; 1 - ALLOWED; HTTP return code
-
- @SerializedName("reason")
- protected String resultReason = null;
-
- @SerializedName("enforcer")
- protected String aclEnforcer = null;
-
- @SerializedName("repoType")
- protected int repositoryType = 0;
-
- @SerializedName("repo")
- protected String repositoryName = null;
-
- @SerializedName("sess")
- protected String sessionId = null;
-
- @SerializedName("cliType")
- protected String clientType = null;
-
- @SerializedName("cliIP")
- protected String clientIP = null;
-
- @SerializedName("action")
- protected String action = null;
-
- @SerializedName("agentHost")
- protected String agentHostname = null;
-
- @SerializedName("logType")
- protected String logType = null;
-
- @SerializedName("id")
- protected String eventId = null;
-
- protected AuditEventBase() {
- }
-
- protected AuditEventBase(String agentId,
- String user,
- Date eventTime,
- long policyId,
- String accessType,
- short accessResult,
- String resultReason,
- String aclEnforcer,
- int repositoryType,
- String repositoryName,
- String sessionId,
- String clientType,
- String clientIP,
- String action) {
- this.agentId = agentId;
- this.user = user;
- this.eventTime = eventTime;
- this.policyId = policyId;
- this.accessType = accessType;
- this.accessResult = accessResult;
- this.resultReason = resultReason;
- this.aclEnforcer = aclEnforcer;
- this.repositoryType = repositoryType;
- this.repositoryName = repositoryName;
- this.sessionId = sessionId;
- this.clientType = clientType;
- this.clientIP = clientIP;
- this.action = action;
- }
-
- /**
- * @return the agentId
- */
- public String getAgentId() {
- return agentId;
- }
-
- /**
- * @param agentId the agentId to set
- */
- public void setAgentId(String agentId) {
- this.agentId = agentId;
- }
-
- /**
- * @return the user
- */
- public String getUser() {
- return user;
- }
-
- /**
- * @param user the user to set
- */
- public void setUser(String user) {
- this.user = user;
- }
-
- /**
- * @return the timeStamp
- */
- public Date getEventTime() {
- return eventTime;
- }
-
- /**
- * @param timeStamp the timeStamp to set
- */
- public void setEventTime(Date eventTime) {
- this.eventTime = eventTime;
- }
-
- /**
- * @return the policyId
- */
- public long getPolicyId() {
- return policyId;
- }
-
- /**
- * @param policyId the policyId to set
- */
- public void setPolicyId(long policyId) {
- this.policyId = policyId;
- }
-
- /**
- * @return the accessType
- */
- public String getAccessType() {
- return accessType;
- }
-
- /**
- * @param accessType the accessType to set
- */
- public void setAccessType(String accessType) {
- this.accessType = accessType;
- }
-
- /**
- * @return the accessResult
- */
- public short getAccessResult() {
- return accessResult;
- }
-
- /**
- * @param accessResult the accessResult to set
- */
- public void setAccessResult(short accessResult) {
- this.accessResult = accessResult;
- }
-
- /**
- * @return the resultReason
- */
- public String getResultReason() {
- return resultReason;
- }
-
- /**
- * @param resultReason the resultReason to set
- */
- public void setResultReason(String resultReason) {
- this.resultReason = resultReason;
- }
-
- /**
- * @return the aclEnforcer
- */
- public String getAclEnforcer() {
- return aclEnforcer;
- }
-
- /**
- * @param aclEnforcer the aclEnforcer to set
- */
- public void setAclEnforcer(String aclEnforcer) {
- this.aclEnforcer = aclEnforcer;
- }
-
- /**
- * @return the repositoryType
- */
- public int getRepositoryType() {
- return repositoryType;
- }
-
- /**
- * @param repositoryType the repositoryType to set
- */
- public void setRepositoryType(int repositoryType) {
- this.repositoryType = repositoryType;
- }
-
- /**
- * @return the repositoryName
- */
- public String getRepositoryName() {
- return repositoryName;
- }
-
- /**
- * @param repositoryName the repositoryName to set
- */
- public void setRepositoryName(String repositoryName) {
- this.repositoryName = repositoryName;
- }
-
- /**
- * @return the sessionId
- */
- public String getSessionId() {
- return sessionId;
- }
-
- /**
- * @param sessionId the sessionId to set
- */
- public void setSessionId(String sessionId) {
- this.sessionId = sessionId;
- }
-
- /**
- * @return the clientType
- */
- public String getClientType() {
- return clientType;
- }
-
- /**
- * @param clientType the clientType to set
- */
- public void setClientType(String clientType) {
- this.clientType = clientType;
- }
-
- /**
- * @return the clientIP
- */
- public String getClientIP() {
- return clientIP;
- }
-
- /**
- * @param clientIP the clientIP to set
- */
- public void setClientIP(String clientIP) {
- this.clientIP = clientIP;
- }
-
- /**
- * @return the action
- */
- public String getAction() {
- return trim(action,MAX_ACTION_FIELD_SIZE) ;
- }
-
- /**
- * @param action the action to set
- */
- public void setAction(String action) {
- this.action = action;
- }
-
- public String getAgentHostname() {
- return agentHostname;
- }
-
- public void setAgentHostname(String agentHostname) {
- this.agentHostname = agentHostname;
- }
-
- public String getLogType() {
- return logType;
- }
-
- public void setLogType(String logType) {
- this.logType = logType;
- }
-
- public String getEventId() {
- return eventId;
- }
-
- public void setEventId(String eventId) {
- this.eventId = eventId;
- }
-
- public abstract void persist(DaoManager daoManager);
-
- @Override
- public String toString() {
- return toString(new StringBuilder()).toString();
- }
-
- protected StringBuilder toString(StringBuilder sb) {
- sb.append("agentId=").append(agentId).append(FIELD_SEPARATOR)
- .append("user=").append(user).append(FIELD_SEPARATOR)
- .append("eventTime=").append(eventTime).append(FIELD_SEPARATOR)
- .append("policyId=").append(policyId).append(FIELD_SEPARATOR)
- .append("accessType=").append(accessType).append(FIELD_SEPARATOR)
- .append("accessResult=").append(accessResult).append(FIELD_SEPARATOR)
- .append("resultReason=").append(resultReason).append(FIELD_SEPARATOR)
- .append("aclEnforcer=").append(aclEnforcer).append(FIELD_SEPARATOR)
- .append("repositoryType=").append(repositoryType).append(FIELD_SEPARATOR)
- .append("repositoryName=").append(repositoryName).append(FIELD_SEPARATOR)
- .append("sessionId=").append(sessionId).append(FIELD_SEPARATOR)
- .append("clientType=").append(clientType).append(FIELD_SEPARATOR)
- .append("clientIP=").append(clientIP).append(FIELD_SEPARATOR)
- .append("action=").append(action).append(FIELD_SEPARATOR)
- .append("agentHostname=").append(agentHostname).append(FIELD_SEPARATOR)
- .append("logType=").append(logType).append(FIELD_SEPARATOR)
- .append("eventId=").append(eventId).append(FIELD_SEPARATOR)
- ;
- return sb;
- }
-
- protected String trim(String str, int len) {
- String ret = str ;
- if (str != null) {
- if (str.length() > len) {
- ret = str.substring(0,len) ;
- }
- }
- return ret ;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/model/EnumRepositoryType.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/model/EnumRepositoryType.java b/agents-audit/src/main/java/com/xasecure/audit/model/EnumRepositoryType.java
deleted file mode 100644
index 0dddef3..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/model/EnumRepositoryType.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * 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 com.xasecure.audit.model;
-
-public final class EnumRepositoryType {
-
- public static final int HDFS = 1 ;
-
- public static final int HBASE = 2 ;
-
- public static final int HIVE = 3 ;
-
- public static final int XAAGENT = 4 ;
-
- public static final int KNOX = 5;
-
- public static final int STORM = 6 ;
-
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/model/HBaseAuditEvent.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/model/HBaseAuditEvent.java b/agents-audit/src/main/java/com/xasecure/audit/model/HBaseAuditEvent.java
deleted file mode 100644
index 4a35ea4..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/model/HBaseAuditEvent.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * 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 com.xasecure.audit.model;
-
-import java.util.Date;
-
-import com.google.gson.annotations.SerializedName;
-
-import com.xasecure.audit.dao.DaoManager;
-import com.xasecure.audit.entity.XXHBaseAuditEvent;
-
-
-public class HBaseAuditEvent extends AuditEventBase {
- @SerializedName("resource")
- protected String resourcePath;
-
- @SerializedName("resType")
- protected String resourceType;
-
- @SerializedName("reqData")
- protected String requestData;
-
- public HBaseAuditEvent() {
- this.repositoryType = EnumRepositoryType.HBASE;
- }
-
- public HBaseAuditEvent(String agentId,
- String user,
- Date eventTime,
- long policyId,
- String accessType,
- short accessResult,
- String resultReason,
- String aclEnforcer,
- int repositoryType,
- String repositoryName,
- String sessionId,
- String clientType,
- String clientIP,
- String resourcePath,
- String resourceType,
- String requestData,
- String action) {
- super(agentId, user, eventTime, policyId, accessType, accessResult, resultReason, aclEnforcer, repositoryType, repositoryName, sessionId, clientType, clientIP, action);
-
- this.resourcePath = resourcePath;
- this.resourceType = resourceType;
- this.requestData = requestData;
- }
-
- /**
- * @return the resourcePath
- */
- public String getResourcePath() {
- return resourcePath;
- }
-
- /**
- * @param resourcePath the resourcePath to set
- */
- public void setResourcePath(String resourcePath) {
- this.resourcePath = resourcePath;
- }
-
- /**
- * @return the resourceType
- */
- public String getResourceType() {
- return resourceType;
- }
-
- /**
- * @param resourceType the resourceType to set
- */
- public void setResourceType(String resourceType) {
- this.resourceType = resourceType;
- }
-
- /**
- * @return the requestData
- */
- public String getRequestData() {
- return trim(requestData,MAX_REQUEST_DATA_FIELD_SIZE) ;
- }
-
- /**
- * @param requestData the requestData to set
- */
- public void setRequestData(String requestData) {
- this.requestData = requestData;
- }
-
- @Override
- public void persist(DaoManager daoManager) {
- daoManager.getXAHBaseAuditEventDao().create(new XXHBaseAuditEvent(this));
- }
-
- @Override
- protected StringBuilder toString(StringBuilder sb) {
- sb.append("HBaseAuditEvent{");
-
- super.toString(sb)
- .append("resourcePath=").append(resourcePath).append(FIELD_SEPARATOR)
- .append("resourceType=").append(resourceType).append(FIELD_SEPARATOR)
- .append("requestData=").append(requestData).append(FIELD_SEPARATOR);
-
- sb.append("}");
-
- return sb;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/model/HdfsAuditEvent.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/model/HdfsAuditEvent.java b/agents-audit/src/main/java/com/xasecure/audit/model/HdfsAuditEvent.java
deleted file mode 100644
index b9a6870..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/model/HdfsAuditEvent.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * 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 com.xasecure.audit.model;
-
-import java.util.Date;
-
-import com.google.gson.annotations.SerializedName;
-
-import com.xasecure.audit.dao.DaoManager;
-import com.xasecure.audit.entity.XXHdfsAuditEvent;
-
-public class HdfsAuditEvent extends AuditEventBase {
- @SerializedName("resource")
- protected String resourcePath;
-
- @SerializedName("resType")
- protected String resourceType;
-
- public HdfsAuditEvent() {
- this.repositoryType = EnumRepositoryType.HDFS;
- }
-
- public HdfsAuditEvent(String agentId,
- String user,
- Date eventTime,
- long policyId,
- String accessType,
- short accessResult,
- String resultReason,
- String aclEnforcer,
- int repositoryType,
- String repositoryName,
- String sessionId,
- String clientType,
- String clientIP,
- String resourcePath,
- String resourceType,
- String action) {
- super(agentId, user, eventTime, policyId, accessType, accessResult, resultReason, aclEnforcer, repositoryType, repositoryName, sessionId, clientType, clientIP, action);
-
- this.resourcePath = resourcePath;
- this.resourceType = resourceType;
- }
-
- /**
- * @return the resourcePath
- */
- public String getResourcePath() {
- return resourcePath;
- }
-
- /**
- * @param resourcePath the resourcePath to set
- */
- public void setResourcePath(String resourcePath) {
- this.resourcePath = resourcePath;
- }
-
- /**
- * @return the resourceType
- */
- public String getResourceType() {
- return resourceType;
- }
-
- /**
- * @param resourceType the resourceType to set
- */
- public void setResourceType(String resourceType) {
- this.resourceType = resourceType;
- }
-
- @Override
- public void persist(DaoManager daoManager) {
- daoManager.getXAHdfsAuditEventDao().create(new XXHdfsAuditEvent(this));
- }
-
- @Override
- protected StringBuilder toString(StringBuilder sb) {
- sb.append("HdfsAuditEvent{");
-
- super.toString(sb)
- .append("resourcePath=").append(resourcePath).append(FIELD_SEPARATOR)
- .append("resourceType=").append(resourceType).append(FIELD_SEPARATOR);
-
- sb.append("}");
-
- return sb;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/model/HiveAuditEvent.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/model/HiveAuditEvent.java b/agents-audit/src/main/java/com/xasecure/audit/model/HiveAuditEvent.java
deleted file mode 100644
index 5765bed..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/model/HiveAuditEvent.java
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * 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 com.xasecure.audit.model;
-
-import java.util.Date;
-
-import com.google.gson.annotations.SerializedName;
-import com.xasecure.audit.dao.DaoManager;
-import com.xasecure.audit.entity.XXHiveAuditEvent;
-
-public class HiveAuditEvent extends AuditEventBase {
- @SerializedName("resource")
- protected String resourcePath;
-
- @SerializedName("resType")
- protected String resourceType;
-
- @SerializedName("reqData")
- protected String requestData;
-
- public HiveAuditEvent() {
- this.repositoryType = EnumRepositoryType.HIVE;
- }
-
- public HiveAuditEvent(String agentId,
- String user,
- Date eventTime,
- long policyId,
- String accessType,
- short accessResult,
- String resultReason,
- String aclEnforcer,
- int repositoryType,
- String repositoryName,
- String sessionId,
- String clientType,
- String clientIP,
- String resourcePath,
- String resourceType,
- String requestData,
- String action) {
- super(agentId, user, eventTime, policyId, accessType, accessResult, resultReason, aclEnforcer, repositoryType, repositoryName, sessionId, clientType, clientIP, action);
-
- this.resourcePath = resourcePath;
- this.resourceType = resourceType;
- this.requestData = requestData;
- }
-
- /**
- * @return the resourcePath
- */
- public String getResourcePath() {
- return resourcePath;
- }
-
- /**
- * @param resourcePath the resourcePath to set
- */
- public void setResourcePath(String resourcePath) {
- this.resourcePath = resourcePath;
- }
-
- /**
- * @return the resourceType
- */
- public String getResourceType() {
- return resourceType;
- }
-
- /**
- * @param resourceType the resourceType to set
- */
- public void setResourceType(String resourceType) {
- this.resourceType = resourceType;
- }
-
- /**
- * @return the requestData
- */
- public String getRequestData() {
- return trim(requestData,MAX_REQUEST_DATA_FIELD_SIZE);
- }
-
- /**
- * @param requestData the requestData to set
- */
- public void setRequestData(String requestData) {
- this.requestData = requestData;
- }
-
- @Override
- public void persist(DaoManager daoManager) {
- daoManager.getXAHiveAuditEventDao().create(new XXHiveAuditEvent(this));
- }
-
- @Override
- protected StringBuilder toString(StringBuilder sb) {
- sb.append("HiveAuditEvent{");
-
- super.toString(sb)
- .append("resourcePath=").append(resourcePath).append(FIELD_SEPARATOR)
- .append("resourceType=").append(resourceType).append(FIELD_SEPARATOR)
- .append("requestData=").append(requestData).append(FIELD_SEPARATOR);
-
- sb.append("}");
-
- return sb;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/model/KnoxAuditEvent.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/model/KnoxAuditEvent.java b/agents-audit/src/main/java/com/xasecure/audit/model/KnoxAuditEvent.java
deleted file mode 100644
index dd18057..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/model/KnoxAuditEvent.java
+++ /dev/null
@@ -1,97 +0,0 @@
-package com.xasecure.audit.model;
-
-import com.google.gson.annotations.SerializedName;
-import com.xasecure.audit.dao.DaoManager;
-import com.xasecure.audit.entity.XXKnoxAuditEvent;
-
-/**
- * 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.
- */
-
-public class KnoxAuditEvent extends AuditEventBase {
- @SerializedName("resource")
- protected String resourcePath;
-
- @SerializedName("resType")
- protected String resourceType;
-
- @SerializedName("reqData")
- protected String requestData;
-
- public KnoxAuditEvent() {
- this.repositoryType = EnumRepositoryType.KNOX;
- }
-
- /**
- * @return the resourcePath
- */
- public String getResourcePath() {
- return resourcePath;
- }
-
- /**
- * @param resourcePath the resourcePath to set
- */
- public void setResourcePath(String resourcePath) {
- this.resourcePath = resourcePath;
- }
-
- /**
- * @return the resourceType
- */
- public String getResourceType() {
- return resourceType;
- }
-
- /**
- * @param resourceType the resourceType to set
- */
- public void setResourceType(String resourceType) {
- this.resourceType = resourceType;
- }
-
- /**
- * @return the requestData
- */
- public String getRequestData() {
- return trim(requestData, MAX_REQUEST_DATA_FIELD_SIZE);
- }
-
- /**
- * @param requestData
- * the requestData to set
- */
- public void setRequestData(String requestData) {
- this.requestData = requestData;
- }
-
- @Override
- public void persist(DaoManager daoManager) {
- daoManager.getXAKnoxAuditEventDao().create(new XXKnoxAuditEvent(this));
- }
-
- @Override
- protected StringBuilder toString(StringBuilder sb) {
- sb.append("KnoxAuditEvent{");
-
- super.toString(sb).append("requestData=")
- .append(requestData).append(FIELD_SEPARATOR);
-
- sb.append("}");
-
- return sb;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/model/StormAuditEvent.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/model/StormAuditEvent.java b/agents-audit/src/main/java/com/xasecure/audit/model/StormAuditEvent.java
deleted file mode 100644
index f911068..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/model/StormAuditEvent.java
+++ /dev/null
@@ -1,97 +0,0 @@
-package com.xasecure.audit.model;
-
-import com.google.gson.annotations.SerializedName;
-import com.xasecure.audit.dao.DaoManager;
-import com.xasecure.audit.entity.XXStormAuditEvent;
-
-/**
- * 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.
- */
-
-public class StormAuditEvent extends AuditEventBase {
- @SerializedName("resource")
- protected String resourcePath;
-
- @SerializedName("resType")
- protected String resourceType;
-
- @SerializedName("reqData")
- protected String requestData;
-
- public StormAuditEvent() {
- this.repositoryType = EnumRepositoryType.STORM;
- }
-
- /**
- * @return the resourcePath
- */
- public String getResourcePath() {
- return resourcePath;
- }
-
- /**
- * @param resourcePath the resourcePath to set
- */
- public void setResourcePath(String resourcePath) {
- this.resourcePath = resourcePath;
- }
-
- /**
- * @return the resourceType
- */
- public String getResourceType() {
- return resourceType;
- }
-
- /**
- * @param resourceType the resourceType to set
- */
- public void setResourceType(String resourceType) {
- this.resourceType = resourceType;
- }
-
- /**
- * @return the requestData
- */
- public String getRequestData() {
- return trim(requestData, MAX_REQUEST_DATA_FIELD_SIZE);
- }
-
- /**
- * @param requestData
- * the requestData to set
- */
- public void setRequestData(String requestData) {
- this.requestData = requestData;
- }
-
- @Override
- public void persist(DaoManager daoManager) {
- daoManager.getXAStormAuditEventDao().create(new XXStormAuditEvent(this));
- }
-
- @Override
- protected StringBuilder toString(StringBuilder sb) {
- sb.append("StormAuditEvent{");
-
- super.toString(sb).append("requestData=")
- .append(requestData).append(FIELD_SEPARATOR);
-
- sb.append("}");
-
- return sb;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/provider/AsyncAuditProvider.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/provider/AsyncAuditProvider.java b/agents-audit/src/main/java/com/xasecure/audit/provider/AsyncAuditProvider.java
deleted file mode 100644
index 4070f47..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/provider/AsyncAuditProvider.java
+++ /dev/null
@@ -1,272 +0,0 @@
-/*
- * 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 com.xasecure.audit.provider;
-
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.ArrayBlockingQueue;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.Properties;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import com.xasecure.audit.model.AuditEventBase;
-
-public class AsyncAuditProvider extends MultiDestAuditProvider implements
- Runnable {
-
- private static final Log LOG = LogFactory.getLog(AsyncAuditProvider.class);
-
- private static int sThreadCount = 0;
-
- private BlockingQueue<AuditEventBase> mQueue = null;
- private Thread mThread = null;
- private boolean mStopThread = false;
- private String mName = null;
- private int mMaxQueueSize = 10 * 1024;
- private int mMaxFlushInterval = 5000; // 5 seconds
-
- // Summary of logs handled
- private AtomicLong lifeTimeInLogCount = new AtomicLong(0); // Total count, including drop count
- private AtomicLong lifeTimeOutLogCount = new AtomicLong(0);
- private AtomicLong lifeTimeDropCount = new AtomicLong(0);
- private AtomicLong intervalInLogCount = new AtomicLong(0);
- private AtomicLong intervalOutLogCount = new AtomicLong(0);
- private AtomicLong intervalDropCount = new AtomicLong(0);
- private long lastIntervalLogTime = System.currentTimeMillis();
- private int intervalLogDurationMS = 60000;
-
- public AsyncAuditProvider(String name, int maxQueueSize, int maxFlushInterval) {
- LOG.info("AsyncAuditProvider(" + name + "): creating..");
-
- if(maxQueueSize < 1) {
- LOG.warn("AsyncAuditProvider(" + name + "): invalid maxQueueSize=" + maxQueueSize + ". will use default " + mMaxQueueSize);
-
- maxQueueSize = mMaxQueueSize;
- }
-
- mName = name;
- mMaxQueueSize = maxQueueSize;
- mMaxFlushInterval = maxFlushInterval;
-
- mQueue = new ArrayBlockingQueue<AuditEventBase>(mMaxQueueSize);
- }
-
- public AsyncAuditProvider(String name, int maxQueueSize, int maxFlushInterval, AuditProvider provider) {
- this(name, maxQueueSize, maxFlushInterval);
-
- addAuditProvider(provider);
- }
-
- @Override
- public void init(Properties props) {
- LOG.info("AsyncAuditProvider(" + mName + ").init()");
-
- super.init(props);
- }
-
- public int getIntervalLogDurationMS() {
- return intervalLogDurationMS;
- }
-
- public void setIntervalLogDurationMS(int intervalLogDurationMS) {
- this.intervalLogDurationMS = intervalLogDurationMS;
- }
-
- @Override
- public void log(AuditEventBase event) {
- LOG.debug("AsyncAuditProvider.logEvent(AuditEventBase)");
-
- queueEvent(event);
- }
-
- @Override
- public void start() {
- mThread = new Thread(this, "AsyncAuditProvider" + (++sThreadCount));
-
- mThread.setDaemon(true);
- mThread.start();
-
- super.start();
- }
-
- @Override
- public void stop() {
- mStopThread = true;
-
- try {
- mThread.join();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- super.stop();
- }
-
- @Override
- public void waitToComplete() {
- waitToComplete(0);
-
- super.waitToComplete();
- }
-
- @Override
- public void run() {
- LOG.info("==> AsyncAuditProvider.run()");
-
- while (!mStopThread) {
- AuditEventBase event = null;
- try {
- event = dequeueEvent();
-
- if (event != null) {
- super.log(event);
- } else {
- flush();
- }
- } catch (Exception excp) {
- logFailedEvent(event, excp);
- }
- }
-
- try {
- flush();
- } catch (Exception excp) {
- LOG.error("AsyncAuditProvider.run()", excp);
- }
-
- LOG.info("<== AsyncAuditProvider.run()");
- }
-
- private void queueEvent(AuditEventBase event) {
- // Increase counts
- lifeTimeInLogCount.incrementAndGet();
- intervalInLogCount.incrementAndGet();
-
- if(! mQueue.offer(event)) {
- lifeTimeDropCount.incrementAndGet();
- intervalDropCount.incrementAndGet();
- }
- }
-
- private AuditEventBase dequeueEvent() {
- AuditEventBase ret = mQueue.poll();
-
- try {
- while(ret == null && !mStopThread) {
- logSummaryIfRequired();
-
- if (mMaxFlushInterval > 0 && isFlushPending()) {
- long timeTillNextFlush = getTimeTillNextFlush();
-
- if (timeTillNextFlush <= 0) {
- break; // force flush
- }
-
- ret = mQueue.poll(timeTillNextFlush, TimeUnit.MILLISECONDS);
- } else {
- // Let's wake up for summary logging
- long waitTime = intervalLogDurationMS - (System.currentTimeMillis() - lastIntervalLogTime);
- waitTime = waitTime <= 0 ? intervalLogDurationMS : waitTime;
-
- ret = mQueue.poll(waitTime, TimeUnit.MILLISECONDS);
- }
- }
- } catch(InterruptedException excp) {
- LOG.error("AsyncAuditProvider.dequeueEvent()", excp);
- }
-
- if(ret != null) {
- lifeTimeOutLogCount.incrementAndGet();
- intervalOutLogCount.incrementAndGet();
- }
-
- logSummaryIfRequired();
-
- return ret;
- }
-
- private void logSummaryIfRequired() {
- long intervalSinceLastLog = System.currentTimeMillis() - lastIntervalLogTime;
-
- if (intervalSinceLastLog > intervalLogDurationMS) {
- if (intervalInLogCount.get() > 0 || intervalOutLogCount.get() > 0 ) {
- long queueSize = mQueue.size();
-
- LOG.info("AsyncAuditProvider-stats:" + mName + ": past " + formatIntervalForLog(intervalSinceLastLog)
- + ": inLogs=" + intervalInLogCount.get()
- + ", outLogs=" + intervalOutLogCount.get()
- + ", dropped=" + intervalDropCount.get()
- + ", currentQueueSize=" + queueSize);
-
- LOG.info("AsyncAuditProvider-stats:" + mName + ": process lifetime"
- + ": inLogs=" + lifeTimeInLogCount.get()
- + ", outLogs=" + lifeTimeOutLogCount.get()
- + ", dropped=" + lifeTimeDropCount.get());
- }
-
- lastIntervalLogTime = System.currentTimeMillis();
- intervalInLogCount.set(0);
- intervalOutLogCount.set(0);
- intervalDropCount.set(0);
- }
- }
-
- private boolean isEmpty() {
- return mQueue.isEmpty();
- }
-
- private void waitToComplete(long maxWaitSeconds) {
- LOG.debug("==> AsyncAuditProvider.waitToComplete()");
-
- for (long waitTime = 0; !isEmpty()
- && (maxWaitSeconds <= 0 || maxWaitSeconds > waitTime); waitTime++) {
- try {
- Thread.sleep(1000);
- } catch (Exception excp) {
- // ignore
- }
- }
-
- LOG.debug("<== AsyncAuditProvider.waitToComplete()");
- }
-
- private long getTimeTillNextFlush() {
- long timeTillNextFlush = mMaxFlushInterval;
-
- if (mMaxFlushInterval > 0) {
- long lastFlushTime = getLastFlushTime();
-
- if (lastFlushTime != 0) {
- long timeSinceLastFlush = System.currentTimeMillis()
- - lastFlushTime;
-
- if (timeSinceLastFlush >= mMaxFlushInterval)
- timeTillNextFlush = 0;
- else
- timeTillNextFlush = mMaxFlushInterval - timeSinceLastFlush;
- }
- }
-
- return timeTillNextFlush;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/provider/AuditProvider.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/provider/AuditProvider.java b/agents-audit/src/main/java/com/xasecure/audit/provider/AuditProvider.java
deleted file mode 100644
index e026cec..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/provider/AuditProvider.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * 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 com.xasecure.audit.provider;
-
-import java.util.Properties;
-
-import com.xasecure.audit.model.AuditEventBase;
-
-public interface AuditProvider {
- public void log(AuditEventBase event);
-
- public void init(Properties prop);
- public void start();
- public void stop();
- public void waitToComplete();
-
- public boolean isFlushPending();
- public long getLastFlushTime();
- public void flush();
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/provider/AuditProviderFactory.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/provider/AuditProviderFactory.java b/agents-audit/src/main/java/com/xasecure/audit/provider/AuditProviderFactory.java
deleted file mode 100644
index 4913b4b..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/provider/AuditProviderFactory.java
+++ /dev/null
@@ -1,243 +0,0 @@
-/**
- * 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 com.xasecure.audit.provider;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import com.xasecure.audit.provider.hdfs.HdfsAuditProvider;
-
-
-/*
- * TODO:
- * 1) Flag to enable/disable audit logging
- * 2) Failed path to be recorded
- * 3) Repo name, repo type from configuration
- */
-
-public class AuditProviderFactory {
-
- public enum ApplicationType { Unknown, Hdfs, HiveCLI, HiveServer2, HBaseMaster, HBaseRegionalServer, Knox, Storm };
-
- private static final Log LOG = LogFactory.getLog(AuditProviderFactory.class);
-
- private static final String AUDIT_IS_ENABLED_PROP = "xasecure.audit.is.enabled" ;
- private static final String AUDIT_DB_IS_ENABLED_PROP = "xasecure.audit.db.is.enabled" ;
- private static final String AUDIT_HDFS_IS_ENABLED_PROP = "xasecure.audit.hdfs.is.enabled";
- private static final String AUDIT_LOG4J_IS_ENABLED_PROP = "xasecure.audit.log4j.is.enabled" ;
-
- private static final int AUDIT_ASYNC_MAX_QUEUE_SIZE_DEFAULT = 10 * 1024;
- private static final int AUDIT_ASYNC_MAX_FLUSH_INTERVAL_DEFAULT = 5 * 1000;
-
- private static AuditProviderFactory sFactory;
-
- private AuditProvider mProvider = null;
- private boolean mInitDone = false;
-
- private AuditProviderFactory() {
- LOG.info("AuditProviderFactory: creating..");
-
- mProvider = getDefaultProvider();
- }
-
- public static AuditProviderFactory getInstance() {
- if(sFactory == null) {
- synchronized(AuditProviderFactory.class) {
- if(sFactory == null) {
- sFactory = new AuditProviderFactory();
- }
- }
- }
-
- return sFactory;
- }
-
- public static AuditProvider getAuditProvider() {
- return AuditProviderFactory.getInstance().getProvider();
- }
-
- public AuditProvider getProvider() {
- return mProvider;
- }
-
- public boolean isInitDone() {
- return mInitDone;
- }
-
- public synchronized void init(Properties props, ApplicationType appType) {
- LOG.info("AuditProviderFactory: initializing..");
-
- if(mInitDone) {
- LOG.warn("AuditProviderFactory.init(): already initialized!", new Exception());
-
- return;
- }
- mInitDone = true;
-
- setApplicationType(appType);
-
- boolean isEnabled = BaseAuditProvider.getBooleanProperty(props, AUDIT_IS_ENABLED_PROP, false);
- boolean isAuditToDbEnabled = BaseAuditProvider.getBooleanProperty(props, AUDIT_DB_IS_ENABLED_PROP, false);
- boolean isAuditToHdfsEnabled = BaseAuditProvider.getBooleanProperty(props, AUDIT_HDFS_IS_ENABLED_PROP, false);
- boolean isAuditToLog4jEnabled = BaseAuditProvider.getBooleanProperty(props, AUDIT_LOG4J_IS_ENABLED_PROP, false);
-
- if(!isEnabled || !(isAuditToDbEnabled || isAuditToHdfsEnabled || isAuditToLog4jEnabled)) {
- LOG.info("AuditProviderFactory: Audit not enabled..");
-
- mProvider = getDefaultProvider();
-
- return;
- }
-
- List<AuditProvider> providers = new ArrayList<AuditProvider>();
-
- if(isAuditToDbEnabled) {
- DbAuditProvider dbProvider = new DbAuditProvider();
-
- boolean isAuditToDbAsync = BaseAuditProvider.getBooleanProperty(props, DbAuditProvider.AUDIT_DB_IS_ASYNC_PROP, false);
-
- if(isAuditToDbAsync) {
- int maxQueueSize = BaseAuditProvider.getIntProperty(props, DbAuditProvider.AUDIT_DB_MAX_QUEUE_SIZE_PROP, AUDIT_ASYNC_MAX_QUEUE_SIZE_DEFAULT);
- int maxFlushInterval = BaseAuditProvider.getIntProperty(props, DbAuditProvider.AUDIT_DB_MAX_FLUSH_INTERVAL_PROP, AUDIT_ASYNC_MAX_FLUSH_INTERVAL_DEFAULT);
-
- AsyncAuditProvider asyncProvider = new AsyncAuditProvider("DbAuditProvider", maxQueueSize, maxFlushInterval, dbProvider);
-
- providers.add(asyncProvider);
- } else {
- providers.add(dbProvider);
- }
- }
-
- if(isAuditToHdfsEnabled) {
- HdfsAuditProvider hdfsProvider = new HdfsAuditProvider();
-
- boolean isAuditToHdfsAsync = BaseAuditProvider.getBooleanProperty(props, HdfsAuditProvider.AUDIT_HDFS_IS_ASYNC_PROP, false);
-
- if(isAuditToHdfsAsync) {
- int maxQueueSize = BaseAuditProvider.getIntProperty(props, HdfsAuditProvider.AUDIT_HDFS_MAX_QUEUE_SIZE_PROP, AUDIT_ASYNC_MAX_QUEUE_SIZE_DEFAULT);
- int maxFlushInterval = BaseAuditProvider.getIntProperty(props, HdfsAuditProvider.AUDIT_HDFS_MAX_FLUSH_INTERVAL_PROP, AUDIT_ASYNC_MAX_FLUSH_INTERVAL_DEFAULT);
-
- AsyncAuditProvider asyncProvider = new AsyncAuditProvider("HdfsAuditProvider", maxQueueSize, maxFlushInterval, hdfsProvider);
-
- providers.add(asyncProvider);
- } else {
- providers.add(hdfsProvider);
- }
- }
-
- if(isAuditToLog4jEnabled) {
- Log4jAuditProvider log4jProvider = new Log4jAuditProvider();
-
- boolean isAuditToLog4jAsync = BaseAuditProvider.getBooleanProperty(props, Log4jAuditProvider.AUDIT_LOG4J_IS_ASYNC_PROP, false);
-
- if(isAuditToLog4jAsync) {
- int maxQueueSize = BaseAuditProvider.getIntProperty(props, Log4jAuditProvider.AUDIT_LOG4J_MAX_QUEUE_SIZE_PROP, AUDIT_ASYNC_MAX_QUEUE_SIZE_DEFAULT);
- int maxFlushInterval = BaseAuditProvider.getIntProperty(props, Log4jAuditProvider.AUDIT_LOG4J_MAX_FLUSH_INTERVAL_PROP, AUDIT_ASYNC_MAX_FLUSH_INTERVAL_DEFAULT);
-
- AsyncAuditProvider asyncProvider = new AsyncAuditProvider("Log4jAuditProvider", maxQueueSize, maxFlushInterval, log4jProvider);
-
- providers.add(asyncProvider);
- } else {
- providers.add(log4jProvider);
- }
- }
-
- if(providers.size() == 0) {
- mProvider = getDefaultProvider();
- } else if(providers.size() == 1) {
- mProvider = providers.get(0);
- } else {
- MultiDestAuditProvider multiDestProvider = new MultiDestAuditProvider();
-
- multiDestProvider.addAuditProviders(providers);
-
- mProvider = multiDestProvider;
- }
-
- mProvider.init(props);
- mProvider.start();
-
- JVMShutdownHook jvmShutdownHook = new JVMShutdownHook(mProvider);
-
- Runtime.getRuntime().addShutdownHook(jvmShutdownHook);
- }
-
- private static void setApplicationType(ApplicationType appType) {
- String strAppType = null;
-
- switch(appType) {
- case Hdfs:
- strAppType = "hdfs";
- break;
-
- case HiveCLI:
- strAppType = "hiveCli";
- break;
-
- case HiveServer2:
- strAppType = "hiveServer2";
- break;
-
- case HBaseMaster:
- strAppType = "hbaseMaster";
- break;
-
- case HBaseRegionalServer:
- strAppType = "hbaseRegional";
- break;
-
- case Knox:
- strAppType = "knox";
- break;
-
- case Storm:
- strAppType = "storm";
- break;
-
- case Unknown:
- strAppType = "unknown";
- break;
- }
-
- MiscUtil.setApplicationType(strAppType);
- }
-
- private AuditProvider getDefaultProvider() {
- return new DummyAuditProvider();
- }
-
- private static class JVMShutdownHook extends Thread {
- AuditProvider mProvider;
-
- public JVMShutdownHook(AuditProvider provider) {
- mProvider = provider;
- }
-
- public void run() {
- mProvider.waitToComplete();
- mProvider.stop();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/provider/BaseAuditProvider.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/provider/BaseAuditProvider.java b/agents-audit/src/main/java/com/xasecure/audit/provider/BaseAuditProvider.java
deleted file mode 100644
index ccf8a4a..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/provider/BaseAuditProvider.java
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * 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 com.xasecure.audit.provider;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-
-import com.xasecure.audit.model.AuditEventBase;
-
-public abstract class BaseAuditProvider implements AuditProvider {
- private static final Log LOG = LogFactory.getLog(BaseAuditProvider.class);
-
- private static final String AUDIT_LOG_FAILURE_REPORT_MIN_INTERVAL_PROP = "xasecure.audit.log.failure.report.min.interval.ms";
-
- private int mLogFailureReportMinIntervalInMs = 60 * 1000;
-
- private AtomicLong mFailedLogLastReportTime = new AtomicLong(0);
- private AtomicLong mFailedLogCountSinceLastReport = new AtomicLong(0);
- private AtomicLong mFailedLogCountLifeTime = new AtomicLong(0);
-
-
- public BaseAuditProvider() {
- }
-
- @Override
- public void init(Properties props) {
- LOG.info("BaseAuditProvider.init()");
-
- mLogFailureReportMinIntervalInMs = getIntProperty(props, AUDIT_LOG_FAILURE_REPORT_MIN_INTERVAL_PROP, 60 * 1000);
- }
-
- public void logFailedEvent(AuditEventBase event) {
- logFailedEvent(event, null);
- }
-
- public void logFailedEvent(AuditEventBase event, Throwable excp) {
- long now = System.currentTimeMillis();
-
- long timeSinceLastReport = now - mFailedLogLastReportTime.get();
- long countSinceLastReport = mFailedLogCountSinceLastReport.incrementAndGet();
- long countLifeTime = mFailedLogCountLifeTime.incrementAndGet();
-
- if(timeSinceLastReport >= mLogFailureReportMinIntervalInMs) {
- mFailedLogLastReportTime.set(now);
- mFailedLogCountSinceLastReport.set(0);
-
- if(excp != null) {
- LOG.warn("failed to log audit event: " + MiscUtil.stringify(event), excp);
- } else {
- LOG.warn("failed to log audit event: " + MiscUtil.stringify(event));
- }
-
- if(countLifeTime > 1) { // no stats to print for the 1st failure
- LOG.warn("Log failure count: " + countSinceLastReport + " in past " + formatIntervalForLog(timeSinceLastReport) + "; " + countLifeTime + " during process lifetime");
- }
- }
- }
-
- public static Map<String, String> getPropertiesWithPrefix(Properties props, String prefix) {
- Map<String, String> prefixedProperties = new HashMap<String, String>();
-
- if(props != null && prefix != null) {
- for(String key : props.stringPropertyNames()) {
- if(key == null) {
- continue;
- }
-
- String val = props.getProperty(key);
-
- if(key.startsWith(prefix)) {
- key = key.substring(prefix.length());
-
- if(key == null) {
- continue;
- }
-
- prefixedProperties.put(key, val);
- }
- }
- }
-
- return prefixedProperties;
- }
-
- public static boolean getBooleanProperty(Properties props, String propName, boolean defValue) {
- boolean ret = defValue;
-
- if(props != null && propName != null) {
- String val = props.getProperty(propName);
-
- if(val != null) {
- ret = Boolean.valueOf(val);
- }
- }
-
- return ret;
- }
-
- public static int getIntProperty(Properties props, String propName, int defValue) {
- int ret = defValue;
-
- if(props != null && propName != null) {
- String val = props.getProperty(propName);
-
- if(val != null) {
- try {
- ret = Integer.parseInt(val);
- } catch(NumberFormatException excp) {
- ret = defValue;
- }
- }
- }
-
- return ret;
- }
-
-
- public static String getStringProperty(Properties props, String propName) {
- String ret = null;
-
- if(props != null && propName != null) {
- String val = props.getProperty(propName);
- if ( val != null){
- ret = val;
- }
- }
-
- return ret;
- }
-
- public String getTimeDiffStr(long time1, long time2) {
- long timeInMs = Math.abs(time1 - time2);
- return formatIntervalForLog(timeInMs);
- }
-
- public String formatIntervalForLog(long timeInMs) {
- long hours = timeInMs / (60 * 60 * 1000);
- long minutes = (timeInMs / (60 * 1000)) % 60;
- long seconds = (timeInMs % (60 * 1000)) / 1000;
- long mSeconds = (timeInMs % (1000));
-
- if (hours > 0)
- return String.format("%02d:%02d:%02d.%03d hours", hours, minutes,
- seconds, mSeconds);
- else if (minutes > 0)
- return String.format("%02d:%02d.%03d minutes", minutes, seconds,
- mSeconds);
- else if (seconds > 0)
- return String.format("%02d.%03d seconds", seconds, mSeconds);
- else
- return String.format("%03d milli-seconds", mSeconds);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/provider/BufferedAuditProvider.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/provider/BufferedAuditProvider.java b/agents-audit/src/main/java/com/xasecure/audit/provider/BufferedAuditProvider.java
deleted file mode 100644
index 94b853c..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/provider/BufferedAuditProvider.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/**
- * 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 com.xasecure.audit.provider;
-
-import java.util.Properties;
-
-import com.xasecure.audit.model.AuditEventBase;
-
-public abstract class BufferedAuditProvider extends BaseAuditProvider {
- private LogBuffer<AuditEventBase> mBuffer = null;
- private LogDestination<AuditEventBase> mDestination = null;
-
- @Override
- public void init(Properties props) {
- super.init(props);
- }
-
- @Override
- public void log(AuditEventBase event) {
- if(event.getAgentHostname() == null) {
- event.setAgentHostname(MiscUtil.getHostname());
- }
-
- if(event.getLogType() == null) {
- event.setLogType("RangerAudit");
- }
-
- if(event.getEventId() == null) {
- event.setEventId(MiscUtil.generateUniqueId());
- }
-
- if(! mBuffer.add(event)) {
- logFailedEvent(event);
- }
- }
-
- @Override
- public void start() {
- mBuffer.start(mDestination);
- }
-
- @Override
- public void stop() {
- mBuffer.stop();
- }
-
- @Override
- public void waitToComplete() {
- }
-
- @Override
- public boolean isFlushPending() {
- return false;
- }
-
- @Override
- public long getLastFlushTime() {
- return 0;
- }
-
- @Override
- public void flush() {
- }
-
- protected LogBuffer<AuditEventBase> getBuffer() {
- return mBuffer;
- }
-
- protected LogDestination<AuditEventBase> getDestination() {
- return mDestination;
- }
-
- protected void setBufferAndDestination(LogBuffer<AuditEventBase> buffer,
- LogDestination<AuditEventBase> destination) {
- mBuffer = buffer;
- mDestination = destination;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/provider/DbAuditProvider.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/provider/DbAuditProvider.java b/agents-audit/src/main/java/com/xasecure/audit/provider/DbAuditProvider.java
deleted file mode 100644
index 8657961..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/provider/DbAuditProvider.java
+++ /dev/null
@@ -1,356 +0,0 @@
-/**
- * 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 com.xasecure.audit.provider;
-
-import java.util.ArrayList;
-import java.util.Map;
-import java.util.Properties;
-
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.EntityTransaction;
-import javax.persistence.Persistence;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import com.xasecure.audit.dao.DaoManager;
-import com.xasecure.audit.model.AuditEventBase;
-import com.xasecure.authorization.hadoop.utils.XaSecureCredentialProvider;
-
-
-/*
- * NOTE:
- * - Instances of this class are not thread-safe.
- */
-public class DbAuditProvider extends BaseAuditProvider {
-
- private static final Log LOG = LogFactory.getLog(DbAuditProvider.class);
-
- public static final String AUDIT_DB_IS_ASYNC_PROP = "xasecure.audit.db.is.async";
- public static final String AUDIT_DB_MAX_QUEUE_SIZE_PROP = "xasecure.audit.db.async.max.queue.size" ;
- public static final String AUDIT_DB_MAX_FLUSH_INTERVAL_PROP = "xasecure.audit.db.async.max.flush.interval.ms";
-
- private static final String AUDIT_DB_BATCH_SIZE_PROP = "xasecure.audit.db.batch.size" ;
- private static final String AUDIT_DB_RETRY_MIN_INTERVAL_PROP = "xasecure.audit.db.config.retry.min.interval.ms";
- private static final String AUDIT_JPA_CONFIG_PROP_PREFIX = "xasecure.audit.jpa.";
- private static final String AUDIT_DB_CREDENTIAL_PROVIDER_FILE = "xasecure.audit.credential.provider.file";
- private static final String AUDIT_DB_CREDENTIAL_PROVIDER_ALIAS = "auditDBCred";
- private static final String AUDIT_JPA_JDBC_PASSWORD = "javax.persistence.jdbc.password";
-
- private EntityManagerFactory entityManagerFactory;
- private DaoManager daoManager;
-
- private int mCommitBatchSize = 1;
- private int mDbRetryMinIntervalMs = 60 * 1000;
- private long mLastCommitTime = System.currentTimeMillis();
- private ArrayList<AuditEventBase> mUncommitted = new ArrayList<AuditEventBase>();
- private Map<String, String> mDbProperties = null;
- private long mLastDbFailedTime = 0;
-
- public DbAuditProvider() {
- LOG.info("DbAuditProvider: creating..");
- }
-
- @Override
- public void init(Properties props) {
- LOG.info("DbAuditProvider.init()");
-
- super.init(props);
-
- mDbProperties = BaseAuditProvider.getPropertiesWithPrefix(props, AUDIT_JPA_CONFIG_PROP_PREFIX);
- mCommitBatchSize = BaseAuditProvider.getIntProperty(props, AUDIT_DB_BATCH_SIZE_PROP, 1000);
- mDbRetryMinIntervalMs = BaseAuditProvider.getIntProperty(props, AUDIT_DB_RETRY_MIN_INTERVAL_PROP, 15 * 1000);
-
- boolean isAsync = BaseAuditProvider.getBooleanProperty(props, AUDIT_DB_IS_ASYNC_PROP, false);
-
- if(! isAsync) {
- mCommitBatchSize = 1; // Batching not supported in sync mode
- }
-
- String jdbcPassword = getCredentialString(BaseAuditProvider.getStringProperty(props, AUDIT_DB_CREDENTIAL_PROVIDER_FILE), AUDIT_DB_CREDENTIAL_PROVIDER_ALIAS);
-
- if(jdbcPassword != null && !jdbcPassword.isEmpty()) {
- mDbProperties.put(AUDIT_JPA_JDBC_PASSWORD, jdbcPassword);
- }
- }
-
- @Override
- public void log(AuditEventBase event) {
- LOG.debug("DbAuditProvider.log()");
-
- boolean isSuccess = false;
-
- try {
- if(preCreate(event)) {
- DaoManager daoMgr = daoManager;
-
- if(daoMgr != null) {
- event.persist(daoMgr);
-
- isSuccess = postCreate(event);
- }
- }
- } catch(Exception excp) {
- logDbError("DbAuditProvider.log(): failed", excp);
- } finally {
- if(! isSuccess) {
- logFailedEvent(event);
- }
- }
- }
-
- @Override
- public void start() {
- LOG.info("DbAuditProvider.start()");
-
- init();
- }
-
- @Override
- public void stop() {
- LOG.info("DbAuditProvider.stop()");
-
- cleanUp();
- }
-
- @Override
- public void waitToComplete() {
- LOG.info("DbAuditProvider.waitToComplete()");
- }
-
- @Override
- public boolean isFlushPending() {
- return mUncommitted.size() > 0;
- }
-
- @Override
- public long getLastFlushTime() {
- return mLastCommitTime;
- }
-
- @Override
- public void flush() {
- if(mUncommitted.size() > 0) {
- boolean isSuccess = commitTransaction();
-
- if(! isSuccess) {
- for(AuditEventBase evt : mUncommitted) {
- logFailedEvent(evt);
- }
- }
-
- mUncommitted.clear();
- }
- }
-
- private synchronized boolean init() {
- long now = System.currentTimeMillis();
-
- if((now - mLastDbFailedTime) < mDbRetryMinIntervalMs) {
- return false;
- }
-
- LOG.info("DbAuditProvider: init()");
-
- try {
- entityManagerFactory = Persistence.createEntityManagerFactory("xa_server", mDbProperties);
-
- daoManager = new DaoManager();
- daoManager.setEntityManagerFactory(entityManagerFactory);
-
- daoManager.getEntityManager(); // this forces the connection to be made to DB
- } catch(Exception excp) {
- logDbError("DbAuditProvider: DB initalization failed", excp);
-
- cleanUp();
-
- return false;
- }
-
- return true;
- }
-
- private synchronized void cleanUp() {
- LOG.info("DbAuditProvider: cleanUp()");
-
- try {
- if(entityManagerFactory != null && entityManagerFactory.isOpen()) {
- entityManagerFactory.close();
- }
- } catch(Exception excp) {
- LOG.error("DbAuditProvider.cleanUp(): failed", excp);
- } finally {
- entityManagerFactory = null;
- daoManager = null;
- }
- }
-
- private boolean isDbConnected() {
- EntityManager em = getEntityManager();
-
- return em != null && em.isOpen();
- }
-
- private EntityManager getEntityManager() {
- DaoManager daoMgr = daoManager;
-
- if(daoMgr != null) {
- try {
- return daoMgr.getEntityManager();
- } catch(Exception excp) {
- logDbError("DbAuditProvider.getEntityManager(): failed", excp);
-
- cleanUp();
- }
- }
-
- return null;
- }
-
- private void clearEntityManager() {
- try {
- EntityManager em = getEntityManager();
-
- if(em != null) {
- em.clear();
- }
- } catch(Exception excp) {
- LOG.warn("DbAuditProvider.clearEntityManager(): failed", excp);
- }
- }
-
- private EntityTransaction getTransaction() {
- EntityManager em = getEntityManager();
-
- return em != null ? em.getTransaction() : null;
- }
-
- private boolean isInTransaction() {
- EntityTransaction trx = getTransaction();
-
- return trx != null && trx.isActive();
- }
-
- private boolean beginTransaction() {
- EntityTransaction trx = getTransaction();
-
- if(trx != null && !trx.isActive()) {
- trx.begin();
- }
-
- if(trx == null) {
- LOG.warn("DbAuditProvider.beginTransaction(): trx is null");
- }
-
- return trx != null;
- }
-
- private boolean commitTransaction() {
- boolean ret = false;
- EntityTransaction trx = null;
-
- try {
- trx = getTransaction();
-
- if(trx != null && trx.isActive()) {
- trx.commit();
-
- ret =true;
- } else {
- throw new Exception("trx is null or not active");
- }
- } catch(Exception excp) {
- logDbError("DbAuditProvider.commitTransaction(): failed", excp);
-
- cleanUp(); // so that next insert will try to init()
- } finally {
- mLastCommitTime = System.currentTimeMillis();
-
- clearEntityManager();
- }
-
- return ret;
- }
-
- private boolean preCreate(AuditEventBase event) {
- boolean ret = true;
-
- if(!isDbConnected()) {
- ret = init();
- }
-
- if(ret) {
- if(! isInTransaction()) {
- ret = beginTransaction();
- }
- }
-
- return ret;
- }
-
- private boolean postCreate(AuditEventBase event) {
- boolean ret = true;
-
- if(mCommitBatchSize <= 1) {
- ret = commitTransaction();
- } else {
- mUncommitted.add(event);
-
- if((mUncommitted.size() % mCommitBatchSize) == 0) {
- ret = commitTransaction();
-
- if(! ret) {
- for(AuditEventBase evt : mUncommitted) {
- if(evt != event) {
- logFailedEvent(evt);
- }
- }
- }
-
- mUncommitted.clear();
- }
- }
- return ret;
- }
-
- private void logDbError(String msg, Exception excp) {
- long now = System.currentTimeMillis();
-
- if((now - mLastDbFailedTime) > mDbRetryMinIntervalMs) {
- mLastDbFailedTime = now;
- }
-
- LOG.warn(msg, excp);
- }
-
- private String getCredentialString(String url,String alias) {
- String ret = null;
-
- if(url != null && alias != null) {
- char[] cred = XaSecureCredentialProvider.getInstance().getCredentialString(url,alias);
-
- if ( cred != null ) {
- ret = new String(cred);
- }
- }
-
- return ret;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/provider/DebugTracer.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/provider/DebugTracer.java b/agents-audit/src/main/java/com/xasecure/audit/provider/DebugTracer.java
deleted file mode 100644
index 6453708..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/provider/DebugTracer.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * 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 com.xasecure.audit.provider;
-
-public interface DebugTracer {
- void debug(String msg);
- void debug(String msg, Throwable excp);
- void info(String msg);
- void info(String msg, Throwable excp);
- void warn(String msg);
- void warn(String msg, Throwable excp);
- void error(String msg);
- void error(String msg, Throwable excp);
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/com/xasecure/audit/provider/DummyAuditProvider.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/com/xasecure/audit/provider/DummyAuditProvider.java b/agents-audit/src/main/java/com/xasecure/audit/provider/DummyAuditProvider.java
deleted file mode 100644
index 73f4b27..0000000
--- a/agents-audit/src/main/java/com/xasecure/audit/provider/DummyAuditProvider.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/**
- * 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 com.xasecure.audit.provider;
-
-import java.util.Properties;
-
-import com.xasecure.audit.model.AuditEventBase;
-
-
-public class DummyAuditProvider implements AuditProvider {
- @Override
- public void init(Properties prop) {
- // intentionally left empty
- }
-
- @Override
- public void log(AuditEventBase event) {
- // intentionally left empty
- }
-
- @Override
- public void start() {
- // intentionally left empty
- }
-
- @Override
- public void stop() {
- // intentionally left empty
- }
-
- @Override
- public void waitToComplete() {
- // intentionally left empty
- }
-
- @Override
- public boolean isFlushPending() {
- return false;
- }
-
- @Override
- public long getLastFlushTime() {
- return 0;
- }
-
- @Override
- public void flush() {
- // intentionally left empty
- }
-}
[05/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
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;
+ }
+
+}
[38/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/test/java/com/xasecure/pdp/knox/URLBasedAuthDBTest.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/test/java/com/xasecure/pdp/knox/URLBasedAuthDBTest.java b/agents-impl/src/test/java/com/xasecure/pdp/knox/URLBasedAuthDBTest.java
deleted file mode 100644
index e835347..0000000
--- a/agents-impl/src/test/java/com/xasecure/pdp/knox/URLBasedAuthDBTest.java
+++ /dev/null
@@ -1,956 +0,0 @@
-/**
- * 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 com.xasecure.pdp.knox;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-import com.xasecure.pdp.model.Policy;
-import com.xasecure.pdp.model.PolicyContainer;
-import com.xasecure.pdp.model.RolePermission;
-
-public class URLBasedAuthDBTest {
-
- @Test
- public void testPolicyEnabled() {
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- null, // ipAddress
- true, // policyEnabled
- true); // auditEnabled
- pdp.setPolicyContainer(policyContainer);
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "WEBHDFS",
- "allow",
- "guest",
- asSet("sales"),
- "127.127.127.127");
- System.out.println("testPolicyEnabled allowed: " + allowed);
- Assert.assertTrue("Access denied while policy is enabled", allowed);
- }
-
- @Test
- public void testPolicyNotEnabled() {
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- null, // ipAddress
- false, // policyEnabled
- true); // auditEnabled
- pdp.setPolicyContainer(policyContainer);
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "WEBHDFS",
- "allow",
- "guest",
- asSet("sales"),
- "127.127.127.127");
- System.out.println("testPolicyNotEnabled allowed: " + allowed);
- Assert.assertFalse("Access allowed while policy is disabled", allowed);
- }
-
- @Test
- public void testPolicyEnabledAuditOnTmSm() {
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- null, // ipAddress
- true, // policyEnabled
- true); // auditEnabled
- pdp.setPolicyContainer(policyContainer);
-
- boolean auditEnabled = pdp.isAuditEnabled(
- "xa",
- "WEBHDFS"
- );
- System.out.println("testPolicyEnabledAuditOnTmSm: " + auditEnabled);
- Assert.assertTrue("Audit not ebabled while policy is matched", auditEnabled);
- }
-
- @Test
- public void testPolicyEnabledAuditOnTnmSm() {
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- null, // ipAddress
- true, // policyEnabled
- true); // auditEnabled
- pdp.setPolicyContainer(policyContainer);
-
- boolean auditEnabled = pdp.isAuditEnabled(
- "yxa",
- "WEBHDFS"
- );
- System.out.println("testPolicyEnabledAuditOnTnmSm auditEnabled: " + auditEnabled);
- Assert.assertFalse("Audit ebabled with a non matching topology", auditEnabled);
- }
-
- @Test
- public void testPolicyEnabledAuditOnTmSnm() {
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- null, // ipAddress
- true, // policyEnabled
- true); // auditEnabled
- pdp.setPolicyContainer(policyContainer);
-
- boolean auditEnabled = pdp.isAuditEnabled(
- "xa",
- "yWEBHDFS"
- );
- System.out.println("testPolicyEnabledAuditOnTmSnm auditEnabled: " + auditEnabled);
- Assert.assertFalse("Audit ebabled with a non matching service", auditEnabled);
- }
-
- @Test
- public void testPolicyEnabledAuditOff() {
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- null, // ipAddress
- true, // policyEnabled
- false); // auditEnabled
- pdp.setPolicyContainer(policyContainer);
-
- boolean auditEnabled = pdp.isAuditEnabled(
- "xa",
- "WEBHDFS"
- );
- System.out.println("testPolicyEnabledAuditOff auditEnabled: " + auditEnabled);
- Assert.assertFalse("Audit ebabled with policy disabling audit", auditEnabled);
- }
-
- @Test
- public void testPolicyNotEnabledAuditOn() {
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- null, // ipAddress
- false, // policyEnabled
- true); // auditEnabled
- pdp.setPolicyContainer(policyContainer);
-
- boolean auditEnabled = pdp.isAuditEnabled(
- "xa",
- "WEBHDFS"
- );
- System.out.println("testPolicyNotEnabledAuditOn auditEnabled: " + auditEnabled);
- Assert.assertFalse("Audit ebabled with policy not enabled", auditEnabled);
- }
-
- @Test
- public void testPolicyNotEnabledAuditOff() {
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- null, // ipAddress
- false, // policyEnabled
- true); // auditEnabled
- pdp.setPolicyContainer(policyContainer);
-
- boolean auditEnabled = pdp.isAuditEnabled(
- "xa",
- "WEBHDFS"
- );
- System.out.println("testPolicyNotEnabledAuditOff auditEnabled: " + auditEnabled);
- Assert.assertFalse("Audit ebabled with policy not enabled and audit off", auditEnabled);
- }
-
- @Test
- public void testSimpleTopologyAccessAllowed() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- null);
- pdp.setPolicyContainer(policyContainer);
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "WEBHDFS",
- "allow",
- "guest",
- asSet("sales"),
- "127.127.127.127");
- System.out.println("testSimpleTopologyAccessAllowed allowed: " + allowed);
- Assert.assertTrue("Access denied for a simple allow policy", allowed);
-
- }
-
- @Test
- public void testSimpleTopologyAccessDenied() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- null);
- pdp.setPolicyContainer(policyContainer);
-
- boolean allowed = pdp.isAccessGranted(
- "ya",
- "WEBHDFS",
- "allow",
- "guest",
- asSet("sales"),
- "127.127.127.127");
- System.out.println("testSimpleTopologyAccessDenied allowed: " + allowed);
- Assert.assertFalse("Access allwed for a simple deny policy", allowed);
-
- }
-
- @Test
- public void testWildTopologyAccessAllowed() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "x*",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- null);
- pdp.setPolicyContainer(policyContainer);
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "WEBHDFS",
- "allow",
- "guest",
- asSet("sales"),
- "127.127.127.127");
- System.out.println("testWildTopologyAccessAllowed allowed: " + allowed);
- Assert.assertTrue("Access denied for a matching wild topology policy", allowed);
-
- }
-
- @Test
- public void testWildTopologyAccessDenied() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "x*",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- null);
- pdp.setPolicyContainer(policyContainer);
-
- boolean allowed = pdp.isAccessGranted(
- "ya",
- "WEBHDFS",
- "allow",
- "guest",
- asSet("sales"),
- "127.127.127.127");
- System.out.println("testWildTopologyAccessDenied allowed: " + allowed);
- Assert.assertFalse("Access allowed for non matching wild topology policy", allowed);
-
- }
-
- @Test
- public void testSimpleServiceAccessAllowed() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- null);
- pdp.setPolicyContainer(policyContainer);
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "WEBHDFS",
- "allow",
- "guest",
- asSet("sales"),
- "127.127.127.127");
- System.out.println("testSimpleServiceAccessAllowed allowed: " + allowed);
- Assert.assertTrue("Access denied for a policy matching service", allowed);
-
- }
-
- @Test
- public void testSimpleServiceAccessDenied() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- null);
- pdp.setPolicyContainer(policyContainer);
-
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "yWEBHDFS",
- "allow",
- "guest",
- asSet("sales"),
- "127.127.127.127");
- System.out.println("testSimpleServiceAccessDenied allowed: " + allowed);
- Assert.assertFalse("Access allowed for a policy with no matching service", allowed);
-
- }
-
- @Test
- public void testWildServiceAccessAllowed() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEB*",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- null);
- pdp.setPolicyContainer(policyContainer);
-
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "WEBHDFS",
- "allow",
- "guest",
- asSet("sales"),
- "127.127.127.127");
- System.out.println("testWildServiceAccessAllowed allowed: " + allowed);
- Assert.assertTrue("Access denied for policy with matching wild service", allowed);
-
- }
-
- @Test
- public void testWildServiceAccessDenied() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEB*",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- null);
- pdp.setPolicyContainer(policyContainer);
-
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "yWEBHDFS",
- "allow",
- "guest",
- asSet("sales"),
- "127.127.127.127");
- System.out.println("testWildServiceAccessDenied allowed: " + allowed);
- Assert.assertFalse("Access allowed for a policy with a non matching wild service", allowed);
-
- }
-
- @Test
- public void testAccessTypeAccessAllowed() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- null);
- pdp.setPolicyContainer(policyContainer);
-
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "WEBHDFS",
- "allow",
- "guest",
- asSet("sales"),
- "127.127.127.127");
- System.out.println("testAccessTypeAccessAllowed allowed: " + allowed);
- Assert.assertTrue("Access denied for a policy with matching accessTyoe", allowed);
-
- }
-
- @Test
- public void testAccessTypeAccessDenied() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- null);
- pdp.setPolicyContainer(policyContainer);
-
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "WEBHDFS",
- "yallow",
- "guest",
- asSet("sales"),
- "127.127.127.127");
- System.out.println("testAccessTypeAccessDenied allowed: " + allowed);
- Assert.assertFalse("Access allowed for a non matching accessType", allowed);
-
- }
-
- @Test
- public void testUserAccessAllowed() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- null);
- pdp.setPolicyContainer(policyContainer);
-
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "WEBHDFS",
- "allow",
- "guest",
- asSet("sales"),
- "127.127.127.127");
- System.out.println("testUserAccessAllowed allowed: " + allowed);
- Assert.assertTrue("Access denied for matching user", allowed);
-
- }
-
- @Test
- public void testUserAccessDenied() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("yguest"),
- asList("sales"),
- null);
- pdp.setPolicyContainer(policyContainer);
-
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "WEBHDFS",
- "yallow",
- "guest",
- asSet("sales"),
- "127.127.127.127");
- System.out.println("testUserAccessDenied allowed: " + allowed);
- Assert.assertFalse("Access allowed for a non matching user", allowed);
-
- }
-
- @Test
- public void testGroupAccessAllowed() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- null,
- asList("sales"),
- null);
- pdp.setPolicyContainer(policyContainer);
-
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "WEBHDFS",
- "allow",
- "sam",
- asSet("sales"),
- "127.127.127.127");
- System.out.println("testGroupAccessAllowe allowed: " + allowed);
- Assert.assertTrue("Access denied for a matching user group", allowed);
-
- }
-
- @Test
- public void testGroupAccessDenied() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- null,
- asList("sales"),
- null);
- pdp.setPolicyContainer(policyContainer);
-
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "WEBHDFS",
- "yallow",
- "guest",
- asSet("sales"),
- "127.127.127.127");
- System.out.println("testGroupAccessDenied allowed: " + allowed);
- Assert.assertFalse("Access allowed for a non matching user group", allowed);
-
- }
-
-
-
- @Test
- public void testSimpleIP4Allowed() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- asList("132.133.134.135"));
- pdp.setPolicyContainer(policyContainer);
-
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "WEBHDFS",
- "allow",
- "guest",
- asSet("sales"),
- "132.133.134.135");
- System.out.println("testSimpleIP4Allowed allowed: " + allowed);
- Assert.assertTrue("Access denied for a matching IP4 request ip", allowed);
-
- }
-
- @Test
- public void testSimpleIP4Denied() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- asList("132.133.134.135"));
- pdp.setPolicyContainer(policyContainer);
-
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "WEBHDFS",
- "allow",
- "guest",
- asSet("sales"),
- "132.133.134.136");
- System.out.println("testSimpleIP4Denied allowed: " + allowed);
- Assert.assertFalse("Access allowed for a non matching IP4 request ip", allowed);
-
- }
-
- @Test
- public void testWildIP4Allowed() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- asList("132.133.134.*"));
- pdp.setPolicyContainer(policyContainer);
-
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "WEBHDFS",
- "allow",
- "guest",
- asSet("sales"),
- "132.133.134.135");
- System.out.println("testWildIP4Allowed allowed: " + allowed);
- Assert.assertTrue("Access denied for a request ip matching wild IP4", allowed);
-
- }
-
- @Test
- public void testWildIP4Denied() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- asList("132.133.134.*"));
- pdp.setPolicyContainer(policyContainer);
-
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "WEBHDFS",
- "allow",
- "guest",
- asSet("sales"),
- "132.133.234.136");
- System.out.println("testWildIP4Denied allowed: " + allowed);
- Assert.assertFalse("Access allowed for a request ip not matching wild IP4", allowed);
-
- }
-
- @Test
- public void testWilderIP4Allowed() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- asList("132.133.*.*"));
- pdp.setPolicyContainer(policyContainer);
-
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "WEBHDFS",
- "allow",
- "guest",
- asSet("sales"),
- "132.133.234.235");
- System.out.println("testWilderIP4Allowed: " + allowed);
- Assert.assertTrue("Access denied for a request ip matching wilder IP4", allowed);
-
- }
-
- @Test
- public void testWilderIP4Denied() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- asList("132.133.*.*"));
- pdp.setPolicyContainer(policyContainer);
-
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "WEBHDFS",
- "allow",
- "guest",
- asSet("sales"),
- "132.233.234.136");
- System.out.println("testWilderIP4Denied allowed: " + allowed);
- Assert.assertFalse("Access allowed for a request ip not matching wilder IP4", allowed);
-
- }
-
- @Test
- public void testWildIP6Allowed() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- asList("132:133:134:*"));
- pdp.setPolicyContainer(policyContainer);
-
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "WEBHDFS",
- "allow",
- "guest",
- asSet("sales"),
- "132:133:134:135");
- System.out.println("testWildIP6Allowed allowed: " + allowed);
- Assert.assertTrue("Access denied for a request ip matching wild IP6", allowed);
-
- }
-
- @Test
- public void testWildIP6AllowedMixedCase() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- asList("132:133:Db8:*"));
- pdp.setPolicyContainer(policyContainer);
-
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "WEBHDFS",
- "allow",
- "guest",
- asSet("sales"),
- "132:133:dB8:135");
- System.out.println("testWildIP6AllowedMixedCase: " + allowed);
- Assert.assertTrue("Access denied for a request ip matching wild IP6 with mixed case", allowed);
-
- }
-
- @Test
- public void testWildIP6Denied() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- asList("132:133:134:*"));
- pdp.setPolicyContainer(policyContainer);
-
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "WEBHDFS",
- "allow",
- "guest",
- asSet("sales"),
- "132:133:234:136");
- System.out.println("testWildIP6Denied allowed: " + allowed);
- Assert.assertFalse("Access allowed for a request ip not matching wild IP6", allowed);
-
- }
-
- @Test
- public void testWilderIP6Allowed() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- asList("132:133:*:*"));
- pdp.setPolicyContainer(policyContainer);
-
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "WEBHDFS",
- "allow",
- "guest",
- asSet("sales"),
- "132:133:234:235");
- System.out.println("testWilderIP6Allowed allowed: " + allowed);
- Assert.assertTrue("Access denied for a request ip matching wilder IP6", allowed);
-
- }
-
- @Test
- public void testWilderIP6Denied() {
-
- URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
-
- PolicyContainer policyContainer = buildPolicyContainer(
- "xa",
- "WEBHDFS",
- asList("allow"),
- asList("guest"),
- asList("sales"),
- asList("132:133:*:*"));
- pdp.setPolicyContainer(policyContainer);
-
-
- boolean allowed = pdp.isAccessGranted(
- "xa",
- "WEBHDFS",
- "allow",
- "guest",
- asSet("sales"),
- "132:233:234:136");
- System.out.println("testWilderIP6Denied allowed: " + allowed);
- Assert.assertFalse("Access allowed for a request ip not matching wilder IP6", allowed);
-
- }
-
- private static PolicyContainer buildPolicyContainer(String topologies,
- String services, List<String> accessTypes, List<String> users,
- List<String> groups, List<String> ipAddresses) {
- return buildPolicyContainer( topologies, services, accessTypes,
- users, groups, ipAddresses, true, true);
-
- }
-
- private static PolicyContainer buildPolicyContainer(String topologies,
- String services, List<String> accessTypes, List<String> users,
- List<String> groups, List<String> ipAddresses,
- boolean policyEnabled, boolean auditEnabled) {
-
- PolicyContainer policyContainer = new PolicyContainer();
- policyContainer.setRepositoryName("knoxdev");
-
- List<Policy> policies = new ArrayList<Policy>();
-
- Policy policy = new Policy();
- policy.setTopologies(topologies);
- policy.setServices(services);
- policy.setPolicyStatus(policyEnabled ? "Enabled" : "NotEnabled");
- policy.setAuditInd(auditEnabled ? 1 : 0);
-
- List<RolePermission> rolePermissions = new ArrayList<RolePermission>();
-
- RolePermission rolePermission = new RolePermission();
-
- rolePermissions.add(rolePermission);
- rolePermission.setAccess(accessTypes);
- rolePermission.setUsers(users);
- rolePermission.setGroups(groups);
- rolePermission.setIpAddress(ipAddresses);
-
- policy.setPermissions(rolePermissions);
-
- policies.add(policy);
-
- policyContainer.setAcl(policies);
-
- return policyContainer;
- }
-
- private static Set<String> asSet(String... a) {
- Set<String> vals = new HashSet<String>();
- for (String s : a) {
- vals.add(s);
- }
- return vals;
- }
-
- private static List<String> asList(String... a) {
- List<String> vals = new ArrayList<String>();
- for (String s : a) {
- vals.add(s);
- }
- return vals;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/test/java/org/apache/ranger/pdp/hdfs/PolicyCacheStoreTest.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/test/java/org/apache/ranger/pdp/hdfs/PolicyCacheStoreTest.java b/agents-impl/src/test/java/org/apache/ranger/pdp/hdfs/PolicyCacheStoreTest.java
new file mode 100644
index 0000000..ad1f472
--- /dev/null
+++ b/agents-impl/src/test/java/org/apache/ranger/pdp/hdfs/PolicyCacheStoreTest.java
@@ -0,0 +1,170 @@
+/*
+ * 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.pdp.hdfs;
+
+import java.io.BufferedReader;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.pdp.config.ConfigWatcher;
+import org.apache.ranger.pdp.config.PolicyRefresher;
+import org.apache.ranger.pdp.hdfs.URLBasedAuthDB;
+import org.apache.ranger.pdp.model.Policy;
+import org.apache.ranger.pdp.model.PolicyContainer;
+import org.apache.ranger.pdp.model.RolePermission;
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Test;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+
+public class PolicyCacheStoreTest {
+ URLBasedAuthDB authDB = null;
+ ConfigWatcher watcherDaemon = null;
+ PolicyRefresher pr = null;
+ PolicyContainer policyContainer=null;
+ String url=null;
+ String sslConfigFileName=null;
+ String lastStoredFileName=null;
+ Long refreshInterval =0L;
+ private static final Log LOG = LogFactory.getLog(PolicyCacheStoreTest.class);
+ @Before
+ public void setup(){
+ authDB = URLBasedAuthDB.getInstance();
+
+ }
+
+ @After
+ public void teardown(){
+ authDB = null;
+ PolicyRefresher pr = null;
+ }
+
+ @Test
+ public void testHdfsPolicyCacheStore(){
+ //Check if the policy cache gets created when agent get created;
+ url="dummyurl";
+ refreshInterval=10L;
+ sslConfigFileName = "dummyConfigFileName.xml";
+ lastStoredFileName = System.getProperty("user.home") +"/"+ "haooopPolicyCache.json";
+ policyContainer = buildPolicyContainer(
+ "/demo/data",
+ 1,
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ null, // ipAddress
+ true, // policyEnabled
+ true); // auditEnabled
+ authDB.OnPolicyChange(policyContainer);
+ pr = spy(new PolicyRefresher(url,refreshInterval,sslConfigFileName,lastStoredFileName));
+ pr.setPolicyContainer(policyContainer);
+ pr.setPolicyChangeListener(authDB);
+ PolicyContainer newPr = readPolicyCache(lastStoredFileName);
+ assertEquals(policyToString(policyContainer),policyToString(newPr));
+ }
+
+ private static PolicyContainer buildPolicyContainer(String resource,
+ int recursiveInd, List<String> accessTypes, List<String> users,
+ List<String> groups, List<String> ipAddresses,
+ boolean policyEnabled, boolean auditEnabled) {
+
+ PolicyContainer policyContainer = new PolicyContainer();
+ policyContainer.setRepositoryName("hadoopdev");
+
+ List<Policy> policies = new ArrayList<Policy>();
+
+ Policy policy = new Policy();
+ policy.setResource(resource);
+ policy.setRecursiveInd(recursiveInd);
+ policy.setPolicyStatus(policyEnabled ? "Enabled" : "NotEnabled");
+ policy.setAuditInd(auditEnabled ? 1 : 0);
+
+ List<RolePermission> rolePermissions = new ArrayList<RolePermission>();
+
+ RolePermission rolePermission = new RolePermission();
+
+ rolePermissions.add(rolePermission);
+ rolePermission.setAccess(accessTypes);
+ rolePermission.setUsers(users);
+ rolePermission.setGroups(groups);
+ rolePermission.setIpAddress(ipAddresses);
+
+ policy.setPermissions(rolePermissions);
+
+ policies.add(policy);
+
+ policyContainer.setAcl(policies);
+
+ return policyContainer;
+ }
+
+ private static Set<String> asSet(String... a) {
+ Set<String> vals = new HashSet<String>();
+ for (String s : a) {
+ vals.add(s);
+ }
+ return vals;
+ }
+
+ private static List<String> asList(String... a) {
+ List<String> vals = new ArrayList<String>();
+ for (String s : a) {
+ vals.add(s);
+ }
+ return vals;
+ }
+
+
+ private PolicyContainer readPolicyCache(String lastStoreFileName) {
+ BufferedReader jsonString = null;
+ try {
+ jsonString = new BufferedReader(new FileReader(lastStoredFileName));
+ } catch (FileNotFoundException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ Gson gson = new GsonBuilder().create();
+ PolicyContainer newPolicyContainer = gson.fromJson(jsonString, PolicyContainer.class);
+ return newPolicyContainer;
+ }
+
+ private String policyToString(PolicyContainer pc) {
+ Gson gson = new GsonBuilder().create() ;
+ String policyAsJson = gson.toJson(policyContainer) ;
+ return policyAsJson;
+ }
+
+
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/test/java/org/apache/ranger/pdp/hdfs/URLBasedAuthDBTest.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/test/java/org/apache/ranger/pdp/hdfs/URLBasedAuthDBTest.java b/agents-impl/src/test/java/org/apache/ranger/pdp/hdfs/URLBasedAuthDBTest.java
new file mode 100644
index 0000000..19023b6
--- /dev/null
+++ b/agents-impl/src/test/java/org/apache/ranger/pdp/hdfs/URLBasedAuthDBTest.java
@@ -0,0 +1,66 @@
+/*
+ * 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.pdp.hdfs;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.ranger.pdp.hdfs.URLBasedAuthDB;
+import org.apache.ranger.pdp.model.Policy;
+import org.apache.ranger.pdp.model.PolicyContainer;
+import org.apache.ranger.pdp.model.ResourcePath;
+import org.junit.Test;
+
+public class URLBasedAuthDBTest {
+
+ @Test
+ public void testIsAuditLogEnabledByACL_emptyPolicyContainer() {
+
+ // audit can't be enabled if authdb isn't initialized
+ assertFalse(mAuthDB.isAuditLogEnabledByACL("blah"));
+
+ // or if the policy container in is null!
+ URLBasedAuthDB spy = spy(mAuthDB);
+ when(spy.getPolicyContainer()).thenReturn(null);
+ assertFalse(mAuthDB.isAuditLogEnabledByACL("blah"));
+
+ // of if policy container is empty, i.e. has no policies!
+ List<Policy> policies = new ArrayList<Policy>();
+ PolicyContainer policyContainer = mock(PolicyContainer.class);
+ when(policyContainer.getAcl()).thenReturn(policies);
+ when(spy.getPolicyContainer()).thenReturn(policyContainer);
+ assertFalse(mAuthDB.isAuditLogEnabledByACL("blah"));
+
+ // or if all policies are empty, i.e. no acls!
+ Policy aPolicy = mock(Policy.class);
+ when(aPolicy.getResourceList()).thenReturn(new ArrayList<ResourcePath>());
+ policies.add(aPolicy);
+ when(policyContainer.getAcl()).thenReturn(policies);
+ when(spy.getPolicyContainer()).thenReturn(policyContainer);
+ assertFalse(spy.isAuditLogEnabledByACL("blah"));
+ }
+
+ private final URLBasedAuthDB mAuthDB = URLBasedAuthDB.getInstance();
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/test/java/org/apache/ranger/pdp/hdfs/URLBasedAuthDB_IsAuditLogEnabledByACL_PTest.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/test/java/org/apache/ranger/pdp/hdfs/URLBasedAuthDB_IsAuditLogEnabledByACL_PTest.java b/agents-impl/src/test/java/org/apache/ranger/pdp/hdfs/URLBasedAuthDB_IsAuditLogEnabledByACL_PTest.java
new file mode 100644
index 0000000..d2dfe96
--- /dev/null
+++ b/agents-impl/src/test/java/org/apache/ranger/pdp/hdfs/URLBasedAuthDB_IsAuditLogEnabledByACL_PTest.java
@@ -0,0 +1,340 @@
+/*
+ * 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.pdp.hdfs;
+
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.pdp.hdfs.URLBasedAuthDB;
+import org.apache.ranger.pdp.model.Policy;
+import org.apache.ranger.pdp.model.PolicyContainer;
+import org.apache.ranger.pdp.model.ResourcePath;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameters;
+
+@RunWith(Parameterized.class)
+public class URLBasedAuthDB_IsAuditLogEnabledByACL_PTest {
+
+ static class PolicyIs {
+ static final boolean wildcard = true;
+ static final boolean audited = true;
+ static final boolean recursive = true;
+
+ static final boolean notWildcard = false;
+ static final boolean notAudited = false;
+ static final boolean notRecursive = false;
+ }
+
+ static final class PolicyPath {
+ static final String path1 = "aPath";
+ static final String path1Child1 = PolicyPath.path1 + "/" + "child1";
+ static final String path1Child2 = PolicyPath.path1 + "/" + "child2";
+
+ static final String path2 = "anotherPath";
+ }
+ static final class TestPath {
+ static final String path1 = PolicyPath.path1;
+ static final String beginsWithPath1 = PolicyPath.path1 + "_";
+ static final String path1Child1 = PolicyPath.path1Child1;
+ static final String path1Child2 = PolicyPath.path1Child2;
+ static final String path1GrandChild1 = String.format("%s/%s/%s", path1, path1Child1, "grandChild1");
+ static final String path1GrandChild2 = String.format("%s/%s/%s", path1, path1Child1, "grandChild2");
+
+ static final String path2 = PolicyPath.path2;
+ static final String beginsWithPath2 = PolicyPath.path2 + "_";
+ static final String path2Child1 = PolicyPath.path2 + "/" + "child1";
+ static final String path2Child2 = PolicyPath.path2 + "/" + "child2";
+ }
+
+ static class ExpectedResult {
+ static final class AuditEnabled {
+ static final boolean yes = true;
+ static final boolean no = false;
+ }
+ }
+
+ static class TestDataIndex {
+ static final int ExpectedResult = 6;
+ static final int Audited = 3;
+ public static final int TestName = 0;
+ public static final int wildCard = 2;
+ }
+
+
+ /**
+ * ASSUMPTION: set of tests passed as such that they require wildcard flag to be set for them to return audit enabled.
+ * So turn wildcard flag of them off to assert that they no-longer work. Of course, those that don't work even with wildcard
+ * should also continue to not work when wildcard is turned off!
+ */
+ private static List<Object[]> turnWildcardOffForTestsThatRequireWildcard(List<Object[]> tests) {
+
+ // in the worse case we would generate one test for each existing test
+ List<Object[]> newTests = new ArrayList<Object[]>(tests.size());
+ for (Object[] aTest: tests) {
+ boolean isPolicyWildcard = (Boolean) aTest[TestDataIndex.wildCard];
+ if (isPolicyWildcard == PolicyIs.wildcard) {
+ Object[] newTest = Arrays.copyOf(aTest, aTest.length);
+ // Change the policy of this test so that Audit is disabled at policy level and accordingly change the expected result
+ newTest[TestDataIndex.wildCard] = PolicyIs.notWildcard;
+ newTest[TestDataIndex.ExpectedResult] = ExpectedResult.AuditEnabled.no;
+ // for debugging purposes alter the test description, too
+ String testName = (String) newTest[TestDataIndex.TestName];
+ newTest[TestDataIndex.TestName] = "[Wildcard-ed base test with wildcard flag turned off] " + testName;
+ newTests.add(newTest);
+ }
+ }
+ return newTests;
+ }
+
+ /**
+ * wildcard - policy flag says wildcard by the policy path itself does not have any wildcards worth expanding.
+ * This should work exactly the same as if wildcard was turned off!
+ */
+ private static List<Object[]> turnWildcardOnForNonWildcardTests(List<Object[]> tests) {
+
+ // in the worse case we would generate one test for each existing test
+ List<Object[]> newTests = new ArrayList<Object[]>(tests.size());
+ /*
+ * If a test currently does not have wildcard set on it, then expectation is changing wildcard flag
+ * true shouldn't change the result. ASSUMPTION here, of course, is that "base tests" don't use any
+ * wild-card characters in their resource paths that would make an otherwise disabled audit to return enabled.
+ */
+ for (Object[] aTest: tests) {
+ boolean isPolicyWildcard = (Boolean) aTest[TestDataIndex.wildCard];
+ if (isPolicyWildcard == PolicyIs.notWildcard) {
+ Object[] newTest = Arrays.copyOf(aTest, aTest.length);
+ // Change the policy of this test so that Audit is disabled at policy level and accordingly change the expected result
+ newTest[TestDataIndex.wildCard] = PolicyIs.wildcard;
+ // for debugging purposes alter the test description, too
+ String testName = (String) newTest[TestDataIndex.TestName];
+ newTest[TestDataIndex.TestName] = "[Base test with wildcard enabled] " + testName;
+ newTests.add(newTest);
+ }
+ }
+ return newTests;
+ }
+
+ /**
+ * Disabled audit on every test that expects result to be yes to ensure that no matter what answer should be false if policy says that audit is disabled!
+ */
+ private static List<Object[]> disableAuditForBaseTests(List<Object[]> tests) {
+
+ List<Object[]> newTests = new ArrayList<Object[]>(tests.size());
+
+ for (Object[] aTest : tests) {
+ boolean expectedResult = (Boolean) aTest[TestDataIndex.ExpectedResult];
+ boolean isPolicyAuditEnabled = (Boolean) aTest[TestDataIndex.Audited];
+
+ if (expectedResult == ExpectedResult.AuditEnabled.yes
+ && isPolicyAuditEnabled == PolicyIs.audited) {
+ Object[] newTest = Arrays.copyOf(aTest, aTest.length);
+ // Change the policy of this test so that Audit is disabled at policy level and accordingly change the expected result
+ newTest[TestDataIndex.Audited] = PolicyIs.notAudited;
+ newTest[TestDataIndex.ExpectedResult] = ExpectedResult.AuditEnabled.no;
+ // for debugging purposes alter the test description, too
+ String testName = (String) newTest[TestDataIndex.TestName];
+ newTest[TestDataIndex.TestName] = "[Base tests with audit disabled] " + testName;
+ newTests.add(newTest);
+ }
+ }
+
+ return newTests;
+ }
+
+ @Parameters
+ public static Collection<Object[]> data() {
+ Object[][] baseTestData = new Object[][] {
+
+ // no-recursive paths - return true if paths match
+ {"policypath(path1) == testpath(path1) => yes",
+ PolicyPath.path1, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.notRecursive, TestPath.path1, ExpectedResult.AuditEnabled.yes},
+ {"policypath(path2) == testpath(path2) => yes",
+ PolicyPath.path2, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.notRecursive, TestPath.path2, ExpectedResult.AuditEnabled.yes},
+
+ // no-recursive paths - return false if paths don't match!
+ {"policypath(path1) != testPath(path2) => no",
+ PolicyPath.path1, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.notRecursive, TestPath.path2, ExpectedResult.AuditEnabled.no},
+ {"policypath(path2) != testPath(path1) => no",
+ PolicyPath.path2, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.notRecursive, TestPath.path1, ExpectedResult.AuditEnabled.no},
+
+ // recursive path policy - should work at least as well as non-recursive, i.e. match when same and not otherwise!
+ {"recursive, policypath(path1) == testpath(path1)",
+ PolicyPath.path1, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path1, ExpectedResult.AuditEnabled.yes},
+ {"recursive, policypath(path2) == testpath(path2)",
+ PolicyPath.path2, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path2, ExpectedResult.AuditEnabled.yes},
+ {"recursive, policypath(path1) == testpath(path2)",
+ PolicyPath.path1, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path2, ExpectedResult.AuditEnabled.no},
+ {"recursive, policypath(path1) == testpath(path2)",
+ PolicyPath.path2, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path1, ExpectedResult.AuditEnabled.no},
+
+ // recursive path policy - should match children
+ {"recursive, policypath(path1) == testpath(path1/child1)",
+ PolicyPath.path1, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path1Child1, ExpectedResult.AuditEnabled.yes},
+ {"recursive, policypath(path1) == testpath(path1/child2)",
+ PolicyPath.path1, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path1Child2, ExpectedResult.AuditEnabled.yes},
+ {"recursive, policypath(path1) == testpath(path1/child1)",
+ PolicyPath.path2, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path2Child1, ExpectedResult.AuditEnabled.yes},
+ {"recursive, policypath(path1) == testpath(path1/child2)",
+ PolicyPath.path2, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path2Child2, ExpectedResult.AuditEnabled.yes},
+
+ // recursive path policy - should match grand children, too!
+ {"recursive, policypath(path1) == testpath(path1/child1/grandChild1)",
+ PolicyPath.path1, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path1GrandChild1, ExpectedResult.AuditEnabled.yes},
+ {"recursive, policypath(path1) == testpath(path1/child1/grandChild2)",
+ PolicyPath.path1, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path1GrandChild2, ExpectedResult.AuditEnabled.yes},
+
+ // recursive path policy - shouldn't match child in some other directory
+ {"recursive, policypath(path1) == testpath(path1/child1)",
+ PolicyPath.path1, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path2Child1, ExpectedResult.AuditEnabled.no},
+ {"recursive, policypath(path1) == testpath(path1/child2)",
+ PolicyPath.path1, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path2Child2, ExpectedResult.AuditEnabled.no},
+ {"recursive, policypath(path1) == testpath(path1/child1)",
+ PolicyPath.path2, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path1Child1, ExpectedResult.AuditEnabled.no},
+ {"recursive, policypath(path1) == testpath(path1/child2)",
+ PolicyPath.path2, PolicyIs.notWildcard, PolicyIs.audited, PolicyIs.recursive, TestPath.path1Child2, ExpectedResult.AuditEnabled.no},
+
+ };
+
+ Object[][] wildCardTestData = new Object[][] {
+ // Pattern contains exact substring
+ {"Wildcard, Pattern contains substring of tested path - 1",
+ "aPath*", PolicyIs.wildcard, PolicyIs.audited, PolicyIs.recursive, "aPath", ExpectedResult.AuditEnabled.yes},
+ {"Wildcard, Pattern contains substring of tested path - 2",
+ "*aPath", PolicyIs.wildcard, PolicyIs.audited, PolicyIs.recursive, "aPath", ExpectedResult.AuditEnabled.yes},
+ {"Wildcard, Pattern contains substring of tested path - 3",
+ "aPa*th", PolicyIs.wildcard, PolicyIs.audited, PolicyIs.recursive, "aPath", ExpectedResult.AuditEnabled.yes},
+ {"Wildcard, Pattern contains substring of tested path - 4",
+ "aP*at*h", PolicyIs.wildcard, PolicyIs.audited, PolicyIs.recursive, "aPath", ExpectedResult.AuditEnabled.yes},
+
+ // Pattern should match
+ {"Wildcard, Pattern should match - 1",
+ "aPath*", PolicyIs.wildcard, PolicyIs.audited, PolicyIs.recursive, "aPath_", ExpectedResult.AuditEnabled.yes},
+ {"Wildcard, Pattern should match - 2",
+ "aPath*", PolicyIs.wildcard, PolicyIs.audited, PolicyIs.recursive, "aPath_longSuffix", ExpectedResult.AuditEnabled.yes},
+ {"Wildcard, Pattern should match - 3",
+ "*aPath", PolicyIs.wildcard, PolicyIs.audited, PolicyIs.recursive, "_aPath", ExpectedResult.AuditEnabled.yes},
+ {"Wildcard, Pattern should match - 4",
+ "*aPath", PolicyIs.wildcard, PolicyIs.audited, PolicyIs.recursive, "longPrefix_aPath", ExpectedResult.AuditEnabled.yes},
+ {"Wildcard, Pattern should match - 5",
+ "*aPath", PolicyIs.wildcard, PolicyIs.audited, PolicyIs.recursive, "_aPath", ExpectedResult.AuditEnabled.yes},
+ {"Wildcard, Pattern should match - 6",
+ "*aPath", PolicyIs.wildcard, PolicyIs.audited, PolicyIs.recursive, "longPrefix_aPath", ExpectedResult.AuditEnabled.yes},
+ {"Wildcard, Pattern should match - 5",
+ "a*Path", PolicyIs.wildcard, PolicyIs.audited, PolicyIs.recursive, "a___Path", ExpectedResult.AuditEnabled.yes},
+ {"Wildcard, Pattern should match - 6",
+ "a*Path", PolicyIs.wildcard, PolicyIs.audited, PolicyIs.recursive, "aMiddlePath", ExpectedResult.AuditEnabled.yes},
+ };
+
+ // in the worst case all tests have a corresponding audit disabled test
+ List<Object[]> baseTests = Arrays.asList(baseTestData);
+ List<Object[]> result = new ArrayList<Object[]>(baseTests);
+
+ // answer is false no matter what if policy is set to not audit
+ List<Object[]> additionalTests = disableAuditForBaseTests(baseTests);
+ result.addAll(additionalTests);
+
+ // turning wildcard flag on when policy path itself does not have wildcard characters in it shouldn't change the result!
+ additionalTests = turnWildcardOnForNonWildcardTests(baseTests);
+ result.addAll(additionalTests);
+
+ List<Object[]> wildcardBaseTests = Arrays.asList(wildCardTestData);
+ result.addAll(wildcardBaseTests);
+
+ additionalTests = turnWildcardOffForTestsThatRequireWildcard(wildcardBaseTests);
+ result.addAll(additionalTests);
+ return result;
+ }
+
+ public URLBasedAuthDB_IsAuditLogEnabledByACL_PTest(String testName, String policyPath, boolean wildCard, boolean audited, boolean recursive, String testPath, boolean expectedResult) {
+ _testName = testName;
+ _policyPath = policyPath;
+ _policyPathWildcard = wildCard;
+ _policyAudited = audited;
+ _policyRecursive = recursive;
+ _testPath = testPath;
+ _expectedResult = expectedResult;
+ }
+
+ private final String _testName;
+ private final String _policyPath;
+ private final boolean _policyPathWildcard;
+ private final boolean _policyAudited;
+ private final boolean _policyRecursive;
+ private final String _testPath;
+ private final boolean _expectedResult;
+
+ @Test
+ public void testIsAuditLogEnabledByACL() {
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(String.format("Test: %sPolicy Path: %s, isWildcard: %b, isAudited: %b, isRecursive: %b, TestPath: %s",
+ _testName, _policyPath, _policyPathWildcard, _policyAudited, _policyRecursive, _testPath));
+ }
+
+ // A policy can have several paths, so let's first stuff our path into a collection
+ ResourcePath path = mock(ResourcePath.class);
+ when(path.getPath()).thenReturn(_policyPath);
+ when(path.isWildcardPath()).thenReturn(_policyPathWildcard);
+ List<ResourcePath> resourcePaths = new ArrayList<ResourcePath>();
+ resourcePaths.add(path);
+
+ // wire it into the policy and set other aspects of the policy
+ Policy aPolicy = mock(Policy.class);
+ when(aPolicy.getResourceList()).thenReturn(resourcePaths);
+
+ int recursiveIndicator = _policyRecursive ? 1 : 0;
+ when(aPolicy.getRecursiveInd()).thenReturn(recursiveIndicator);
+
+ int auditedIndicator = _policyAudited ? 1 : 0;
+ when(aPolicy.getAuditInd()).thenReturn(auditedIndicator);
+
+ // a container can have several policies to first we stuff our policy into a container
+ List<Policy> policies = new ArrayList<Policy>();
+ policies.add(aPolicy);
+ // now wire the policy into the container
+ PolicyContainer policyContainer = mock(PolicyContainer.class);
+ when(policyContainer.getAcl()).thenReturn(policies);
+
+ // finally wire the policy container into the authdb
+ URLBasedAuthDB spy = spy(mAuthDB);
+ when(spy.getPolicyContainer()).thenReturn(policyContainer);
+
+ // assert the result
+ boolean result = spy.isAuditLogEnabledByACL(_testPath);
+ assertThat(_testName, result, is(_expectedResult));
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(String.format(", Expected Result (Audit enabled?): %b Result: %b\n", _expectedResult, result));
+ }
+ }
+
+ private final URLBasedAuthDB mAuthDB = URLBasedAuthDB.getInstance();
+ private static final Log LOG = LogFactory.getLog(URLBasedAuthDB_IsAuditLogEnabledByACL_PTest.class) ;
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-impl/src/test/java/org/apache/ranger/pdp/knox/URLBasedAuthDBTest.java
----------------------------------------------------------------------
diff --git a/agents-impl/src/test/java/org/apache/ranger/pdp/knox/URLBasedAuthDBTest.java b/agents-impl/src/test/java/org/apache/ranger/pdp/knox/URLBasedAuthDBTest.java
new file mode 100644
index 0000000..3e0724d
--- /dev/null
+++ b/agents-impl/src/test/java/org/apache/ranger/pdp/knox/URLBasedAuthDBTest.java
@@ -0,0 +1,956 @@
+/**
+ * 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.pdp.knox;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.ranger.pdp.knox.URLBasedAuthDB;
+import org.apache.ranger.pdp.model.Policy;
+import org.apache.ranger.pdp.model.PolicyContainer;
+import org.apache.ranger.pdp.model.RolePermission;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class URLBasedAuthDBTest {
+
+ @Test
+ public void testPolicyEnabled() {
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ null, // ipAddress
+ true, // policyEnabled
+ true); // auditEnabled
+ pdp.setPolicyContainer(policyContainer);
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "WEBHDFS",
+ "allow",
+ "guest",
+ asSet("sales"),
+ "127.127.127.127");
+ System.out.println("testPolicyEnabled allowed: " + allowed);
+ Assert.assertTrue("Access denied while policy is enabled", allowed);
+ }
+
+ @Test
+ public void testPolicyNotEnabled() {
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ null, // ipAddress
+ false, // policyEnabled
+ true); // auditEnabled
+ pdp.setPolicyContainer(policyContainer);
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "WEBHDFS",
+ "allow",
+ "guest",
+ asSet("sales"),
+ "127.127.127.127");
+ System.out.println("testPolicyNotEnabled allowed: " + allowed);
+ Assert.assertFalse("Access allowed while policy is disabled", allowed);
+ }
+
+ @Test
+ public void testPolicyEnabledAuditOnTmSm() {
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ null, // ipAddress
+ true, // policyEnabled
+ true); // auditEnabled
+ pdp.setPolicyContainer(policyContainer);
+
+ boolean auditEnabled = pdp.isAuditEnabled(
+ "xa",
+ "WEBHDFS"
+ );
+ System.out.println("testPolicyEnabledAuditOnTmSm: " + auditEnabled);
+ Assert.assertTrue("Audit not ebabled while policy is matched", auditEnabled);
+ }
+
+ @Test
+ public void testPolicyEnabledAuditOnTnmSm() {
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ null, // ipAddress
+ true, // policyEnabled
+ true); // auditEnabled
+ pdp.setPolicyContainer(policyContainer);
+
+ boolean auditEnabled = pdp.isAuditEnabled(
+ "yxa",
+ "WEBHDFS"
+ );
+ System.out.println("testPolicyEnabledAuditOnTnmSm auditEnabled: " + auditEnabled);
+ Assert.assertFalse("Audit ebabled with a non matching topology", auditEnabled);
+ }
+
+ @Test
+ public void testPolicyEnabledAuditOnTmSnm() {
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ null, // ipAddress
+ true, // policyEnabled
+ true); // auditEnabled
+ pdp.setPolicyContainer(policyContainer);
+
+ boolean auditEnabled = pdp.isAuditEnabled(
+ "xa",
+ "yWEBHDFS"
+ );
+ System.out.println("testPolicyEnabledAuditOnTmSnm auditEnabled: " + auditEnabled);
+ Assert.assertFalse("Audit ebabled with a non matching service", auditEnabled);
+ }
+
+ @Test
+ public void testPolicyEnabledAuditOff() {
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ null, // ipAddress
+ true, // policyEnabled
+ false); // auditEnabled
+ pdp.setPolicyContainer(policyContainer);
+
+ boolean auditEnabled = pdp.isAuditEnabled(
+ "xa",
+ "WEBHDFS"
+ );
+ System.out.println("testPolicyEnabledAuditOff auditEnabled: " + auditEnabled);
+ Assert.assertFalse("Audit ebabled with policy disabling audit", auditEnabled);
+ }
+
+ @Test
+ public void testPolicyNotEnabledAuditOn() {
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ null, // ipAddress
+ false, // policyEnabled
+ true); // auditEnabled
+ pdp.setPolicyContainer(policyContainer);
+
+ boolean auditEnabled = pdp.isAuditEnabled(
+ "xa",
+ "WEBHDFS"
+ );
+ System.out.println("testPolicyNotEnabledAuditOn auditEnabled: " + auditEnabled);
+ Assert.assertFalse("Audit ebabled with policy not enabled", auditEnabled);
+ }
+
+ @Test
+ public void testPolicyNotEnabledAuditOff() {
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ null, // ipAddress
+ false, // policyEnabled
+ true); // auditEnabled
+ pdp.setPolicyContainer(policyContainer);
+
+ boolean auditEnabled = pdp.isAuditEnabled(
+ "xa",
+ "WEBHDFS"
+ );
+ System.out.println("testPolicyNotEnabledAuditOff auditEnabled: " + auditEnabled);
+ Assert.assertFalse("Audit ebabled with policy not enabled and audit off", auditEnabled);
+ }
+
+ @Test
+ public void testSimpleTopologyAccessAllowed() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ null);
+ pdp.setPolicyContainer(policyContainer);
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "WEBHDFS",
+ "allow",
+ "guest",
+ asSet("sales"),
+ "127.127.127.127");
+ System.out.println("testSimpleTopologyAccessAllowed allowed: " + allowed);
+ Assert.assertTrue("Access denied for a simple allow policy", allowed);
+
+ }
+
+ @Test
+ public void testSimpleTopologyAccessDenied() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ null);
+ pdp.setPolicyContainer(policyContainer);
+
+ boolean allowed = pdp.isAccessGranted(
+ "ya",
+ "WEBHDFS",
+ "allow",
+ "guest",
+ asSet("sales"),
+ "127.127.127.127");
+ System.out.println("testSimpleTopologyAccessDenied allowed: " + allowed);
+ Assert.assertFalse("Access allwed for a simple deny policy", allowed);
+
+ }
+
+ @Test
+ public void testWildTopologyAccessAllowed() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "x*",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ null);
+ pdp.setPolicyContainer(policyContainer);
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "WEBHDFS",
+ "allow",
+ "guest",
+ asSet("sales"),
+ "127.127.127.127");
+ System.out.println("testWildTopologyAccessAllowed allowed: " + allowed);
+ Assert.assertTrue("Access denied for a matching wild topology policy", allowed);
+
+ }
+
+ @Test
+ public void testWildTopologyAccessDenied() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "x*",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ null);
+ pdp.setPolicyContainer(policyContainer);
+
+ boolean allowed = pdp.isAccessGranted(
+ "ya",
+ "WEBHDFS",
+ "allow",
+ "guest",
+ asSet("sales"),
+ "127.127.127.127");
+ System.out.println("testWildTopologyAccessDenied allowed: " + allowed);
+ Assert.assertFalse("Access allowed for non matching wild topology policy", allowed);
+
+ }
+
+ @Test
+ public void testSimpleServiceAccessAllowed() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ null);
+ pdp.setPolicyContainer(policyContainer);
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "WEBHDFS",
+ "allow",
+ "guest",
+ asSet("sales"),
+ "127.127.127.127");
+ System.out.println("testSimpleServiceAccessAllowed allowed: " + allowed);
+ Assert.assertTrue("Access denied for a policy matching service", allowed);
+
+ }
+
+ @Test
+ public void testSimpleServiceAccessDenied() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ null);
+ pdp.setPolicyContainer(policyContainer);
+
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "yWEBHDFS",
+ "allow",
+ "guest",
+ asSet("sales"),
+ "127.127.127.127");
+ System.out.println("testSimpleServiceAccessDenied allowed: " + allowed);
+ Assert.assertFalse("Access allowed for a policy with no matching service", allowed);
+
+ }
+
+ @Test
+ public void testWildServiceAccessAllowed() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEB*",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ null);
+ pdp.setPolicyContainer(policyContainer);
+
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "WEBHDFS",
+ "allow",
+ "guest",
+ asSet("sales"),
+ "127.127.127.127");
+ System.out.println("testWildServiceAccessAllowed allowed: " + allowed);
+ Assert.assertTrue("Access denied for policy with matching wild service", allowed);
+
+ }
+
+ @Test
+ public void testWildServiceAccessDenied() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEB*",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ null);
+ pdp.setPolicyContainer(policyContainer);
+
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "yWEBHDFS",
+ "allow",
+ "guest",
+ asSet("sales"),
+ "127.127.127.127");
+ System.out.println("testWildServiceAccessDenied allowed: " + allowed);
+ Assert.assertFalse("Access allowed for a policy with a non matching wild service", allowed);
+
+ }
+
+ @Test
+ public void testAccessTypeAccessAllowed() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ null);
+ pdp.setPolicyContainer(policyContainer);
+
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "WEBHDFS",
+ "allow",
+ "guest",
+ asSet("sales"),
+ "127.127.127.127");
+ System.out.println("testAccessTypeAccessAllowed allowed: " + allowed);
+ Assert.assertTrue("Access denied for a policy with matching accessTyoe", allowed);
+
+ }
+
+ @Test
+ public void testAccessTypeAccessDenied() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ null);
+ pdp.setPolicyContainer(policyContainer);
+
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "WEBHDFS",
+ "yallow",
+ "guest",
+ asSet("sales"),
+ "127.127.127.127");
+ System.out.println("testAccessTypeAccessDenied allowed: " + allowed);
+ Assert.assertFalse("Access allowed for a non matching accessType", allowed);
+
+ }
+
+ @Test
+ public void testUserAccessAllowed() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ null);
+ pdp.setPolicyContainer(policyContainer);
+
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "WEBHDFS",
+ "allow",
+ "guest",
+ asSet("sales"),
+ "127.127.127.127");
+ System.out.println("testUserAccessAllowed allowed: " + allowed);
+ Assert.assertTrue("Access denied for matching user", allowed);
+
+ }
+
+ @Test
+ public void testUserAccessDenied() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("yguest"),
+ asList("sales"),
+ null);
+ pdp.setPolicyContainer(policyContainer);
+
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "WEBHDFS",
+ "yallow",
+ "guest",
+ asSet("sales"),
+ "127.127.127.127");
+ System.out.println("testUserAccessDenied allowed: " + allowed);
+ Assert.assertFalse("Access allowed for a non matching user", allowed);
+
+ }
+
+ @Test
+ public void testGroupAccessAllowed() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ null,
+ asList("sales"),
+ null);
+ pdp.setPolicyContainer(policyContainer);
+
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "WEBHDFS",
+ "allow",
+ "sam",
+ asSet("sales"),
+ "127.127.127.127");
+ System.out.println("testGroupAccessAllowe allowed: " + allowed);
+ Assert.assertTrue("Access denied for a matching user group", allowed);
+
+ }
+
+ @Test
+ public void testGroupAccessDenied() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ null,
+ asList("sales"),
+ null);
+ pdp.setPolicyContainer(policyContainer);
+
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "WEBHDFS",
+ "yallow",
+ "guest",
+ asSet("sales"),
+ "127.127.127.127");
+ System.out.println("testGroupAccessDenied allowed: " + allowed);
+ Assert.assertFalse("Access allowed for a non matching user group", allowed);
+
+ }
+
+
+
+ @Test
+ public void testSimpleIP4Allowed() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ asList("132.133.134.135"));
+ pdp.setPolicyContainer(policyContainer);
+
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "WEBHDFS",
+ "allow",
+ "guest",
+ asSet("sales"),
+ "132.133.134.135");
+ System.out.println("testSimpleIP4Allowed allowed: " + allowed);
+ Assert.assertTrue("Access denied for a matching IP4 request ip", allowed);
+
+ }
+
+ @Test
+ public void testSimpleIP4Denied() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ asList("132.133.134.135"));
+ pdp.setPolicyContainer(policyContainer);
+
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "WEBHDFS",
+ "allow",
+ "guest",
+ asSet("sales"),
+ "132.133.134.136");
+ System.out.println("testSimpleIP4Denied allowed: " + allowed);
+ Assert.assertFalse("Access allowed for a non matching IP4 request ip", allowed);
+
+ }
+
+ @Test
+ public void testWildIP4Allowed() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ asList("132.133.134.*"));
+ pdp.setPolicyContainer(policyContainer);
+
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "WEBHDFS",
+ "allow",
+ "guest",
+ asSet("sales"),
+ "132.133.134.135");
+ System.out.println("testWildIP4Allowed allowed: " + allowed);
+ Assert.assertTrue("Access denied for a request ip matching wild IP4", allowed);
+
+ }
+
+ @Test
+ public void testWildIP4Denied() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ asList("132.133.134.*"));
+ pdp.setPolicyContainer(policyContainer);
+
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "WEBHDFS",
+ "allow",
+ "guest",
+ asSet("sales"),
+ "132.133.234.136");
+ System.out.println("testWildIP4Denied allowed: " + allowed);
+ Assert.assertFalse("Access allowed for a request ip not matching wild IP4", allowed);
+
+ }
+
+ @Test
+ public void testWilderIP4Allowed() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ asList("132.133.*.*"));
+ pdp.setPolicyContainer(policyContainer);
+
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "WEBHDFS",
+ "allow",
+ "guest",
+ asSet("sales"),
+ "132.133.234.235");
+ System.out.println("testWilderIP4Allowed: " + allowed);
+ Assert.assertTrue("Access denied for a request ip matching wilder IP4", allowed);
+
+ }
+
+ @Test
+ public void testWilderIP4Denied() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ asList("132.133.*.*"));
+ pdp.setPolicyContainer(policyContainer);
+
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "WEBHDFS",
+ "allow",
+ "guest",
+ asSet("sales"),
+ "132.233.234.136");
+ System.out.println("testWilderIP4Denied allowed: " + allowed);
+ Assert.assertFalse("Access allowed for a request ip not matching wilder IP4", allowed);
+
+ }
+
+ @Test
+ public void testWildIP6Allowed() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ asList("132:133:134:*"));
+ pdp.setPolicyContainer(policyContainer);
+
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "WEBHDFS",
+ "allow",
+ "guest",
+ asSet("sales"),
+ "132:133:134:135");
+ System.out.println("testWildIP6Allowed allowed: " + allowed);
+ Assert.assertTrue("Access denied for a request ip matching wild IP6", allowed);
+
+ }
+
+ @Test
+ public void testWildIP6AllowedMixedCase() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ asList("132:133:Db8:*"));
+ pdp.setPolicyContainer(policyContainer);
+
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "WEBHDFS",
+ "allow",
+ "guest",
+ asSet("sales"),
+ "132:133:dB8:135");
+ System.out.println("testWildIP6AllowedMixedCase: " + allowed);
+ Assert.assertTrue("Access denied for a request ip matching wild IP6 with mixed case", allowed);
+
+ }
+
+ @Test
+ public void testWildIP6Denied() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ asList("132:133:134:*"));
+ pdp.setPolicyContainer(policyContainer);
+
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "WEBHDFS",
+ "allow",
+ "guest",
+ asSet("sales"),
+ "132:133:234:136");
+ System.out.println("testWildIP6Denied allowed: " + allowed);
+ Assert.assertFalse("Access allowed for a request ip not matching wild IP6", allowed);
+
+ }
+
+ @Test
+ public void testWilderIP6Allowed() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ asList("132:133:*:*"));
+ pdp.setPolicyContainer(policyContainer);
+
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "WEBHDFS",
+ "allow",
+ "guest",
+ asSet("sales"),
+ "132:133:234:235");
+ System.out.println("testWilderIP6Allowed allowed: " + allowed);
+ Assert.assertTrue("Access denied for a request ip matching wilder IP6", allowed);
+
+ }
+
+ @Test
+ public void testWilderIP6Denied() {
+
+ URLBasedAuthDB pdp = URLBasedAuthDB.getInstanceWithBackEndMocked();
+
+ PolicyContainer policyContainer = buildPolicyContainer(
+ "xa",
+ "WEBHDFS",
+ asList("allow"),
+ asList("guest"),
+ asList("sales"),
+ asList("132:133:*:*"));
+ pdp.setPolicyContainer(policyContainer);
+
+
+ boolean allowed = pdp.isAccessGranted(
+ "xa",
+ "WEBHDFS",
+ "allow",
+ "guest",
+ asSet("sales"),
+ "132:233:234:136");
+ System.out.println("testWilderIP6Denied allowed: " + allowed);
+ Assert.assertFalse("Access allowed for a request ip not matching wilder IP6", allowed);
+
+ }
+
+ private static PolicyContainer buildPolicyContainer(String topologies,
+ String services, List<String> accessTypes, List<String> users,
+ List<String> groups, List<String> ipAddresses) {
+ return buildPolicyContainer( topologies, services, accessTypes,
+ users, groups, ipAddresses, true, true);
+
+ }
+
+ private static PolicyContainer buildPolicyContainer(String topologies,
+ String services, List<String> accessTypes, List<String> users,
+ List<String> groups, List<String> ipAddresses,
+ boolean policyEnabled, boolean auditEnabled) {
+
+ PolicyContainer policyContainer = new PolicyContainer();
+ policyContainer.setRepositoryName("knoxdev");
+
+ List<Policy> policies = new ArrayList<Policy>();
+
+ Policy policy = new Policy();
+ policy.setTopologies(topologies);
+ policy.setServices(services);
+ policy.setPolicyStatus(policyEnabled ? "Enabled" : "NotEnabled");
+ policy.setAuditInd(auditEnabled ? 1 : 0);
+
+ List<RolePermission> rolePermissions = new ArrayList<RolePermission>();
+
+ RolePermission rolePermission = new RolePermission();
+
+ rolePermissions.add(rolePermission);
+ rolePermission.setAccess(accessTypes);
+ rolePermission.setUsers(users);
+ rolePermission.setGroups(groups);
+ rolePermission.setIpAddress(ipAddresses);
+
+ policy.setPermissions(rolePermissions);
+
+ policies.add(policy);
+
+ policyContainer.setAcl(policies);
+
+ return policyContainer;
+ }
+
+ private static Set<String> asSet(String... a) {
+ Set<String> vals = new HashSet<String>();
+ for (String s : a) {
+ vals.add(s);
+ }
+ return vals;
+ }
+
+ private static List<String> asList(String... a) {
+ List<String> vals = new ArrayList<String>();
+ for (String s : a) {
+ vals.add(s);
+ }
+ return vals;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-installer/src/main/java/com/xasecure/utils/install/PasswordGenerator.java
----------------------------------------------------------------------
diff --git a/agents-installer/src/main/java/com/xasecure/utils/install/PasswordGenerator.java b/agents-installer/src/main/java/com/xasecure/utils/install/PasswordGenerator.java
deleted file mode 100644
index 8d84223..0000000
--- a/agents-installer/src/main/java/com/xasecure/utils/install/PasswordGenerator.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * 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 com.xasecure.utils.install;
-
-import java.util.ArrayList;
-import java.util.Random;
-
-public class PasswordGenerator {
-
-
- private int minimumPasswordLength = 8 ;
-
- private int maximumPasswordLength = 12 ;
-
- private boolean isExpectedNumberic = true ;
-
- private boolean isExpectedBothCase = true ;
-
- private static final ArrayList<Character> alphaLetters = new ArrayList<Character>() ;
-
- private static final ArrayList<Character> alphaUpperLetters = new ArrayList<Character>() ;
-
- private static final ArrayList<Character> numericLetters = new ArrayList<Character>() ;
-
-
- static {
- for(int x = 'a' ; x <= 'z' ; x++) {
- char v = (char)x ;
- alphaLetters.add(Character.toLowerCase(v)) ;
- alphaUpperLetters.add(Character.toUpperCase(v)) ;
- }
- for(int i = 0 ; i < 10 ; i++) {
- numericLetters.add(Character.forDigit(i,10)) ;
- }
- }
-
-
-
- public static void main(String[] args) {
- PasswordGenerator pg = new PasswordGenerator() ;
- System.out.println(pg.generatorPassword()) ;
- }
-
-
- private int getPasswordLength() {
- int ret = 0;
-
- if (minimumPasswordLength == maximumPasswordLength) {
- ret = minimumPasswordLength ;
- }
- else {
-
- int diff = Math.abs(maximumPasswordLength - minimumPasswordLength) + 1 ;
- ret = minimumPasswordLength + new Random().nextInt(diff) ;
- }
- return (ret) ;
- }
-
-
- public String generatorPassword() {
-
- String password = null ;
-
- ArrayList<Character> all = new ArrayList<Character>() ;
-
- all.addAll(alphaLetters) ;
- all.addAll(alphaUpperLetters) ;
- all.addAll(numericLetters) ;
-
- int len = getPasswordLength() ;
-
- Random random = new Random() ;
-
- int setSz = all.size();
-
- do
- {
- StringBuilder sb = new StringBuilder();
-
- for(int i = 0 ; i < len ; i++) {
- int index = random.nextInt(setSz) ;
- Character c = all.get(index) ;
- while ((i == 0) && Character.isDigit(c)) {
- index = random.nextInt(setSz) ;
- c = all.get(index) ;
- }
- sb.append(all.get(index)) ;
- }
- password = sb.toString() ;
- } while (! isValidPassword(password)) ;
-
-
- return password ;
-
- }
-
- private boolean isValidPassword(String pass) {
- boolean ret = true ;
-
- if (isExpectedNumberic || isExpectedBothCase) {
- boolean lowerCaseFound = false ;
- boolean digitFound = false ;
- boolean upperCaseFound = false ;
- for(char c : pass.toCharArray()) {
- if (!digitFound && Character.isDigit(c)) {
- digitFound = true ;
- }
- else if (!lowerCaseFound && Character.isLowerCase(c)) {
- lowerCaseFound = true ;
- }
- else if (!upperCaseFound && Character.isUpperCase(c) ) {
- upperCaseFound = true ;
- }
- }
-
- if (isExpectedNumberic && !digitFound) {
- ret = false ;
- }
-
- if (isExpectedBothCase && (!lowerCaseFound || !upperCaseFound)) {
- ret = false ;
- }
- }
-
- return ret ;
- }
-}
[35/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hbase-agent/src/main/java/com/xasecure/authorization/hbase/XaSecureAuthorizationCoprocessor.java
----------------------------------------------------------------------
diff --git a/hbase-agent/src/main/java/com/xasecure/authorization/hbase/XaSecureAuthorizationCoprocessor.java b/hbase-agent/src/main/java/com/xasecure/authorization/hbase/XaSecureAuthorizationCoprocessor.java
deleted file mode 100644
index fc032c5..0000000
--- a/hbase-agent/src/main/java/com/xasecure/authorization/hbase/XaSecureAuthorizationCoprocessor.java
+++ /dev/null
@@ -1,1259 +0,0 @@
-/*
- * 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 com.xasecure.authorization.hbase;
-import java.io.IOException;
-import java.net.InetAddress;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.Collection;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.NavigableSet;
-import java.util.Set;
-import java.util.TimeZone;
-
-import org.apache.commons.lang.StringUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.hbase.Cell;
-import org.apache.hadoop.hbase.CellUtil;
-import org.apache.hadoop.hbase.CoprocessorEnvironment;
-import org.apache.hadoop.hbase.HColumnDescriptor;
-import org.apache.hadoop.hbase.HRegionInfo;
-import org.apache.hadoop.hbase.HTableDescriptor;
-import org.apache.hadoop.hbase.KeyValue;
-import org.apache.hadoop.hbase.NamespaceDescriptor;
-import org.apache.hadoop.hbase.ServerName;
-import org.apache.hadoop.hbase.TableName;
-import org.apache.hadoop.hbase.client.Append;
-import org.apache.hadoop.hbase.client.Delete;
-import org.apache.hadoop.hbase.client.Durability;
-import org.apache.hadoop.hbase.client.Get;
-import org.apache.hadoop.hbase.client.Increment;
-import org.apache.hadoop.hbase.client.Put;
-import org.apache.hadoop.hbase.client.Result;
-import org.apache.hadoop.hbase.client.Scan;
-import org.apache.hadoop.hbase.coprocessor.CoprocessorException;
-import org.apache.hadoop.hbase.coprocessor.CoprocessorService;
-import org.apache.hadoop.hbase.coprocessor.MasterCoprocessorEnvironment;
-import org.apache.hadoop.hbase.coprocessor.ObserverContext;
-import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
-import org.apache.hadoop.hbase.coprocessor.RegionServerCoprocessorEnvironment;
-import org.apache.hadoop.hbase.filter.ByteArrayComparable;
-import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
-import org.apache.hadoop.hbase.filter.FilterList;
-import org.apache.hadoop.hbase.ipc.RequestContext;
-import org.apache.hadoop.hbase.master.RegionPlan;
-import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
-import org.apache.hadoop.hbase.protobuf.ResponseConverter;
-import org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos;
-import org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos.AccessControlService;
-import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
-import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.CleanupBulkLoadRequest;
-import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.PrepareBulkLoadRequest;
-import org.apache.hadoop.hbase.regionserver.HRegion;
-import org.apache.hadoop.hbase.regionserver.InternalScanner;
-import org.apache.hadoop.hbase.regionserver.RegionScanner;
-import org.apache.hadoop.hbase.regionserver.ScanType;
-import org.apache.hadoop.hbase.regionserver.Store;
-import org.apache.hadoop.hbase.regionserver.StoreFile;
-import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
-import org.apache.hadoop.hbase.security.AccessDeniedException;
-import org.apache.hadoop.hbase.security.User;
-import org.apache.hadoop.hbase.security.access.Permission;
-import org.apache.hadoop.hbase.security.access.Permission.Action;
-import org.apache.hadoop.hbase.security.access.TablePermission;
-import org.apache.hadoop.hbase.security.access.UserPermission;
-import org.apache.hadoop.hbase.security.access.XaAccessControlLists;
-import org.apache.hadoop.hbase.util.Bytes;
-import org.apache.hadoop.hbase.util.Pair;
-
-import com.google.common.collect.Lists;
-import com.google.common.collect.MapMaker;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-import com.google.protobuf.RpcCallback;
-import com.google.protobuf.RpcController;
-import com.google.protobuf.Service;
-import com.xasecure.admin.client.XaAdminRESTClient;
-import com.xasecure.admin.client.datatype.GrantRevokeData;
-import com.xasecure.admin.client.datatype.GrantRevokeData.PermMap;
-import com.xasecure.audit.model.EnumRepositoryType;
-import com.xasecure.audit.model.HBaseAuditEvent;
-import com.xasecure.audit.provider.AuditProviderFactory;
-import com.xasecure.authorization.hadoop.config.XaSecureConfiguration;
-import com.xasecure.authorization.hadoop.constants.XaSecureHadoopConstants;
-import com.xasecure.authorization.utils.StringUtil;
-
-public class XaSecureAuthorizationCoprocessor extends XaSecureAuthorizationCoprocessorBase implements AccessControlService.Interface, CoprocessorService {
- private static final Log LOG = LogFactory.getLog(XaSecureAuthorizationCoprocessor.class.getName());
- private static final String XaSecureModuleName = XaSecureConfiguration.getInstance().get(XaSecureHadoopConstants.AUDITLOG_XASECURE_MODULE_ACL_NAME_PROP , XaSecureHadoopConstants.DEFAULT_XASECURE_MODULE_ACL_NAME) ;
- private static final short accessGrantedFlag = 1;
- private static final short accessDeniedFlag = 0;
- private static final String repositoryName = XaSecureConfiguration.getInstance().get(XaSecureHadoopConstants.AUDITLOG_REPOSITORY_NAME_PROP);
- private static final boolean UpdateXaPoliciesOnGrantRevoke = XaSecureConfiguration.getInstance().getBoolean(XaSecureHadoopConstants.HBASE_UPDATE_XAPOLICIES_ON_GRANT_REVOKE_PROP, XaSecureHadoopConstants.HBASE_UPDATE_XAPOLICIES_ON_GRANT_REVOKE_DEFAULT_VALUE);
- private static final String GROUP_PREFIX = "@";
-
-
- private static final String SUPERUSER_CONFIG_PROP = "hbase.superuser";
- private static final String WILDCARD = "*";
- private static final byte[] WILDCARD_MATCH = "*".getBytes();
-
- private static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT+0");
-
- private RegionCoprocessorEnvironment regionEnv;
- private Map<InternalScanner, String> scannerOwners = new MapMaker().weakKeys().makeMap();
-
- private HBaseAccessController accessController = HBaseAccessControllerFactory.getInstance();
- private List<String> superUserList = null;
- // Utilities Methods
- protected byte[] getTableName(RegionCoprocessorEnvironment e) {
- HRegion region = e.getRegion();
- byte[] tableName = null;
- if (region != null) {
- HRegionInfo regionInfo = region.getRegionInfo();
- if (regionInfo != null) {
- tableName = regionInfo.getTable().getName() ;
- }
- }
- return tableName;
- }
- protected void isSystemOrSuperUser(Configuration conf) throws IOException {
- User user = User.getCurrent();
- if (user == null) {
- throw new IOException("Unable to obtain the current user, authorization checks for internal operations will not work correctly!");
- }
- String currentUser = user.getShortName();
- List<String> superusers = Lists.asList(currentUser, conf.getStrings(SUPERUSER_CONFIG_PROP, new String[0]));
- User activeUser = getActiveUser();
- if (!(superusers.contains(activeUser.getShortName()))) {
- throw new AccessDeniedException("User '" + (user != null ? user.getShortName() : "null") + "is not system or super user.");
- }
- }
- private boolean isSuperUser(User user) {
- boolean isSuper = false;
- isSuper = (superUserList != null && superUserList.contains(user.getShortName()));
- if (LOG.isDebugEnabled()) {
- LOG.debug("IsSuperCheck on [" + user.getShortName() + "] returns [" + isSuper + "]");
- }
- return isSuper;
- }
- protected boolean isSpecialTable(HRegionInfo regionInfo) {
- return isSpecialTable(regionInfo.getTable().getName());
- }
- protected boolean isSpecialTable(byte[] tableName) {
- return isSpecialTable(Bytes.toString(tableName));
- }
- protected boolean isSpecialTable(String tableNameStr) {
- return tableNameStr.equals("hbase:meta") || tableNameStr.equals("-ROOT-") || tableNameStr.equals(".META.");
- }
- @SuppressWarnings("unused")
- private String getUser() {
- User u = getActiveUser();
- if (u == null) {
- return "(user:unknown)";
- } else {
- String groups = (u.getGroupNames() == null) ? "" : StringUtils.join(u.getGroupNames(), ",");
- return "(user:" + u.getShortName() + ", groups: [" + groups + "])";
- }
- }
- private User getActiveUser() {
- User user = RequestContext.getRequestUser();
- if (!RequestContext.isInRequestContext()) {
- // for non-rpc handling, fallback to system user
- try {
- user = User.getCurrent();
- } catch (IOException e) {
- LOG.error("Unable to find the current user");
- user = null;
- }
- }
- return user;
- }
-
- private String getRemoteAddress() {
- RequestContext reqContext = RequestContext.get();
- InetAddress remoteAddr = reqContext != null ? reqContext.getRemoteAddress() : null;
- String strAddr = remoteAddr != null ? remoteAddr.getHostAddress() : null;
-
- return strAddr;
- }
-
- // Methods that are used within the CoProcessor
- private void requireScannerOwner(InternalScanner s) throws AccessDeniedException {
- if (RequestContext.isInRequestContext()) {
- String requestUserName = RequestContext.getRequestUserName();
- String owner = scannerOwners.get(s);
- if (owner != null && !owner.equals(requestUserName)) {
- throw new AccessDeniedException("User '" + requestUserName + "' is not the scanner owner!");
- }
- }
- }
- // Methods that are delegated to AUTHManager
- public boolean isPermissionGranted(User user, Action action) {
- if (isSuperUser(user)) {
- return true;
- } else {
- return accessController.isAccessAllowed(user, action);
- }
- }
- public boolean isPermissionGranted(User user, byte[] tableName, Action action) {
- if (isSuperUser(user)) {
- return true;
- } else {
- return accessController.isAccessAllowed(user, tableName, action);
- }
- }
- public boolean isPermissionGranted(User user, byte[] tableName, byte[] colf, Action action) {
- if (isSuperUser(user)) {
- return true;
- } else {
- return accessController.isAccessAllowed(user, tableName, colf, WILDCARD_MATCH, action);
- }
- }
- public boolean isPermissionGranted(User user, byte[] tableName, byte[] colf, byte[] col, Action action) {
- if (isSuperUser(user)) {
- return true;
- } else {
- return accessController.isAccessAllowed(user, tableName, colf, col, action);
- }
- }
- // Methods that are internally used by co-processors
- @SuppressWarnings("unchecked")
- public void requirePermission(String request, Action action, RegionCoprocessorEnvironment rEnv, Map<byte[], ? extends Collection<?>> families) throws IOException {
- HRegionInfo hri = rEnv.getRegion().getRegionInfo();
- byte[] tableName = hri.getTable().getName() ;
- String tableNameStr = Bytes.toString(tableName);
- if (hri.isMetaTable() || hri.isMetaRegion()) {
- if (action == TablePermission.Action.READ) {
- return;
- }
- }
- User user = getActiveUser();
- if (user == null) {
- throw new AccessDeniedException("No user associated with request (" + request + ") for action: " + action + "on table:" + tableName);
- }
- if (isSuperUser(user)) {
- return;
- }
- if (action == TablePermission.Action.WRITE && (hri.isMetaTable() || hri.isMetaRegion()) && (isPermissionGranted(user, Permission.Action.CREATE) || isPermissionGranted(user, Permission.Action.ADMIN))) {
- return;
- }
- if (isPermissionGranted(user, tableName, (byte[]) null, action)) {
- return;
- }
- if (families != null && families.size() > 0) {
- // all families must pass
- for (Map.Entry<byte[], ? extends Collection<?>> family : families.entrySet()) {
- // a) check for family level access
- if (isPermissionGranted(user, tableName, family.getKey(), action)) {
- continue; // family-level permission overrides per-qualifier
- }
- // b) qualifier level access can still succeed
- if ((family.getValue() != null) && (family.getValue().size() > 0)) {
- if (family.getValue() instanceof Set) { // Set<byte[]> - Set
- // of Columns
- // for each qualifier of the family
- Set<byte[]> qualifierSet = (Set<byte[]>) family.getValue();
- for (byte[] qualifier : qualifierSet) {
- if (!isPermissionGranted(user, tableName, family.getKey(), qualifier, action)) {
- if (accessController.isAudited(tableName)) {
- auditEvent(request, tableName, family.getKey(), qualifier, null, null, user, accessDeniedFlag);
- }
- throw new AccessDeniedException("Insufficient permissions for user '" + user + "',action: " + action + ", tableName:" + tableNameStr + ", family:" + Bytes.toString(family.getKey()) + ",column: " + Bytes.toString(qualifier));
- }
- }
- } else if (family.getValue() instanceof List) { // List<KeyValue>
- // - List of
- // KeyValue
- // pair
- List<KeyValue> kvList = (List<KeyValue>) family.getValue();
- for (KeyValue kv : kvList) {
- if (!isPermissionGranted(user, tableName, family.getKey(), kv.getQualifier(), action)) {
- if (accessController.isAudited(tableName)) {
- auditEvent(request, tableName, family.getKey(), kv.getQualifier(), null, null, user, accessDeniedFlag);
- }
- throw new AccessDeniedException("Insufficient permissions for user '" + user + "',action: " + action + ", tableName:" + tableNameStr + ", family:" + Bytes.toString(family.getKey()) + ",column: " + Bytes.toString(kv.getQualifier()));
- }
- }
- }
- } else {
- if (accessController.isAudited(tableName)) {
- auditEvent(request, tableName, family.getKey(), null, null, null, user, accessDeniedFlag);
- }
- throw new AccessDeniedException("Insufficient permissions for user '" + user + "',action: " + action + ", tableName:" + tableNameStr + ", family:" + Bytes.toString(family.getKey()) + ", no columns found.");
- }
- }
- return;
- }
- if (accessController.isAudited(tableName)) {
- auditEvent(request, tableName, null, null, null, null, user, accessDeniedFlag);
- }
- throw new AccessDeniedException("Insufficient permissions for user '" + user + "',action: " + action + ", tableName:" + tableNameStr);
- }
- // Check if the user has global permission ...
- protected void requireGlobalPermission(String request, String objName, Permission.Action action) throws AccessDeniedException {
- User user = getActiveUser();
- if (!isPermissionGranted(user, action)) {
- if (accessController.isAudited(WILDCARD_MATCH)) {
- auditEvent(request, objName, null, null, null, null, user, accessDeniedFlag);
- }
- throw new AccessDeniedException("Insufficient permissions for user '" + getActiveUser() + "' (global, action=" + action + ")");
- }
- }
- protected void requirePermission(String request, byte[] tableName, Permission.Action action) throws AccessDeniedException {
- User user = getActiveUser();
- if (!isPermissionGranted(user, tableName, action)) {
- if (accessController.isAudited(tableName)) {
- auditEvent(request, tableName, null, null, null, null, user, accessDeniedFlag);
- }
- throw new AccessDeniedException("Insufficient permissions for user '" + getActiveUser() + "' (global, action=" + action + ")");
- }
- }
- protected void requirePermission(String request, byte[] aTableName, byte[] aColumnFamily, byte[] aQualifier, Permission.Action... actions) throws AccessDeniedException {
- User user = getActiveUser();
- boolean isAllowed = false;
-
- for (Action action : actions) {
- isAllowed = isPermissionGranted(user, aTableName, aColumnFamily, aQualifier, action);
-
- if(isAllowed) {
- break;
- }
- }
-
- if (!isAllowed) {
- if (accessController.isAudited(aTableName)) {
- auditEvent(request, aTableName, aColumnFamily, aQualifier, null, null, user, accessDeniedFlag);
- }
- Permission.Action deniedAction = actions.length > 0 ? actions[0] : null;
-
- throw new AccessDeniedException("Insufficient permissions for user '" + user + "',action: " + deniedAction + ", tableName:" + Bytes.toString(aTableName) + ", family:" + Bytes.toString(aColumnFamily) + ",column: " + Bytes.toString(aQualifier));
- }
- }
- protected void requirePermission(String request, Permission.Action perm, RegionCoprocessorEnvironment env, Collection<byte[]> families) throws IOException {
- HashMap<byte[], Set<byte[]>> familyMap = new HashMap<byte[], Set<byte[]>>();
-
- if(families != null) {
- for (byte[] family : families) {
- familyMap.put(family, null);
- }
- }
- requirePermission(request, perm, env, familyMap);
- }
- protected boolean isPermissionGranted(String request, User requestUser, Permission.Action perm, RegionCoprocessorEnvironment env, Map<byte[], NavigableSet<byte[]>> familyMap) {
- boolean ret = true;
- try {
- requirePermission(request, perm, env, familyMap);
- } catch (Throwable t) {
- ret = false;
- }
- return ret;
- }
- protected boolean hasFamilyQualifierPermission(User requestUser, Permission.Action perm, RegionCoprocessorEnvironment env, Map<byte[], NavigableSet<byte[]>> familyMap) {
- User user = requestUser;
- byte[] tableName = getTableName(env);
- if (familyMap != null && familyMap.size() > 0) {
- for (Map.Entry<byte[], NavigableSet<byte[]>> family : familyMap.entrySet()) {
- if (family.getValue() != null && !family.getValue().isEmpty()) {
- for (byte[] qualifier : family.getValue()) {
- boolean isGranted = isPermissionGranted(user, tableName, family.getKey(), qualifier, perm);
- LOG.info(":=> hasFamilyQualifierPermission: T(" + Bytes.toString(tableName) + "), family: (" + Bytes.toString(family.getKey() ) + "), Q(" + Bytes.toString(qualifier) + "), Permission: [" + perm + "] => [" + isGranted + "]") ;
- if (isGranted) {
- return true;
- }
- }
- } else {
- boolean isGranted = isPermissionGranted(user, tableName, family.getKey(), perm);
- LOG.info(":=> hasFamilyPermission: T(" + Bytes.toString(tableName) + "), family: (" + Bytes.toString(family.getKey() ) + ", Permission: [" + perm + "] => [" + isGranted + "]") ;
- if (isGranted) {
- return true;
- }
- }
- }
- } else {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Empty family map passed for permission check");
- }
- }
- return false;
- }
-
-
- public void checkPermissions(Permission[] permissions) throws IOException {
- String tableName = regionEnv.getRegion().getTableDesc().getTableName().getNameAsString() ;
- for (Permission permission : permissions) {
- if (permission instanceof TablePermission) {
- TablePermission tperm = (TablePermission) permission;
- for (Permission.Action action : permission.getActions()) {
- if (! tperm.getTableName().getNameAsString().equals(tableName)) {
- throw new AccessDeniedException(String.format("This method can only execute at the table specified in TablePermission. " + "Table of the region:%s , requested table:%s", tableName,
- tperm.getTableName().getNameAsString()));
- }
- HashMap<byte[], Set<byte[]>> familyMap = Maps.newHashMapWithExpectedSize(1);
- if (tperm.getFamily() != null) {
- if (tperm.getQualifier() != null) {
- familyMap.put(tperm.getFamily(), Sets.newHashSet(tperm.getQualifier()));
- } else {
- familyMap.put(tperm.getFamily(), null);
- }
- }
- requirePermission("checkPermissions", action, regionEnv, familyMap);
- }
- } else {
- for (Permission.Action action : permission.getActions()) {
- byte[] tname = regionEnv.getRegion().getTableDesc().getTableName().getName() ;
- requirePermission("checkPermissions", tname, action);
- }
- }
- }
- }
-
- @Override
- public void postAddColumn(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName, HColumnDescriptor column) throws IOException {
- auditEvent("addColumn", tableName.getName(), column.getName(), null, null, null, getActiveUser(), accessGrantedFlag);
- }
- @Override
- public void postAssign(ObserverContext<MasterCoprocessorEnvironment> c, HRegionInfo regionInfo) throws IOException {
- auditEvent("assign", regionInfo.getTable().getNameAsString(), null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- @Override
- public void postBalance(ObserverContext<MasterCoprocessorEnvironment> c,List<RegionPlan> aRegPlanList) throws IOException {
- auditEvent("balance", (String) null, null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- @Override
- public void postBalanceSwitch(ObserverContext<MasterCoprocessorEnvironment> c, boolean oldValue, boolean newValue) throws IOException {
- auditEvent("balanceSwitch", (String) null, null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- @Override
- public void postCloneSnapshot(ObserverContext<MasterCoprocessorEnvironment> ctx, SnapshotDescription snapshot, HTableDescriptor hTableDescriptor) throws IOException {
- auditEvent("cloneSnapshot", hTableDescriptor.getNameAsString(), null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- @Override
- public void postCreateTable(ObserverContext<MasterCoprocessorEnvironment> ctx, HTableDescriptor desc, HRegionInfo[] regions) throws IOException {
- auditEvent("createTable", desc.getNameAsString(), null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- @Override
- public void postDelete(ObserverContext<RegionCoprocessorEnvironment> c, Delete delete, WALEdit edit, Durability durability) throws IOException {
- auditEvent("delete", delete.toString(), null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- @Override
- public void postDeleteColumn(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName, byte[] col) throws IOException {
- auditEvent("deleteColumn", tableName.getName(), col, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- @Override
- public void postDeleteSnapshot(ObserverContext<MasterCoprocessorEnvironment> ctx, SnapshotDescription snapshot) throws IOException {
- auditEvent("deleteSnapShot", (String) null, null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- @Override
- public void postDeleteTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName) throws IOException {
- auditEvent("deleteTable", tableName.getName(), null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- @Override
- public void postDisableTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName) throws IOException {
- auditEvent("disableTable", tableName.getName(), null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- @Override
- public void postEnableTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName) throws IOException {
- auditEvent("enableTable", tableName.getName(), null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- @Override
- public void postModifyColumn(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName, HColumnDescriptor descriptor) throws IOException {
- auditEvent("modifyColumn", tableName.getName(), descriptor.getName(), null, null, null, getActiveUser(), accessGrantedFlag);
- }
- @Override
- public void postModifyTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName, HTableDescriptor htd) throws IOException {
- auditEvent("modifyTable", tableName.getName(), null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- @Override
- public void postMove(ObserverContext<MasterCoprocessorEnvironment> c, HRegionInfo region, ServerName srcServer, ServerName destServer) throws IOException {
- auditEvent("move", region.getTable().getName(), null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- @Override
- public void postOpen(ObserverContext<RegionCoprocessorEnvironment> ctx) {
- auditEvent("open", (String) null, null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- @Override
- public void postRestoreSnapshot(ObserverContext<MasterCoprocessorEnvironment> ctx, SnapshotDescription snapshot, HTableDescriptor hTableDescriptor) throws IOException {
- auditEvent("restoreSnapshot", (String) null, null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- @Override
- public void postScannerClose(ObserverContext<RegionCoprocessorEnvironment> c, InternalScanner s) throws IOException {
- try {
- scannerOwners.remove(s);
- } finally {
- byte[] tableName = getTableName(c.getEnvironment());
-
- if (!isSpecialTable(tableName)) {
- auditEvent("scannerClose", tableName, null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- }
- }
- @Override
- public RegionScanner postScannerOpen(ObserverContext<RegionCoprocessorEnvironment> c, Scan scan, RegionScanner s) throws IOException {
- try {
- User user = getActiveUser();
- if (user != null && user.getShortName() != null) {
- scannerOwners.put(s, user.getShortName());
- }
- } finally {
- byte[] tableName = getTableName(c.getEnvironment());
-
- if (!isSpecialTable(tableName)) {
- auditEvent("scannerOpen", tableName, null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- }
- return s;
- }
- @Override
- public void postSnapshot(ObserverContext<MasterCoprocessorEnvironment> ctx, SnapshotDescription snapshot, HTableDescriptor hTableDescriptor) throws IOException {
- auditEvent("snapshot", hTableDescriptor.getNameAsString(), null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- @Override
- public void postStartMaster(ObserverContext<MasterCoprocessorEnvironment> ctx) throws IOException {
- if(UpdateXaPoliciesOnGrantRevoke) {
- XaAccessControlLists.init(ctx.getEnvironment().getMasterServices());
- }
-
- auditEvent("startMaster", (String) null, null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- @Override
- public void postUnassign(ObserverContext<MasterCoprocessorEnvironment> c, HRegionInfo regionInfo, boolean force) throws IOException {
- auditEvent("unassign", regionInfo.getTable().getName(), null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- @Override
- public void preAddColumn(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName, HColumnDescriptor column) throws IOException {
- requirePermission("addColumn", tableName.getName(), null, null, Action.ADMIN, Action.CREATE);
- }
- @Override
- public Result preAppend(ObserverContext<RegionCoprocessorEnvironment> c, Append append) throws IOException {
- requirePermission("append", TablePermission.Action.WRITE, c.getEnvironment(), append.getFamilyCellMap());
- return null;
- }
- @Override
- public void preAssign(ObserverContext<MasterCoprocessorEnvironment> c, HRegionInfo regionInfo) throws IOException {
- requirePermission("assign", regionInfo.getTable().getName(), null, null, Action.ADMIN);
- }
- @Override
- public void preBalance(ObserverContext<MasterCoprocessorEnvironment> c) throws IOException {
- requirePermission("balance", null, Permission.Action.ADMIN);
- }
- @Override
- public boolean preBalanceSwitch(ObserverContext<MasterCoprocessorEnvironment> c, boolean newValue) throws IOException {
- requirePermission("balanceSwitch", null, Permission.Action.ADMIN);
- return newValue;
- }
- @Override
- public void preBulkLoadHFile(ObserverContext<RegionCoprocessorEnvironment> ctx, List<Pair<byte[], String>> familyPaths) throws IOException {
- List<byte[]> cfs = new LinkedList<byte[]>();
- for (Pair<byte[], String> el : familyPaths) {
- cfs.add(el.getFirst());
- }
- requirePermission("bulkLoadHFile", Permission.Action.WRITE, ctx.getEnvironment(), cfs);
- }
- @Override
- public boolean preCheckAndDelete(ObserverContext<RegionCoprocessorEnvironment> c, byte[] row, byte[] family, byte[] qualifier, CompareOp compareOp, ByteArrayComparable comparator, Delete delete, boolean result) throws IOException {
- Collection<byte[]> familyMap = Arrays.asList(new byte[][] { family });
- requirePermission("checkAndDelete", TablePermission.Action.READ, c.getEnvironment(), familyMap);
- requirePermission("checkAndDelete", TablePermission.Action.WRITE, c.getEnvironment(), familyMap);
- return result;
- }
- @Override
- public boolean preCheckAndPut(ObserverContext<RegionCoprocessorEnvironment> c, byte[] row, byte[] family, byte[] qualifier, CompareOp compareOp, ByteArrayComparable comparator, Put put, boolean result) throws IOException {
- Collection<byte[]> familyMap = Arrays.asList(new byte[][] { family });
- requirePermission("checkAndPut", TablePermission.Action.READ, c.getEnvironment(), familyMap);
- requirePermission("checkAndPut", TablePermission.Action.WRITE, c.getEnvironment(), familyMap);
- return result;
- }
- @Override
- public void preCloneSnapshot(ObserverContext<MasterCoprocessorEnvironment> ctx, SnapshotDescription snapshot, HTableDescriptor hTableDescriptor) throws IOException {
- requirePermission("cloneSnapshot", null, Permission.Action.ADMIN);
- }
- @Override
- public void preClose(ObserverContext<RegionCoprocessorEnvironment> e, boolean abortRequested) throws IOException {
- requirePermission("close", getTableName(e.getEnvironment()), Permission.Action.ADMIN);
- }
- @Override
- public InternalScanner preCompact(ObserverContext<RegionCoprocessorEnvironment> e, Store store, InternalScanner scanner,ScanType scanType) throws IOException {
- requirePermission("compact", getTableName(e.getEnvironment()), null, null, Action.ADMIN, Action.CREATE);
- return scanner;
- }
- @Override
- public void preCompactSelection(ObserverContext<RegionCoprocessorEnvironment> e, Store store, List<StoreFile> candidates) throws IOException {
- requirePermission("compactSelection", getTableName(e.getEnvironment()), null, null, Action.ADMIN, Action.CREATE);
- }
-
- @Override
- public void preCreateTable(ObserverContext<MasterCoprocessorEnvironment> c, HTableDescriptor desc, HRegionInfo[] regions) throws IOException {
- requirePermission("createTable", desc.getName(), Permission.Action.CREATE);
- }
- @Override
- public void preDelete(ObserverContext<RegionCoprocessorEnvironment> c, Delete delete, WALEdit edit, Durability durability) throws IOException {
- requirePermission("delete", TablePermission.Action.WRITE, c.getEnvironment(), delete.getFamilyCellMap());
- }
- @Override
- public void preDeleteColumn(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName, byte[] col) throws IOException {
- requirePermission("deleteColumn", tableName.getName(), null, null, Action.ADMIN, Action.CREATE);
- }
- @Override
- public void preDeleteSnapshot(ObserverContext<MasterCoprocessorEnvironment> ctx, SnapshotDescription snapshot) throws IOException {
- requirePermission("deleteSnapshot", null, Permission.Action.ADMIN);
- }
- @Override
- public void preDeleteTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName) throws IOException {
- requirePermission("deleteTable", tableName.getName(), null, null, Action.ADMIN, Action.CREATE);
- }
- @Override
- public void preDisableTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName) throws IOException {
- requirePermission("disableTable", tableName.getName(), null, null, Action.ADMIN, Action.CREATE);
- }
- @Override
- public void preEnableTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName) throws IOException {
- requirePermission("enableTable", tableName.getName(), null, null, Action.ADMIN, Action.CREATE);
- }
- @Override
- public boolean preExists(ObserverContext<RegionCoprocessorEnvironment> c, Get get, boolean exists) throws IOException {
- requirePermission("exists", TablePermission.Action.READ, c.getEnvironment(), get.familySet());
- return exists;
- }
- @Override
- public void preFlush(ObserverContext<RegionCoprocessorEnvironment> e) throws IOException {
- requirePermission("flush", getTableName(e.getEnvironment()), null, null, Action.ADMIN, Action.CREATE);
- }
- @Override
- public void preGetClosestRowBefore(ObserverContext<RegionCoprocessorEnvironment> c, byte[] row, byte[] family, Result result) throws IOException {
- requirePermission("getClosestRowBefore", TablePermission.Action.READ, c.getEnvironment(), (family != null ? Lists.newArrayList(family) : null));
- }
- @Override
- public Result preIncrement(ObserverContext<RegionCoprocessorEnvironment> c, Increment increment) throws IOException {
- requirePermission("increment", TablePermission.Action.WRITE, c.getEnvironment(), increment.getFamilyCellMap().keySet());
-
- return null;
- }
- @Override
- public long preIncrementColumnValue(ObserverContext<RegionCoprocessorEnvironment> c, byte[] row, byte[] family, byte[] qualifier, long amount, boolean writeToWAL) throws IOException {
- requirePermission("incrementColumnValue", TablePermission.Action.READ, c.getEnvironment(), Arrays.asList(new byte[][] { family }));
- requirePermission("incrementColumnValue", TablePermission.Action.WRITE, c.getEnvironment(), Arrays.asList(new byte[][] { family }));
- return -1;
- }
- @Override
- public void preModifyColumn(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName, HColumnDescriptor descriptor) throws IOException {
- requirePermission("modifyColumn", tableName.getName(), null, null, Action.ADMIN, Action.CREATE);
- }
- @Override
- public void preModifyTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName, HTableDescriptor htd) throws IOException {
- requirePermission("modifyTable", tableName.getName(), null, null, Action.ADMIN, Action.CREATE);
- }
- @Override
- public void preMove(ObserverContext<MasterCoprocessorEnvironment> c, HRegionInfo region, ServerName srcServer, ServerName destServer) throws IOException {
- requirePermission("move", region.getTable().getName() , null, null, Action.ADMIN);
- }
- @Override
- public void preOpen(ObserverContext<RegionCoprocessorEnvironment> e) throws IOException {
- RegionCoprocessorEnvironment env = e.getEnvironment();
- final HRegion region = env.getRegion();
- if (region == null) {
- LOG.error("NULL region from RegionCoprocessorEnvironment in preOpen()");
- return;
- } else {
- HRegionInfo regionInfo = region.getRegionInfo();
- if (isSpecialTable(regionInfo)) {
- isSystemOrSuperUser(regionEnv.getConfiguration());
- } else {
- requirePermission("open", getTableName(e.getEnvironment()), Action.ADMIN);
- }
- }
- }
- @Override
- public void preRestoreSnapshot(ObserverContext<MasterCoprocessorEnvironment> ctx, SnapshotDescription snapshot, HTableDescriptor hTableDescriptor) throws IOException {
- requirePermission("restoreSnapshot", hTableDescriptor.getName(), Permission.Action.ADMIN);
- }
-
- @Override
- public void preScannerClose(ObserverContext<RegionCoprocessorEnvironment> c, InternalScanner s) throws IOException {
- requireScannerOwner(s);
- }
- @Override
- public boolean preScannerNext(ObserverContext<RegionCoprocessorEnvironment> c, InternalScanner s, List<Result> result, int limit, boolean hasNext) throws IOException {
- requireScannerOwner(s);
- return hasNext;
- }
- @Override
- public RegionScanner preScannerOpen(ObserverContext<RegionCoprocessorEnvironment> c, Scan scan, RegionScanner s) throws IOException {
- RegionCoprocessorEnvironment e = c.getEnvironment();
- User user = getActiveUser();
- boolean isGranted = isPermissionGranted("scannerOpen", user, TablePermission.Action.READ, e, scan.getFamilyMap());
- if (!isGranted) {
- if (hasFamilyQualifierPermission(user, TablePermission.Action.READ, e, scan.getFamilyMap())) {
- byte[] table = getTableName(e);
- XaSecureAccessControlFilter filter = new XaSecureAccessControlFilter(user, table);
- if (scan.hasFilter()) {
- FilterList wrapper = new FilterList(FilterList.Operator.MUST_PASS_ALL, Lists.newArrayList(filter, scan.getFilter()));
- scan.setFilter(wrapper);
- } else {
- scan.setFilter(filter);
- }
- } else {
- throw new AccessDeniedException("Insufficient permissions for user '" + (user != null ? user.getShortName() : "null") + "' for scanner open on table " + Bytes.toString(getTableName(e)));
- }
- }
- return s;
- }
- @Override
- public void preShutdown(ObserverContext<MasterCoprocessorEnvironment> c) throws IOException {
- requirePermission("shutdown", null, Permission.Action.ADMIN);
- }
- @Override
- public void preSnapshot(ObserverContext<MasterCoprocessorEnvironment> ctx, SnapshotDescription snapshot, HTableDescriptor hTableDescriptor) throws IOException {
- requirePermission("snapshot", hTableDescriptor.getName(), Permission.Action.ADMIN);
- }
- @Override
- public void preSplit(ObserverContext<RegionCoprocessorEnvironment> e) throws IOException {
- requirePermission("split", getTableName(e.getEnvironment()), null, null, Action.ADMIN);
- }
- @Override
- public void preStopMaster(ObserverContext<MasterCoprocessorEnvironment> c) throws IOException {
- requirePermission("stopMaster", null, Permission.Action.ADMIN);
- }
- @Override
- public void preStopRegionServer(ObserverContext<RegionServerCoprocessorEnvironment> env) throws IOException {
- requirePermission("stop", null, Permission.Action.ADMIN);
- }
- @Override
- public void preUnassign(ObserverContext<MasterCoprocessorEnvironment> c, HRegionInfo regionInfo, boolean force) throws IOException {
- requirePermission("unassign", regionInfo.getTable().getName(), null, null, Action.ADMIN);
- }
- private String coprocessorType = "unknown";
- private static final String MASTER_COPROCESSOR_TYPE = "master";
- private static final String REGIONAL_COPROCESSOR_TYPE = "regional";
- private static final String REGIONAL_SERVER_COPROCESSOR_TYPE = "regionalServer";
- @Override
- public void start(CoprocessorEnvironment env) throws IOException {
- AuditProviderFactory.ApplicationType appType = AuditProviderFactory.ApplicationType.Unknown;
-
- if (env instanceof MasterCoprocessorEnvironment) {
- coprocessorType = MASTER_COPROCESSOR_TYPE;
- appType = AuditProviderFactory.ApplicationType.HBaseMaster;
- } else if (env instanceof RegionServerCoprocessorEnvironment) {
- coprocessorType = REGIONAL_SERVER_COPROCESSOR_TYPE;
- appType = AuditProviderFactory.ApplicationType.HBaseRegionalServer;
- } else if (env instanceof RegionCoprocessorEnvironment) {
- regionEnv = (RegionCoprocessorEnvironment) env;
- coprocessorType = REGIONAL_COPROCESSOR_TYPE;
- appType = AuditProviderFactory.ApplicationType.HBaseRegionalServer;
- }
-
- XaSecureConfiguration.getInstance().initAudit(appType);
-
- if (superUserList == null) {
- superUserList = new ArrayList<String>();
- Configuration conf = env.getConfiguration();
- String[] users = conf.getStrings(SUPERUSER_CONFIG_PROP);
- if (users != null) {
- for (String user : users) {
- user = user.trim();
- LOG.info("Start() - Adding Super User(" + user + ")");
- superUserList.add(user);
- }
- }
- }
- if (LOG.isDebugEnabled()) {
- LOG.debug("Start of Coprocessor: [" + coprocessorType + "] with superUserList [" + superUserList + "]");
- }
- }
- @Override
- public void stop(CoprocessorEnvironment env) {
- }
- @Override
- public void prePut(ObserverContext<RegionCoprocessorEnvironment> c, Put put, WALEdit edit, Durability durability) throws IOException {
- requirePermission("put", TablePermission.Action.WRITE, c.getEnvironment(), put.getFamilyCellMap());
- }
-
- @Override
- public void postPut(ObserverContext<RegionCoprocessorEnvironment> c, Put put, WALEdit edit, Durability durability) {
- byte[] tableName = getTableName(c.getEnvironment());
- if (!isSpecialTable(tableName)) {
- if (accessController.isAudited(tableName)) {
- Map<byte[], List<Cell>> colf2KeyValMap = put.getFamilyCellMap() ;
- for (byte[] colf : colf2KeyValMap.keySet()) {
- if (colf != null) {
- List<Cell> kvList = colf2KeyValMap.get(colf);
- for (Cell kv : kvList) {
- auditEvent("Put", tableName, CellUtil.cloneFamily(kv), CellUtil.cloneQualifier(kv) , CellUtil.cloneRow(kv), CellUtil.cloneValue(kv), getActiveUser(), accessGrantedFlag);
- }
- }
- }
-
-
- }
- }
- }
-
- @Override
- public void preGetOp(final ObserverContext<RegionCoprocessorEnvironment> rEnv, final Get get, final List<Cell> result) throws IOException {
- RegionCoprocessorEnvironment e = rEnv.getEnvironment();
- User requestUser = getActiveUser();
-
-
- if (LOG.isDebugEnabled())
- {
- StringBuilder fields = new StringBuilder() ;
- Map<byte[], NavigableSet<byte[]>> familyMap = get.getFamilyMap() ;
- if (familyMap != null && familyMap.size() > 0) {
- for(byte[] columnfamily : familyMap.keySet() ) {
- if (columnfamily != null && columnfamily.length > 0) {
- NavigableSet<byte[]> columnNameSet = familyMap.get(columnfamily) ;
- if (columnNameSet != null && columnNameSet.size() > 0) {
- for(byte[] columnname : columnNameSet) {
- fields.append("Field[" + Bytes.toString(columnfamily) + ":" + Bytes.toString(columnname) + "],") ;
- }
- }
- else {
- fields.append("Field[" + Bytes.toString(columnfamily) + ":null],") ;
- }
- }
- }
- }
- else {
- if (familyMap == null){
- fields.append("{null}") ;
- }
- else {
- fields.append("{empty}") ;
- }
- }
- LOG.debug("preGet is checking permission for the following fields: {" + fields.toString() + "}");
- }
-
- boolean isPermGranted = isPermissionGranted("get", requestUser, TablePermission.Action.READ, e, get.getFamilyMap());
-
- if (!isPermGranted) {
- isPermGranted = hasFamilyQualifierPermission(requestUser, TablePermission.Action.READ, e, get.getFamilyMap());
- if (isPermGranted) {
- byte[] table = getTableName(e);
- XaSecureAccessControlFilter filter = new XaSecureAccessControlFilter(requestUser, table);
- if (get.getFilter() != null) {
- FilterList wrapper = new FilterList(FilterList.Operator.MUST_PASS_ALL, Lists.newArrayList(filter, get.getFilter()));
- get.setFilter(wrapper);
- } else {
- get.setFilter(filter);
- }
- } else {
- throw new AccessDeniedException("Insufficient permissions (table=" + e.getRegion().getTableDesc().getNameAsString() + ", action=READ)");
- }
- }
- }
- @Override
- public void postGetOp(final ObserverContext<RegionCoprocessorEnvironment> env, final Get get, final List<Cell> results) throws IOException {
- HRegionInfo hri = env.getEnvironment().getRegion().getRegionInfo();
-
- byte[] tableName = hri.getTable().getName() ;
-
- if (!isSpecialTable(tableName)) {
- try {
- if (accessController.isAudited(tableName)) {
- for (Cell cell : results) {
- auditEvent("Get", tableName, cell.getFamily(), cell.getQualifier(), cell.getRow(), cell.getValue(), getActiveUser(), accessGrantedFlag);
- }
- }
- } catch (Throwable t) {
- }
- }
- }
-
- @Override
- public void preRegionOffline(ObserverContext<MasterCoprocessorEnvironment> c, HRegionInfo regionInfo) throws IOException {
- requirePermission("regionOffline", regionInfo.getTable().getName(), null, null, Action.ADMIN);
- }
- @Override
- public void postRegionOffline(ObserverContext<MasterCoprocessorEnvironment> c, HRegionInfo regionInfo) throws IOException {
- auditEvent("regionOffline", regionInfo.getTable().getName(), null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- @Override
- public void preCreateNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx, NamespaceDescriptor ns) throws IOException {
- requireGlobalPermission("createNamespace", ns.getName(), Action.ADMIN);
- }
- @Override
- public void postCreateNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx, NamespaceDescriptor ns) throws IOException {
- if (accessController.isAudited(WILDCARD_MATCH)) {
- auditEvent("createNamespace", ns.getName(), null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- }
- @Override
- public void preDeleteNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx, String namespace) throws IOException {
- requireGlobalPermission("deleteNamespace", namespace, Action.ADMIN);
- }
- @Override
- public void postDeleteNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx, String namespace) throws IOException {
- if (accessController.isAudited(WILDCARD_MATCH)) {
- auditEvent("deleteNamespace", namespace, null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- }
- @Override
- public void preModifyNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx, NamespaceDescriptor ns) throws IOException {
- requireGlobalPermission("modifyNamespace", ns.getName(), Action.ADMIN);
- }
- @Override
- public void postModifyNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx, NamespaceDescriptor ns) throws IOException {
- if (accessController.isAudited(WILDCARD_MATCH)) {
- auditEvent("modifyNamespace", ns.getName(), null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- }
- @Override
- public void preGetTableDescriptors(ObserverContext<MasterCoprocessorEnvironment> ctx, List<TableName> tableNamesList, List<HTableDescriptor> descriptors) throws IOException {
- if (tableNamesList == null || tableNamesList.isEmpty()) { // If the list is empty, this is a request for all table descriptors and requires GLOBAL ADMIN privs.
- requireGlobalPermission("getTableDescriptors", WILDCARD, Action.ADMIN);
- } else { // Otherwise, if the requestor has ADMIN or CREATE privs for all listed tables, the request can be granted.
- for (TableName tableName: tableNamesList) {
- requirePermission("getTableDescriptors", tableName.getName(), null, null, Action.ADMIN, Action.CREATE);
- }
- }
- }
- @Override
- public void postGetTableDescriptors(ObserverContext<MasterCoprocessorEnvironment> ctx, List<HTableDescriptor> descriptors) throws IOException {
- if (descriptors == null || descriptors.isEmpty()) { // If the list is empty, this is a request for all table descriptors and requires GLOBAL ADMIN privs.
- auditEvent("getTableDescriptors", WILDCARD, null, null, null, null, getActiveUser(), accessGrantedFlag);
- } else { // Otherwise, if the requestor has ADMIN or CREATE privs for all listed tables, the request can be granted.
- for (HTableDescriptor descriptor : descriptors) {
- auditEvent("getTableDescriptors", descriptor.getName(), null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
- }
- }
- @Override
- public void preMerge(ObserverContext<RegionServerCoprocessorEnvironment> ctx, HRegion regionA, HRegion regionB) throws IOException {
- requirePermission("mergeRegions", regionA.getTableDesc().getTableName().getName(), null, null, Action.ADMIN);
- }
-
- @Override
- public void postMerge(ObserverContext<RegionServerCoprocessorEnvironment> c, HRegion regionA, HRegion regionB, HRegion mergedRegion) throws IOException {
- auditEvent("mergeRegions", regionA.getTableDesc().getTableName().getName(), null, null, null, null, getActiveUser(), accessGrantedFlag);
- }
-
- public void prePrepareBulkLoad(ObserverContext<RegionCoprocessorEnvironment> ctx, PrepareBulkLoadRequest request) throws IOException {
- List<byte[]> cfs = null;
-
- requirePermission("prePrepareBulkLoad", Permission.Action.WRITE, ctx.getEnvironment(), cfs);
- }
-
- public void preCleanupBulkLoad(ObserverContext<RegionCoprocessorEnvironment> ctx, CleanupBulkLoadRequest request) throws IOException {
- List<byte[]> cfs = null;
-
- requirePermission("preCleanupBulkLoad", Permission.Action.WRITE, ctx.getEnvironment(), cfs);
- }
-
- private void auditEvent(String eventName, byte[] tableName, byte[] columnFamilyName, byte[] qualifierName, byte[] row, byte[] value, User user, short accessFlag) {
- auditEvent(eventName, Bytes.toString(tableName), Bytes.toString(columnFamilyName), Bytes.toString(qualifierName), row, value, user, accessFlag);
- }
-
- private void auditEvent(String eventName, String tableName, String columnFamilyName, String qualifierName, byte[] row, byte[] value, User user, short accessFlag) {
-
- if (tableName != null && accessController.isAudited(tableName.getBytes())) {
-
- String resourceType = "table";
- String resourceName = tableName;
- if (columnFamilyName != null && columnFamilyName.length() > 0) {
- resourceName += "/" + columnFamilyName;
- resourceType = "columnFamily";
- }
- if (qualifierName != null && qualifierName.length() > 0) {
- resourceName += "/" + qualifierName;
- resourceType = "column";
- }
-
- HBaseAuditEvent auditEvent = new HBaseAuditEvent();
-
- auditEvent.setAclEnforcer(XaSecureModuleName);
- auditEvent.setResourceType(resourceType);
- auditEvent.setResourcePath(resourceName);
- auditEvent.setAction(eventName);
- auditEvent.setAccessType(eventName);
- auditEvent.setUser(user == null ? XaSecureHadoopConstants.AUDITLOG_EMPTY_STRING : user.getShortName());
- auditEvent.setAccessResult(accessFlag);
- auditEvent.setClientIP(getRemoteAddress());
- auditEvent.setEventTime(getUTCDate());
- auditEvent.setRepositoryType(EnumRepositoryType.HBASE);
- auditEvent.setRepositoryName(repositoryName);
-
- try {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Writing audit log [" + auditEvent + "] - START.");
- }
- AuditProviderFactory.getAuditProvider().log(auditEvent);
- if (LOG.isDebugEnabled()) {
- LOG.debug("Writing audit log [" + auditEvent + "] - END.");
- }
- }
- catch(Throwable t) {
- LOG.error("ERROR during audit log [" + auditEvent + "]", t);
- }
-
- }
- }
-
- public static Date getUTCDate() {
- Calendar local=Calendar.getInstance();
- int offset = local.getTimeZone().getOffset(local.getTimeInMillis());
- GregorianCalendar utc = new GregorianCalendar(gmtTimeZone);
- utc.setTimeInMillis(local.getTimeInMillis());
- utc.add(Calendar.MILLISECOND, -offset);
- return utc.getTime();
- }
-
- @Override
- public void grant(RpcController controller, AccessControlProtos.GrantRequest request, RpcCallback<AccessControlProtos.GrantResponse> done) {
- boolean isSuccess = false;
-
- if(UpdateXaPoliciesOnGrantRevoke) {
- GrantRevokeData grData = null;
-
- try {
- grData = createGrantData(request);
-
- XaAdminRESTClient xaAdmin = new XaAdminRESTClient();
-
- xaAdmin.grantPrivilege(grData);
-
- isSuccess = true;
- } catch(IOException excp) {
- LOG.warn("grant() failed", excp);
-
- ResponseConverter.setControllerException(controller, excp);
- } catch (Exception excp) {
- LOG.warn("grant() failed", excp);
-
- ResponseConverter.setControllerException(controller, new CoprocessorException(excp.getMessage()));
- } finally {
- byte[] tableName = grData == null ? null : StringUtil.getBytes(grData.getTables());
-
- if(accessController.isAudited(tableName)) {
- byte[] colFamily = grData == null ? null : StringUtil.getBytes(grData.getColumnFamilies());
- byte[] qualifier = grData == null ? null : StringUtil.getBytes(grData.getColumns());
-
- // Note: failed return from REST call will be logged as 'DENIED'
- auditEvent("grant", tableName, colFamily, qualifier, null, null, getActiveUser(), isSuccess ? accessGrantedFlag : accessDeniedFlag);
- }
- }
- }
-
- AccessControlProtos.GrantResponse response = isSuccess ? AccessControlProtos.GrantResponse.getDefaultInstance() : null;
-
- done.run(response);
- }
-
- @Override
- public void revoke(RpcController controller, AccessControlProtos.RevokeRequest request, RpcCallback<AccessControlProtos.RevokeResponse> done) {
- boolean isSuccess = false;
-
- if(UpdateXaPoliciesOnGrantRevoke) {
- GrantRevokeData grData = null;
-
- try {
- grData = createRevokeData(request);
-
- XaAdminRESTClient xaAdmin = new XaAdminRESTClient();
-
- xaAdmin.revokePrivilege(grData);
-
- isSuccess = true;
- } catch(IOException excp) {
- LOG.warn("revoke() failed", excp);
-
- ResponseConverter.setControllerException(controller, excp);
- } catch (Exception excp) {
- LOG.warn("revoke() failed", excp);
-
- ResponseConverter.setControllerException(controller, new CoprocessorException(excp.getMessage()));
- } finally {
- byte[] tableName = grData == null ? null : StringUtil.getBytes(grData.getTables());
-
- if(accessController.isAudited(tableName)) {
- byte[] colFamily = grData == null ? null : StringUtil.getBytes(grData.getColumnFamilies());
- byte[] qualifier = grData == null ? null : StringUtil.getBytes(grData.getColumns());
-
- // Note: failed return from REST call will be logged as 'DENIED'
- auditEvent("revoke", tableName, colFamily, qualifier, null, null, getActiveUser(), isSuccess ? accessGrantedFlag : accessDeniedFlag);
- }
- }
- }
-
- AccessControlProtos.RevokeResponse response = isSuccess ? AccessControlProtos.RevokeResponse.getDefaultInstance() : null;
-
- done.run(response);
- }
-
- @Override
- public void checkPermissions(RpcController controller, AccessControlProtos.CheckPermissionsRequest request, RpcCallback<AccessControlProtos.CheckPermissionsResponse> done) {
- LOG.debug("checkPermissions(): ");
- }
-
- @Override
- public void getUserPermissions(RpcController controller, AccessControlProtos.GetUserPermissionsRequest request, RpcCallback<AccessControlProtos.GetUserPermissionsResponse> done) {
- LOG.debug("getUserPermissions(): ");
- }
-
- @Override
- public Service getService() {
- return AccessControlProtos.AccessControlService.newReflectiveService(this);
- }
-
- private GrantRevokeData createGrantData(AccessControlProtos.GrantRequest request) throws Exception {
- org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos.UserPermission up = request.getUserPermission();
- org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos.Permission perm = up == null ? null : up.getPermission();
-
- UserPermission userPerm = up == null ? null : ProtobufUtil.toUserPermission(up);
- Permission.Action[] actions = userPerm == null ? null : userPerm.getActions();
- String userName = userPerm == null ? null : Bytes.toString(userPerm.getUser());
- String tableName = null;
- String colFamily = null;
- String qualifier = null;
-
- if(perm == null) {
- throw new Exception("grant(): invalid data - permission is null");
- }
-
- if(StringUtil.isEmpty(userName)) {
- throw new Exception("grant(): invalid data - username empty");
- }
-
- if ((actions == null) || (actions.length == 0)) {
- throw new Exception("grant(): invalid data - no action specified");
- }
-
- switch(perm.getType()) {
- case Global:
- tableName = colFamily = qualifier = "*";
- break;
-
- case Table:
- tableName = Bytes.toString(userPerm.getTableName().getName());
- colFamily = Bytes.toString(userPerm.getFamily());
- qualifier = Bytes.toString(userPerm.getQualifier());
- break;
-
- case Namespace:
- default:
- LOG.warn("grant(): ignoring type '" + perm.getType().name() + "'");
- break;
- }
-
- if(StringUtil.isEmpty(tableName) && StringUtil.isEmpty(colFamily) && StringUtil.isEmpty(qualifier)) {
- throw new Exception("grant(): table/columnFamily/columnQualifier not specified");
- }
-
- PermMap permMap = new PermMap();
-
- if(userName.startsWith(GROUP_PREFIX)) {
- permMap.addGroup(userName.substring(GROUP_PREFIX.length()));
- } else {
- permMap.addUser(userName);
- }
-
- for (int i = 0; i < actions.length; i++) {
- switch(actions[i].code()) {
- case 'R':
- case 'W':
- case 'C':
- case 'A':
- permMap.addPerm(actions[i].name());
- break;
-
- default:
- LOG.warn("grant(): ignoring action '" + actions[i].name() + "' for user '" + userName + "'");
- }
- }
-
- User activeUser = getActiveUser();
- String grantor = activeUser != null ? activeUser.getShortName() : null;
-
- GrantRevokeData grData = new GrantRevokeData();
-
- grData.setHBaseData(grantor, repositoryName, tableName, qualifier, colFamily, permMap);
-
- return grData;
- }
-
- private GrantRevokeData createRevokeData(AccessControlProtos.RevokeRequest request) throws Exception {
- org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos.UserPermission up = request.getUserPermission();
- org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos.Permission perm = up == null ? null : up.getPermission();
-
- UserPermission userPerm = up == null ? null : ProtobufUtil.toUserPermission(up);
- String userName = userPerm == null ? null : Bytes.toString(userPerm.getUser());
- String tableName = null;
- String colFamily = null;
- String qualifier = null;
-
- if(perm == null) {
- throw new Exception("revoke(): invalid data - permission is null");
- }
-
- if(StringUtil.isEmpty(userName)) {
- throw new Exception("revoke(): invalid data - username empty");
- }
-
- switch(perm.getType()) {
- case Global :
- tableName = colFamily = qualifier = "*";
- break;
-
- case Table :
- tableName = Bytes.toString(userPerm.getTableName().getName());
- colFamily = Bytes.toString(userPerm.getFamily());
- qualifier = Bytes.toString(userPerm.getQualifier());
- break;
-
- case Namespace:
- default:
- LOG.warn("revoke(): ignoring type '" + perm.getType().name() + "'");
- break;
- }
-
- if(StringUtil.isEmpty(tableName) && StringUtil.isEmpty(colFamily) && StringUtil.isEmpty(qualifier)) {
- throw new Exception("revoke(): table/columnFamily/columnQualifier not specified");
- }
-
- PermMap permMap = new PermMap();
-
- if(userName.startsWith(GROUP_PREFIX)) {
- permMap.addGroup(userName.substring(GROUP_PREFIX.length()));
- } else {
- permMap.addUser(userName);
- }
-
- // revoke removes all permissions
- permMap.addPerm(Permission.Action.READ.name());
- permMap.addPerm(Permission.Action.WRITE.name());
- permMap.addPerm(Permission.Action.CREATE.name());
- permMap.addPerm(Permission.Action.ADMIN.name());
-
- User activeUser = getActiveUser();
- String grantor = activeUser != null ? activeUser.getShortName() : null;
-
- GrantRevokeData grData = new GrantRevokeData();
-
- grData.setHBaseData(grantor, repositoryName, tableName, qualifier, colFamily, permMap);
-
- return grData;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hbase-agent/src/main/java/com/xasecure/authorization/hbase/XaSecureAuthorizationCoprocessorBase.java
----------------------------------------------------------------------
diff --git a/hbase-agent/src/main/java/com/xasecure/authorization/hbase/XaSecureAuthorizationCoprocessorBase.java b/hbase-agent/src/main/java/com/xasecure/authorization/hbase/XaSecureAuthorizationCoprocessorBase.java
deleted file mode 100644
index b60a95b..0000000
--- a/hbase-agent/src/main/java/com/xasecure/authorization/hbase/XaSecureAuthorizationCoprocessorBase.java
+++ /dev/null
@@ -1,671 +0,0 @@
-/**
- *
- * 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 com.xasecure.authorization.hbase;
-
-import java.io.IOException;
-import java.util.List;
-
-import org.apache.hadoop.hbase.HColumnDescriptor;
-import org.apache.hadoop.hbase.HRegionInfo;
-import org.apache.hadoop.hbase.HTableDescriptor;
-import org.apache.hadoop.hbase.NamespaceDescriptor;
-import org.apache.hadoop.hbase.ServerName;
-import org.apache.hadoop.hbase.TableName;
-import org.apache.hadoop.hbase.client.Mutation;
-import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
-import org.apache.hadoop.hbase.coprocessor.BulkLoadObserver;
-import org.apache.hadoop.hbase.coprocessor.MasterCoprocessorEnvironment;
-import org.apache.hadoop.hbase.coprocessor.MasterObserver;
-import org.apache.hadoop.hbase.coprocessor.ObserverContext;
-import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
-import org.apache.hadoop.hbase.coprocessor.RegionServerCoprocessorEnvironment;
-import org.apache.hadoop.hbase.coprocessor.RegionServerObserver;
-import org.apache.hadoop.hbase.master.RegionPlan;
-import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
-import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.CleanupBulkLoadRequest;
-import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.PrepareBulkLoadRequest;
-import org.apache.hadoop.hbase.regionserver.HRegion;
-import org.apache.hadoop.hbase.replication.ReplicationEndpoint;
-import org.apache.hadoop.hbase.security.access.Permission;
-import org.apache.hadoop.hbase.security.access.Permission.Action;
-
-public class XaSecureAuthorizationCoprocessorBase extends BaseRegionObserver
- implements MasterObserver, RegionServerObserver, BulkLoadObserver {
-
- @Override
- public void preStopRegionServer(
- ObserverContext<RegionServerCoprocessorEnvironment> env)
- throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preMerge(
- ObserverContext<RegionServerCoprocessorEnvironment> ctx,
- HRegion regionA, HRegion regionB) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postMerge(
- ObserverContext<RegionServerCoprocessorEnvironment> c,
- HRegion regionA, HRegion regionB, HRegion mergedRegion)
- throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preMergeCommit(
- ObserverContext<RegionServerCoprocessorEnvironment> ctx,
- HRegion regionA, HRegion regionB, List<Mutation> metaEntries)
- throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postMergeCommit(
- ObserverContext<RegionServerCoprocessorEnvironment> ctx,
- HRegion regionA, HRegion regionB, HRegion mergedRegion)
- throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preRollBackMerge(
- ObserverContext<RegionServerCoprocessorEnvironment> ctx,
- HRegion regionA, HRegion regionB) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postRollBackMerge(
- ObserverContext<RegionServerCoprocessorEnvironment> ctx,
- HRegion regionA, HRegion regionB) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preCreateTable(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- HTableDescriptor desc, HRegionInfo[] regions) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postCreateTable(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- HTableDescriptor desc, HRegionInfo[] regions) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preCreateTableHandler(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- HTableDescriptor desc, HRegionInfo[] regions) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postCreateTableHandler(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- HTableDescriptor desc, HRegionInfo[] regions) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preDeleteTable(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postDeleteTable(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preDeleteTableHandler(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postDeleteTableHandler(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preModifyTable(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName, HTableDescriptor htd) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postModifyTable(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName, HTableDescriptor htd) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preModifyTableHandler(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName, HTableDescriptor htd) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postModifyTableHandler(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName, HTableDescriptor htd) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preAddColumn(ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName, HColumnDescriptor column) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postAddColumn(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName, HColumnDescriptor column) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preAddColumnHandler(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName, HColumnDescriptor column) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postAddColumnHandler(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName, HColumnDescriptor column) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preModifyColumn(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName, HColumnDescriptor descriptor)
- throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postModifyColumn(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName, HColumnDescriptor descriptor)
- throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preModifyColumnHandler(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName, HColumnDescriptor descriptor)
- throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postModifyColumnHandler(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName, HColumnDescriptor descriptor)
- throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preDeleteColumn(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName, byte[] c) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postDeleteColumn(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName, byte[] c) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preDeleteColumnHandler(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName, byte[] c) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postDeleteColumnHandler(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName, byte[] c) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preEnableTable(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postEnableTable(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preEnableTableHandler(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postEnableTableHandler(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preDisableTable(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postDisableTable(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preDisableTableHandler(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postDisableTableHandler(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- TableName tableName) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preMove(ObserverContext<MasterCoprocessorEnvironment> ctx,
- HRegionInfo region, ServerName srcServer, ServerName destServer)
- throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postMove(ObserverContext<MasterCoprocessorEnvironment> ctx,
- HRegionInfo region, ServerName srcServer, ServerName destServer)
- throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preAssign(ObserverContext<MasterCoprocessorEnvironment> ctx,
- HRegionInfo regionInfo) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postAssign(ObserverContext<MasterCoprocessorEnvironment> ctx,
- HRegionInfo regionInfo) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preUnassign(ObserverContext<MasterCoprocessorEnvironment> ctx,
- HRegionInfo regionInfo, boolean force) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postUnassign(ObserverContext<MasterCoprocessorEnvironment> ctx,
- HRegionInfo regionInfo, boolean force) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preRegionOffline(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- HRegionInfo regionInfo) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postRegionOffline(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- HRegionInfo regionInfo) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preBalance(ObserverContext<MasterCoprocessorEnvironment> ctx)
- throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postBalance(ObserverContext<MasterCoprocessorEnvironment> ctx,
- List<RegionPlan> plans) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public boolean preBalanceSwitch(
- ObserverContext<MasterCoprocessorEnvironment> ctx, boolean newValue)
- throws IOException {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public void postBalanceSwitch(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- boolean oldValue, boolean newValue) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preShutdown(ObserverContext<MasterCoprocessorEnvironment> ctx)
- throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preStopMaster(ObserverContext<MasterCoprocessorEnvironment> ctx)
- throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postStartMaster(
- ObserverContext<MasterCoprocessorEnvironment> ctx)
- throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preMasterInitialization(
- ObserverContext<MasterCoprocessorEnvironment> ctx)
- throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preSnapshot(ObserverContext<MasterCoprocessorEnvironment> ctx,
- SnapshotDescription snapshot, HTableDescriptor hTableDescriptor)
- throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postSnapshot(ObserverContext<MasterCoprocessorEnvironment> ctx,
- SnapshotDescription snapshot, HTableDescriptor hTableDescriptor)
- throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preCloneSnapshot(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- SnapshotDescription snapshot, HTableDescriptor hTableDescriptor)
- throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postCloneSnapshot(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- SnapshotDescription snapshot, HTableDescriptor hTableDescriptor)
- throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preRestoreSnapshot(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- SnapshotDescription snapshot, HTableDescriptor hTableDescriptor)
- throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postRestoreSnapshot(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- SnapshotDescription snapshot, HTableDescriptor hTableDescriptor)
- throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preDeleteSnapshot(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- SnapshotDescription snapshot) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postDeleteSnapshot(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- SnapshotDescription snapshot) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preGetTableDescriptors(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- List<TableName> tableNamesList, List<HTableDescriptor> descriptors)
- throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postGetTableDescriptors(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- List<HTableDescriptor> descriptors) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preCreateNamespace(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- NamespaceDescriptor ns) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postCreateNamespace(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- NamespaceDescriptor ns) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preDeleteNamespace(
- ObserverContext<MasterCoprocessorEnvironment> ctx, String namespace)
- throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postDeleteNamespace(
- ObserverContext<MasterCoprocessorEnvironment> ctx, String namespace)
- throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void preModifyNamespace(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- NamespaceDescriptor ns) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void postModifyNamespace(
- ObserverContext<MasterCoprocessorEnvironment> ctx,
- NamespaceDescriptor ns) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- public void preRollWALWriterRequest(ObserverContext<RegionServerCoprocessorEnvironment> ctx) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- public void postRollWALWriterRequest(ObserverContext<RegionServerCoprocessorEnvironment> ctx) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- public void preTableFlush(final ObserverContext<MasterCoprocessorEnvironment> ctx, final TableName tableName) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- public void postTableFlush(ObserverContext<MasterCoprocessorEnvironment> ctx, TableName tableName) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- public void preTruncateTableHandler(final ObserverContext<MasterCoprocessorEnvironment> ctx, TableName tableName) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- public void postTruncateTableHandler(final ObserverContext<MasterCoprocessorEnvironment> ctx, TableName tableName) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- public void preTruncateTable(final ObserverContext<MasterCoprocessorEnvironment> ctx, TableName tableName) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- public void postTruncateTable(final ObserverContext<MasterCoprocessorEnvironment> ctx, TableName tableName) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- public ReplicationEndpoint postCreateReplicationEndPoint(ObserverContext<RegionServerCoprocessorEnvironment> ctx, ReplicationEndpoint endpoint) {
- return endpoint;
- }
-
- public void prePrepareBulkLoad(ObserverContext<RegionCoprocessorEnvironment> ctx, PrepareBulkLoadRequest request) throws IOException {
- }
-
- public void preCleanupBulkLoad(ObserverContext<RegionCoprocessorEnvironment> ctx, CleanupBulkLoadRequest request) throws IOException {
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hbase-agent/src/main/java/org/apache/hadoop/hbase/security/access/RangerAccessControlLists.java
----------------------------------------------------------------------
diff --git a/hbase-agent/src/main/java/org/apache/hadoop/hbase/security/access/RangerAccessControlLists.java b/hbase-agent/src/main/java/org/apache/hadoop/hbase/security/access/RangerAccessControlLists.java
new file mode 100644
index 0000000..7f33b15
--- /dev/null
+++ b/hbase-agent/src/main/java/org/apache/hadoop/hbase/security/access/RangerAccessControlLists.java
@@ -0,0 +1,104 @@
+/**
+ *
+ * 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.hadoop.hbase.security.access;
+
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+
+import org.apache.hadoop.hbase.TableExistsException;
+import org.apache.hadoop.hbase.master.MasterServices;
+import org.apache.log4j.Logger;
+
+
+public class RangerAccessControlLists {
+
+ private static final Logger LOG = Logger.getLogger(RangerAccessControlLists.class) ;
+
+ public static void init(MasterServices master) throws IOException {
+
+ Class<AccessControlLists> accessControlListsClass = AccessControlLists.class ;
+ String cName = accessControlListsClass.getName() ;
+
+ Class<?>[] params = new Class[1] ;
+ params[0] = MasterServices.class ;
+
+ for (String mname : new String[] { "init", "createACLTable" } ) {
+ try {
+ try {
+ Method m = accessControlListsClass.getDeclaredMethod(mname, params) ;
+ if (m != null) {
+ try {
+
+ try {
+ m.invoke(null, master) ;
+ logInfo("Execute method name [" + mname + "] in Class [" + cName + "] is successful.");
+ } catch (InvocationTargetException e) {
+ Throwable cause = e ;
+ boolean tableExistsExceptionFound = false ;
+ if (e != null) {
+ Throwable ecause = e.getTargetException() ;
+ if (ecause != null) {
+ cause = ecause ;
+ if (ecause instanceof TableExistsException) {
+ tableExistsExceptionFound = true ;
+ }
+ }
+ }
+ if (! tableExistsExceptionFound) {
+ logError("Unable to execute the method [" + mname + "] on [" + cName + "] due to exception", cause) ;
+ throw new IOException(cause) ;
+ }
+ }
+ return ;
+ } catch (IllegalArgumentException e) {
+ logError("Unable to execute method name [" + mname + "] in Class [" + cName + "].", e);
+ throw new IOException(e) ;
+ } catch (IllegalAccessException e) {
+ logError("Unable to execute method name [" + mname + "] in Class [" + cName + "].", e);
+ throw new IOException(e) ;
+ }
+ }
+ }
+ catch(NoSuchMethodException nsme) {
+ logInfo("Unable to get method name [" + mname + "] in Class [" + cName + "]. Ignoring the exception");
+ }
+ } catch (SecurityException e) {
+ logError("Unable to get method name [" + mname + "] in Class [" + cName + "].", e);
+ throw new IOException(e) ;
+ }
+ }
+ throw new IOException("Unable to initialize() [" + cName + "]") ;
+ }
+
+
+ private static void logInfo(String msg) {
+ // System.out.println(msg) ;
+ LOG.info(msg) ;
+ }
+
+ private static void logError(String msg, Throwable t) {
+// System.err.println(msg) ;
+// if (t != null) {
+// t.printStackTrace(System.err);
+// }
+ LOG.error(msg, t);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/hbase-agent/src/main/java/org/apache/hadoop/hbase/security/access/XaAccessControlLists.java
----------------------------------------------------------------------
diff --git a/hbase-agent/src/main/java/org/apache/hadoop/hbase/security/access/XaAccessControlLists.java b/hbase-agent/src/main/java/org/apache/hadoop/hbase/security/access/XaAccessControlLists.java
deleted file mode 100644
index 8313532..0000000
--- a/hbase-agent/src/main/java/org/apache/hadoop/hbase/security/access/XaAccessControlLists.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/**
- *
- * 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.hadoop.hbase.security.access;
-
-import java.io.IOException;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-
-import org.apache.hadoop.hbase.TableExistsException;
-import org.apache.hadoop.hbase.master.MasterServices;
-import org.apache.log4j.Logger;
-
-
-public class XaAccessControlLists {
-
- private static final Logger LOG = Logger.getLogger(XaAccessControlLists.class) ;
-
- public static void init(MasterServices master) throws IOException {
-
- Class<AccessControlLists> accessControlListsClass = AccessControlLists.class ;
- String cName = accessControlListsClass.getName() ;
-
- Class<?>[] params = new Class[1] ;
- params[0] = MasterServices.class ;
-
- for (String mname : new String[] { "init", "createACLTable" } ) {
- try {
- try {
- Method m = accessControlListsClass.getDeclaredMethod(mname, params) ;
- if (m != null) {
- try {
-
- try {
- m.invoke(null, master) ;
- logInfo("Execute method name [" + mname + "] in Class [" + cName + "] is successful.");
- } catch (InvocationTargetException e) {
- Throwable cause = e ;
- boolean tableExistsExceptionFound = false ;
- if (e != null) {
- Throwable ecause = e.getTargetException() ;
- if (ecause != null) {
- cause = ecause ;
- if (ecause instanceof TableExistsException) {
- tableExistsExceptionFound = true ;
- }
- }
- }
- if (! tableExistsExceptionFound) {
- logError("Unable to execute the method [" + mname + "] on [" + cName + "] due to exception", cause) ;
- throw new IOException(cause) ;
- }
- }
- return ;
- } catch (IllegalArgumentException e) {
- logError("Unable to execute method name [" + mname + "] in Class [" + cName + "].", e);
- throw new IOException(e) ;
- } catch (IllegalAccessException e) {
- logError("Unable to execute method name [" + mname + "] in Class [" + cName + "].", e);
- throw new IOException(e) ;
- }
- }
- }
- catch(NoSuchMethodException nsme) {
- logInfo("Unable to get method name [" + mname + "] in Class [" + cName + "]. Ignoring the exception");
- }
- } catch (SecurityException e) {
- logError("Unable to get method name [" + mname + "] in Class [" + cName + "].", e);
- throw new IOException(e) ;
- }
- }
- throw new IOException("Unable to initialize() [" + cName + "]") ;
- }
-
-
- private static void logInfo(String msg) {
- // System.out.println(msg) ;
- LOG.info(msg) ;
- }
-
- private static void logError(String msg, Throwable t) {
-// System.err.println(msg) ;
-// if (t != null) {
-// t.printStackTrace(System.err);
-// }
- LOG.error(msg, t);
- }
-
-}
[02/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/entity/XXAsset.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXAsset.java b/security-admin/src/main/java/org/apache/ranger/entity/XXAsset.java
new file mode 100644
index 0000000..f203cf6
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/entity/XXAsset.java
@@ -0,0 +1,289 @@
+/*
+ * 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.entity;
+
+/**
+ * Asset
+ *
+ */
+
+import java.util.*;
+
+import javax.persistence.*;
+import javax.xml.bind.annotation.*;
+
+import org.apache.ranger.common.*;
+import org.apache.ranger.entity.*;
+
+
+@Entity
+@Table(name="x_asset")
+@XmlRootElement
+public class XXAsset extends XXDBBase implements java.io.Serializable {
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @SequenceGenerator(name="X_ASSET_SEQ",sequenceName="X_ASSET_SEQ",allocationSize=1)
+ @GeneratedValue(strategy=GenerationType.AUTO,generator="X_ASSET_SEQ")
+ @Column(name="ID")
+ protected Long id;
+
+ @Override
+ public void setId(Long id) {
+ this.id=id;
+ }
+ @Override
+ public Long getId() {
+ return id;
+ }
+ /**
+ * Name
+ * <ul>
+ * <li>The maximum length for this attribute is <b>1024</b>.
+ * </ul>
+ *
+ */
+ @Column(name="ASSET_NAME" , nullable=false , length=1024)
+ protected String name;
+
+ /**
+ * Description
+ * <ul>
+ * <li>The maximum length for this attribute is <b>4000</b>.
+ * </ul>
+ *
+ */
+ @Column(name="DESCR" , nullable=false , length=4000)
+ protected String description;
+
+ /**
+ * Status
+ * <ul>
+ * <li>This attribute is of type enum CommonEnums::ActiveStatus
+ * </ul>
+ *
+ */
+ @Column(name="ACT_STATUS" , nullable=false )
+ protected int activeStatus = XAConstants.STATUS_DISABLED;
+
+ /**
+ * Type of asset
+ * <ul>
+ * <li>This attribute is of type enum CommonEnums::AssetType
+ * </ul>
+ *
+ */
+ @Column(name="ASSET_TYPE" , nullable=false )
+ protected int assetType = AppConstants.ASSET_UNKNOWN;
+
+ /**
+ * Config in json format
+ * <ul>
+ * <li>The maximum length for this attribute is <b>10000</b>.
+ * </ul>
+ *
+ */
+ @Column(name="CONFIG" , length=10000)
+ protected String config;
+
+ /**
+ * Support native authorization
+ * <ul>
+ * </ul>
+ *
+ */
+ @Column(name="SUP_NATIVE" , nullable=false )
+ protected boolean supportNative = false;
+
+ /**
+ * Default constructor. This will set all the attributes to default value.
+ */
+ public XXAsset ( ) {
+ activeStatus = XAConstants.STATUS_DISABLED;
+ assetType = AppConstants.ASSET_UNKNOWN;
+ }
+
+ @Override
+ public int getMyClassType( ) {
+ return AppConstants.CLASS_TYPE_XA_ASSET;
+ }
+
+ @Override
+ public String getMyDisplayValue() {
+ return getDescription( );
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>name</b>.
+ * You cannot set null to the attribute.
+ * @param name Value to set member attribute <b>name</b>
+ */
+ public void setName( String name ) {
+ this.name = name;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>name</b>
+ * @return String - value of member attribute <b>name</b>.
+ */
+ public String getName( ) {
+ return this.name;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>description</b>.
+ * You cannot set null to the attribute.
+ * @param description Value to set member attribute <b>description</b>
+ */
+ public void setDescription( String description ) {
+ this.description = description;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>description</b>
+ * @return String - value of member attribute <b>description</b>.
+ */
+ public String getDescription( ) {
+ return this.description;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>activeStatus</b>.
+ * You cannot set null to the attribute.
+ * @param activeStatus Value to set member attribute <b>activeStatus</b>
+ */
+ public void setActiveStatus( int activeStatus ) {
+ this.activeStatus = activeStatus;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>activeStatus</b>
+ * @return int - value of member attribute <b>activeStatus</b>.
+ */
+ public int getActiveStatus( ) {
+ return this.activeStatus;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>assetType</b>.
+ * You cannot set null to the attribute.
+ * @param assetType Value to set member attribute <b>assetType</b>
+ */
+ public void setAssetType( int assetType ) {
+ this.assetType = assetType;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>assetType</b>
+ * @return int - value of member attribute <b>assetType</b>.
+ */
+ public int getAssetType( ) {
+ return this.assetType;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>config</b>.
+ * You cannot set null to the attribute.
+ * @param config Value to set member attribute <b>config</b>
+ */
+ public void setConfig( String config ) {
+ this.config = config;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>config</b>
+ * @return String - value of member attribute <b>config</b>.
+ */
+ public String getConfig( ) {
+ return this.config;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>supportNative</b>.
+ * You cannot set null to the attribute.
+ * @param supportNative Value to set member attribute <b>supportNative</b>
+ */
+ public void setSupportNative( boolean supportNative ) {
+ this.supportNative = supportNative;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>supportNative</b>
+ * @return boolean - value of member attribute <b>supportNative</b>.
+ */
+ public boolean isSupportNative( ) {
+ return this.supportNative;
+ }
+
+ /**
+ * This return the bean content in string format
+ * @return formatedStr
+ */
+ @Override
+ public String toString( ) {
+ String str = "XXAsset={";
+ str += super.toString();
+ str += "name={" + name + "} ";
+ str += "description={" + description + "} ";
+ str += "activeStatus={" + activeStatus + "} ";
+ str += "assetType={" + assetType + "} ";
+ str += "config={" + config + "} ";
+ str += "supportNative={" + supportNative + "} ";
+ str += "}";
+ return str;
+ }
+
+ /**
+ * Checks for all attributes except referenced db objects
+ * @return true if all attributes match
+ */
+ @Override
+ public boolean equals( Object obj) {
+ if ( !super.equals(obj) ) {
+ return false;
+ }
+ XXAsset other = (XXAsset) obj;
+ if ((this.name == null && other.name != null) || (this.name != null && !this.name.equals(other.name))) {
+ return false;
+ }
+ if ((this.description == null && other.description != null) || (this.description != null && !this.description.equals(other.description))) {
+ return false;
+ }
+ if( this.activeStatus != other.activeStatus ) return false;
+ if( this.assetType != other.assetType ) return false;
+ if ((this.config == null && other.config != null) || (this.config != null && !this.config.equals(other.config))) {
+ return false;
+ }
+ if( this.supportNative != other.supportNative ) return false;
+ return true;
+ }
+ public static String getEnumName(String fieldName ) {
+ if( fieldName.equals("activeStatus") ) {
+ return "CommonEnums.ActiveStatus";
+ }
+ if( fieldName.equals("assetType") ) {
+ return "CommonEnums.AssetType";
+ }
+ //Later TODO
+ //return super.getEnumName(fieldName);
+ return null;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/entity/XXAuditMap.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXAuditMap.java b/security-admin/src/main/java/org/apache/ranger/entity/XXAuditMap.java
new file mode 100644
index 0000000..dd14898
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/entity/XXAuditMap.java
@@ -0,0 +1,228 @@
+/*
+ * 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.entity;
+
+/**
+ * Audi map
+ *
+ */
+
+import java.util.*;
+
+import javax.persistence.*;
+import javax.xml.bind.annotation.*;
+
+import org.apache.ranger.common.*;
+import org.apache.ranger.entity.*;
+
+
+@Entity
+@Table(name="x_audit_map")
+@XmlRootElement
+public class XXAuditMap extends XXDBBase implements java.io.Serializable {
+ private static final long serialVersionUID = 1L;
+
+
+ @Id
+ @SequenceGenerator(name="X_AUDIT_MAP_SEQ",sequenceName="X_AUDIT_MAP_SEQ",allocationSize=1)
+ @GeneratedValue(strategy=GenerationType.AUTO,generator="X_AUDIT_MAP_SEQ")
+ @Column(name="ID")
+ protected Long id;
+ @Override
+ public void setId(Long id) {
+ this.id=id;
+ }
+
+ @Override
+ public Long getId() {
+ return id;
+ }
+
+ /**
+ * Id of the resource
+ * <ul>
+ * </ul>
+ *
+ */
+ @Column(name="RES_ID" )
+ protected Long resourceId;
+
+
+ /**
+ * Id of the group
+ * <ul>
+ * </ul>
+ *
+ */
+ @Column(name="GROUP_ID" )
+ protected Long groupId;
+
+
+ /**
+ * Id of the user
+ * <ul>
+ * </ul>
+ *
+ */
+ @Column(name="USER_ID" )
+ protected Long userId;
+
+
+ /**
+ * Type of audit
+ * <ul>
+ * <li>This attribute is of type enum CommonEnums::XAAuditType
+ * </ul>
+ *
+ */
+ @Column(name="AUDIT_TYPE" , nullable=false )
+ protected int auditType = AppConstants.XA_AUDIT_TYPE_UNKNOWN;
+
+ /**
+ * Default constructor. This will set all the attributes to default value.
+ */
+ public XXAuditMap ( ) {
+ auditType = AppConstants.XA_AUDIT_TYPE_UNKNOWN;
+ }
+
+ @Override
+ public int getMyClassType( ) {
+ return AppConstants.CLASS_TYPE_XA_AUDIT_MAP;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>resourceId</b>.
+ * You cannot set null to the attribute.
+ * @param resourceId Value to set member attribute <b>resourceId</b>
+ */
+ public void setResourceId( Long resourceId ) {
+ this.resourceId = resourceId;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>resourceId</b>
+ * @return Long - value of member attribute <b>resourceId</b>.
+ */
+ public Long getResourceId( ) {
+ return this.resourceId;
+ }
+
+
+ /**
+ * This method sets the value to the member attribute <b>groupId</b>.
+ * You cannot set null to the attribute.
+ * @param groupId Value to set member attribute <b>groupId</b>
+ */
+ public void setGroupId( Long groupId ) {
+ this.groupId = groupId;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>groupId</b>
+ * @return Long - value of member attribute <b>groupId</b>.
+ */
+ public Long getGroupId( ) {
+ return this.groupId;
+ }
+
+
+ /**
+ * This method sets the value to the member attribute <b>userId</b>.
+ * You cannot set null to the attribute.
+ * @param userId Value to set member attribute <b>userId</b>
+ */
+ public void setUserId( Long userId ) {
+ this.userId = userId;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>userId</b>
+ * @return Long - value of member attribute <b>userId</b>.
+ */
+ public Long getUserId( ) {
+ return this.userId;
+ }
+
+
+ /**
+ * This method sets the value to the member attribute <b>auditType</b>.
+ * You cannot set null to the attribute.
+ * @param auditType Value to set member attribute <b>auditType</b>
+ */
+ public void setAuditType( int auditType ) {
+ this.auditType = auditType;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>auditType</b>
+ * @return int - value of member attribute <b>auditType</b>.
+ */
+ public int getAuditType( ) {
+ return this.auditType;
+ }
+
+ /**
+ * This return the bean content in string format
+ * @return formatedStr
+ */
+ @Override
+ public String toString( ) {
+ String str = "XXAuditMap={";
+ str += super.toString();
+ str += "resourceId={" + resourceId + "} ";
+ str += "groupId={" + groupId + "} ";
+ str += "userId={" + userId + "} ";
+ str += "auditType={" + auditType + "} ";
+ str += "}";
+ return str;
+ }
+
+ /**
+ * Checks for all attributes except referenced db objects
+ * @return true if all attributes match
+ */
+ @Override
+ public boolean equals( Object obj) {
+ if ( !super.equals(obj) ) {
+ return false;
+ }
+ XXAuditMap other = (XXAuditMap) obj;
+ if ((this.resourceId == null && other.resourceId != null) || (this.resourceId != null && !this.resourceId.equals(other.resourceId))) {
+ return false;
+ }
+ if ((this.groupId == null && other.groupId != null) || (this.groupId != null && !this.groupId.equals(other.groupId))) {
+ return false;
+ }
+ if ((this.userId == null && other.userId != null) || (this.userId != null && !this.userId.equals(other.userId))) {
+ return false;
+ }
+ if( this.auditType != other.auditType ) return false;
+ return true;
+ }
+ public static String getEnumName(String fieldName ) {
+ if( fieldName.equals("auditType") ) {
+ return "CommonEnums.XAAuditType";
+ }
+ //Later TODO
+ //return super.getEnumName(fieldName);
+ return null;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/entity/XXAuthSession.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXAuthSession.java b/security-admin/src/main/java/org/apache/ranger/entity/XXAuthSession.java
new file mode 100644
index 0000000..d54ce72
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/entity/XXAuthSession.java
@@ -0,0 +1,472 @@
+/*
+ * 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.entity;
+
+/**
+ * Authentication session
+ *
+ */
+
+import java.util.*;
+
+import javax.persistence.*;
+import javax.xml.bind.annotation.*;
+
+import org.apache.ranger.common.*;
+import org.apache.ranger.entity.*;
+
+
+@Entity
+@Table(name="x_auth_sess")
+@XmlRootElement
+public class XXAuthSession extends XXDBBase implements java.io.Serializable {
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @SequenceGenerator(name="X_AUTH_SESS_SEQ",sequenceName="X_AUTH_SESS_SEQ",allocationSize=1)
+ @GeneratedValue(strategy=GenerationType.AUTO,generator="X_AUTH_SESS_SEQ")
+ @Column(name="ID")
+ protected Long id;
+ @Override
+ public void setId(Long id) {
+ this.id=id;
+ }
+
+ @Override
+ public Long getId() {
+ return id;
+ }
+ /**
+ * Enum values for AuthStatus
+ */
+ /**
+ * AUTH_STATUS_UNKNOWN is an element of enum AuthStatus. Its value is "AUTH_STATUS_UNKNOWN".
+ */
+ public static final int AUTH_STATUS_UNKNOWN = 0;
+ /**
+ * AUTH_STATUS_SUCCESS is an element of enum AuthStatus. Its value is "AUTH_STATUS_SUCCESS".
+ */
+ public static final int AUTH_STATUS_SUCCESS = 1;
+ /**
+ * AUTH_STATUS_WRONG_PASSWORD is an element of enum AuthStatus. Its value is "AUTH_STATUS_WRONG_PASSWORD".
+ */
+ public static final int AUTH_STATUS_WRONG_PASSWORD = 2;
+ /**
+ * AUTH_STATUS_DISABLED is an element of enum AuthStatus. Its value is "AUTH_STATUS_DISABLED".
+ */
+ public static final int AUTH_STATUS_DISABLED = 3;
+ /**
+ * AUTH_STATUS_LOCKED is an element of enum AuthStatus. Its value is "AUTH_STATUS_LOCKED".
+ */
+ public static final int AUTH_STATUS_LOCKED = 4;
+ /**
+ * AUTH_STATUS_PASSWORD_EXPIRED is an element of enum AuthStatus. Its value is "AUTH_STATUS_PASSWORD_EXPIRED".
+ */
+ public static final int AUTH_STATUS_PASSWORD_EXPIRED = 5;
+ /**
+ * AUTH_STATUS_USER_NOT_FOUND is an element of enum AuthStatus. Its value is "AUTH_STATUS_USER_NOT_FOUND".
+ */
+ public static final int AUTH_STATUS_USER_NOT_FOUND = 6;
+
+ /**
+ * Max value for enum AuthStatus_MAX
+ */
+ public static final int AuthStatus_MAX = 6;
+
+ /**
+ * Enum values for AuthType
+ */
+ /**
+ * AUTH_TYPE_UNKNOWN is an element of enum AuthType. Its value is "AUTH_TYPE_UNKNOWN".
+ */
+ public static final int AUTH_TYPE_UNKNOWN = 0;
+ /**
+ * AUTH_TYPE_PASSWORD is an element of enum AuthType. Its value is "AUTH_TYPE_PASSWORD".
+ */
+ public static final int AUTH_TYPE_PASSWORD = 1;
+
+ /**
+ * Max value for enum AuthType_MAX
+ */
+ public static final int AuthType_MAX = 1;
+
+
+
+ /**
+ * Login ID of the user
+ * <ul>
+ * <li>The maximum length for this attribute is <b>767</b>.
+ * </ul>
+ *
+ */
+ @Column(name="LOGIN_ID" , nullable=false , length=767)
+ protected String loginId;
+
+ /**
+ * Id of the user
+ * <ul>
+ * </ul>
+ *
+ */
+ @Column(name="USER_ID" )
+ protected Long userId;
+
+
+ /**
+ * External session id. Currently spring/http session
+ * <ul>
+ * <li>The maximum length for this attribute is <b>512</b>.
+ * </ul>
+ *
+ */
+ @Column(name="EXT_SESS_ID" , length=512)
+ protected String extSessionId;
+
+ /**
+ * Date and time of authentication
+ * <ul>
+ * </ul>
+ *
+ */
+ @Temporal(TemporalType.TIMESTAMP)
+ @Column(name="AUTH_TIME" , nullable=false )
+ protected Date authTime = DateUtil.getUTCDate();
+
+ /**
+ * Authentication status
+ * <ul>
+ * <li>This attribute is of type enum XXAuthSession::AuthStatus
+ * </ul>
+ *
+ */
+ @Column(name="AUTH_STATUS" , nullable=false )
+ protected int authStatus = AUTH_STATUS_UNKNOWN;
+
+ /**
+ * Authentication type
+ * <ul>
+ * <li>This attribute is of type enum XXAuthSession::AuthType
+ * </ul>
+ *
+ */
+ @Column(name="AUTH_TYPE" , nullable=false )
+ protected int authType = AUTH_TYPE_UNKNOWN;
+
+ /**
+ * Authentication provider
+ * <ul>
+ * <li>This attribute is of type enum XXAuthSession::AuthType
+ * </ul>
+ *
+ */
+ @Column(name="AUTH_PROVIDER" , nullable=false )
+ protected int authProvider = AUTH_TYPE_UNKNOWN;
+
+ /**
+ * Type of the device
+ * <ul>
+ * <li>This attribute is of type enum CommonEnums::DeviceType
+ * </ul>
+ *
+ */
+ @Column(name="DEVICE_TYPE" , nullable=false )
+ protected int deviceType = XAConstants.DEVICE_UNKNOWN;
+
+ /**
+ * IP where the request came from
+ * <ul>
+ * <li>The maximum length for this attribute is <b>48</b>.
+ * </ul>
+ *
+ */
+ @Column(name="REQ_IP" , nullable=false , length=48)
+ protected String requestIP;
+
+ /**
+ * UserAgent of the requesting device
+ * <ul>
+ * <li>The maximum length for this attribute is <b>1024</b>.
+ * </ul>
+ *
+ */
+ @Column(name="REQ_UA" , length=1024)
+ protected String requestUserAgent;
+
+ /**
+ * Default constructor. This will set all the attributes to default value.
+ */
+ public XXAuthSession ( ) {
+ authStatus = AUTH_STATUS_UNKNOWN;
+ authType = AUTH_TYPE_UNKNOWN;
+ authProvider = AUTH_TYPE_UNKNOWN;
+ deviceType = XAConstants.DEVICE_UNKNOWN;
+ }
+
+ @Override
+ public int getMyClassType( ) {
+ return AppConstants.CLASS_TYPE_AUTH_SESS;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>loginId</b>.
+ * You cannot set null to the attribute.
+ * @param loginId Value to set member attribute <b>loginId</b>
+ */
+ public void setLoginId( String loginId ) {
+ this.loginId = loginId;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>loginId</b>
+ * @return String - value of member attribute <b>loginId</b>.
+ */
+ public String getLoginId( ) {
+ return this.loginId;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>userId</b>.
+ * You cannot set null to the attribute.
+ * @param userId Value to set member attribute <b>userId</b>
+ */
+ public void setUserId( Long userId ) {
+ this.userId = userId;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>userId</b>
+ * @return Long - value of member attribute <b>userId</b>.
+ */
+ public Long getUserId( ) {
+ return this.userId;
+ }
+
+
+ /**
+ * This method sets the value to the member attribute <b>extSessionId</b>.
+ * You cannot set null to the attribute.
+ * @param extSessionId Value to set member attribute <b>extSessionId</b>
+ */
+ public void setExtSessionId( String extSessionId ) {
+ this.extSessionId = extSessionId;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>extSessionId</b>
+ * @return String - value of member attribute <b>extSessionId</b>.
+ */
+ public String getExtSessionId( ) {
+ return this.extSessionId;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>authTime</b>.
+ * You cannot set null to the attribute.
+ * @param authTime Value to set member attribute <b>authTime</b>
+ */
+ public void setAuthTime( Date authTime ) {
+ this.authTime = authTime;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>authTime</b>
+ * @return Date - value of member attribute <b>authTime</b>.
+ */
+ public Date getAuthTime( ) {
+ return this.authTime;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>authStatus</b>.
+ * You cannot set null to the attribute.
+ * @param authStatus Value to set member attribute <b>authStatus</b>
+ */
+ public void setAuthStatus( int authStatus ) {
+ this.authStatus = authStatus;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>authStatus</b>
+ * @return int - value of member attribute <b>authStatus</b>.
+ */
+ public int getAuthStatus( ) {
+ return this.authStatus;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>authType</b>.
+ * You cannot set null to the attribute.
+ * @param authType Value to set member attribute <b>authType</b>
+ */
+ public void setAuthType( int authType ) {
+ this.authType = authType;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>authType</b>
+ * @return int - value of member attribute <b>authType</b>.
+ */
+ public int getAuthType( ) {
+ return this.authType;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>authProvider</b>.
+ * You cannot set null to the attribute.
+ * @param authProvider Value to set member attribute <b>authProvider</b>
+ */
+ public void setAuthProvider( int authProvider ) {
+ this.authProvider = authProvider;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>authProvider</b>
+ * @return int - value of member attribute <b>authProvider</b>.
+ */
+ public int getAuthProvider( ) {
+ return this.authProvider;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>deviceType</b>.
+ * You cannot set null to the attribute.
+ * @param deviceType Value to set member attribute <b>deviceType</b>
+ */
+ public void setDeviceType( int deviceType ) {
+ this.deviceType = deviceType;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>deviceType</b>
+ * @return int - value of member attribute <b>deviceType</b>.
+ */
+ public int getDeviceType( ) {
+ return this.deviceType;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>requestIP</b>.
+ * You cannot set null to the attribute.
+ * @param requestIP Value to set member attribute <b>requestIP</b>
+ */
+ public void setRequestIP( String requestIP ) {
+ this.requestIP = requestIP;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>requestIP</b>
+ * @return String - value of member attribute <b>requestIP</b>.
+ */
+ public String getRequestIP( ) {
+ return this.requestIP;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>requestUserAgent</b>.
+ * You cannot set null to the attribute.
+ * @param requestUserAgent Value to set member attribute <b>requestUserAgent</b>
+ */
+ public void setRequestUserAgent( String requestUserAgent ) {
+ this.requestUserAgent = requestUserAgent;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>requestUserAgent</b>
+ * @return String - value of member attribute <b>requestUserAgent</b>.
+ */
+ public String getRequestUserAgent( ) {
+ return this.requestUserAgent;
+ }
+
+ /**
+ * This return the bean content in string format
+ * @return formatedStr
+ */
+ @Override
+ public String toString( ) {
+ String str = "XXAuthSession={";
+ str += super.toString();
+ str += "loginId={" + loginId + "} ";
+ str += "userId={" + userId + "} ";
+ str += "extSessionId={" + extSessionId + "} ";
+ str += "authTime={" + authTime + "} ";
+ str += "authStatus={" + authStatus + "} ";
+ str += "authType={" + authType + "} ";
+ str += "authProvider={" + authProvider + "} ";
+ str += "deviceType={" + deviceType + "} ";
+ str += "requestIP={" + requestIP + "} ";
+ str += "requestUserAgent={" + requestUserAgent + "} ";
+ str += "}";
+ return str;
+ }
+
+ /**
+ * Checks for all attributes except referenced db objects
+ * @return true if all attributes match
+ */
+ @Override
+ public boolean equals( Object obj) {
+ if ( !super.equals(obj) ) {
+ return false;
+ }
+ XXAuthSession other = (XXAuthSession) obj;
+ if ((this.loginId == null && other.loginId != null) || (this.loginId != null && !this.loginId.equals(other.loginId))) {
+ return false;
+ }
+ if ((this.userId == null && other.userId != null) || (this.userId != null && !this.userId.equals(other.userId))) {
+ return false;
+ }
+ if ((this.extSessionId == null && other.extSessionId != null) || (this.extSessionId != null && !this.extSessionId.equals(other.extSessionId))) {
+ return false;
+ }
+ if ((this.authTime == null && other.authTime != null) || (this.authTime != null && !this.authTime.equals(other.authTime))) {
+ return false;
+ }
+ if( this.authStatus != other.authStatus ) return false;
+ if( this.authType != other.authType ) return false;
+ if( this.authProvider != other.authProvider ) return false;
+ if( this.deviceType != other.deviceType ) return false;
+ if ((this.requestIP == null && other.requestIP != null) || (this.requestIP != null && !this.requestIP.equals(other.requestIP))) {
+ return false;
+ }
+ if ((this.requestUserAgent == null && other.requestUserAgent != null) || (this.requestUserAgent != null && !this.requestUserAgent.equals(other.requestUserAgent))) {
+ return false;
+ }
+ return true;
+ }
+ public static String getEnumName(String fieldName ) {
+ if( fieldName.equals("authStatus") ) {
+ return "CommonEnums.AuthStatus";
+ }
+ if( fieldName.equals("authType") ) {
+ return "CommonEnums.AuthType";
+ }
+ if( fieldName.equals("authProvider") ) {
+ return "CommonEnums.AuthType";
+ }
+ if( fieldName.equals("deviceType") ) {
+ return "CommonEnums.DeviceType";
+ }
+ //Later TODO
+ //return super.getEnumName(fieldName);
+ return null;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/entity/XXCredentialStore.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXCredentialStore.java b/security-admin/src/main/java/org/apache/ranger/entity/XXCredentialStore.java
new file mode 100644
index 0000000..b300071
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/entity/XXCredentialStore.java
@@ -0,0 +1,164 @@
+/*
+ * 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.entity;
+
+/**
+ * Credential Store
+ *
+ */
+
+import java.util.*;
+
+import javax.persistence.*;
+import javax.xml.bind.annotation.*;
+
+import org.apache.ranger.common.*;
+import org.apache.ranger.entity.*;
+
+
+@Entity
+@Table(name="x_cred_store")
+@XmlRootElement
+public class XXCredentialStore extends XXDBBase implements java.io.Serializable {
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @SequenceGenerator(name="X_CRED_STORE_SEQ",sequenceName="X_CRED_STORE_SEQ",allocationSize=1)
+ @GeneratedValue(strategy=GenerationType.AUTO,generator="X_CRED_STORE_SEQ")
+ @Column(name="ID")
+ protected Long id;
+
+ @Override
+ public void setId(Long id) {
+ this.id=id;
+ }
+ @Override
+ public Long getId() {
+ return id;
+ }
+ /**
+ * Name
+ * <ul>
+ * <li>The maximum length for this attribute is <b>1024</b>.
+ * </ul>
+ *
+ */
+ @Column(name="STORE_NAME" , nullable=false , length=1024)
+ protected String name;
+
+ /**
+ * Description
+ * <ul>
+ * <li>The maximum length for this attribute is <b>4000</b>.
+ * </ul>
+ *
+ */
+ @Column(name="DESCR" , nullable=false , length=4000)
+ protected String description;
+
+ /**
+ * Default constructor. This will set all the attributes to default value.
+ */
+ public XXCredentialStore ( ) {
+ }
+
+ @Override
+ public int getMyClassType( ) {
+ return AppConstants.CLASS_TYPE_XA_CRED_STORE;
+ }
+
+ @Override
+ public String getMyDisplayValue() {
+ return getDescription( );
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>name</b>.
+ * You cannot set null to the attribute.
+ * @param name Value to set member attribute <b>name</b>
+ */
+ public void setName( String name ) {
+ this.name = name;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>name</b>
+ * @return String - value of member attribute <b>name</b>.
+ */
+ public String getName( ) {
+ return this.name;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>description</b>.
+ * You cannot set null to the attribute.
+ * @param description Value to set member attribute <b>description</b>
+ */
+ public void setDescription( String description ) {
+ this.description = description;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>description</b>
+ * @return String - value of member attribute <b>description</b>.
+ */
+ public String getDescription( ) {
+ return this.description;
+ }
+
+ /**
+ * This return the bean content in string format
+ * @return formatedStr
+ */
+ @Override
+ public String toString( ) {
+ String str = "XXCredentialStore={";
+ str += super.toString();
+ str += "name={" + name + "} ";
+ str += "description={" + description + "} ";
+ str += "}";
+ return str;
+ }
+
+ /**
+ * Checks for all attributes except referenced db objects
+ * @return true if all attributes match
+ */
+ @Override
+ public boolean equals( Object obj) {
+ if ( !super.equals(obj) ) {
+ return false;
+ }
+ XXCredentialStore other = (XXCredentialStore) obj;
+ if ((this.name == null && other.name != null) || (this.name != null && !this.name.equals(other.name))) {
+ return false;
+ }
+ if ((this.description == null && other.description != null) || (this.description != null && !this.description.equals(other.description))) {
+ return false;
+ }
+ return true;
+ }
+ public static String getEnumName(String fieldName ) {
+ //Later TODO
+ //return super.getEnumName(fieldName);
+ return null;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/entity/XXDBBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXDBBase.java b/security-admin/src/main/java/org/apache/ranger/entity/XXDBBase.java
new file mode 100644
index 0000000..666f0f5
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/entity/XXDBBase.java
@@ -0,0 +1,234 @@
+/*
+ * 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.entity;
+
+/**
+ * Base JPA class with id, versionNumber and other common attributes
+ *
+ */
+
+import java.util.*;
+
+import javax.persistence.*;
+import javax.xml.bind.annotation.*;
+
+import org.apache.ranger.common.*;
+import org.apache.ranger.entity.*;
+
+
+@MappedSuperclass @EntityListeners( org.apache.ranger.common.db.JPABeanCallbacks.class)
+@XmlRootElement
+public abstract class XXDBBase extends Object implements java.io.Serializable {
+ private static final long serialVersionUID = 1L;
+
+
+
+ /**
+ * Id for the object
+ * <ul>
+ * <li>This attribute is the <b>Primary Key</b> for this class<br>.
+ * </ul>
+ *
+ */
+
+ /**
+ * Date/Time creation of this user.
+ * <ul>
+ * </ul>
+ *
+ */
+ @Temporal(TemporalType.TIMESTAMP)
+ @Column(name="CREATE_TIME" )
+ protected Date createTime = DateUtil.getUTCDate();
+
+ /**
+ * Date value.
+ * <ul>
+ * </ul>
+ *
+ */
+ @Temporal(TemporalType.TIMESTAMP)
+ @Column(name="UPDATE_TIME" )
+ protected Date updateTime = DateUtil.getUTCDate();
+
+ /**
+ * Added by
+ * <ul>
+ * </ul>
+ *
+ */
+ @Column(name="ADDED_BY_ID" )
+ protected Long addedByUserId;
+
+
+ /**
+ * Last updated by
+ * <ul>
+ * </ul>
+ *
+ */
+ @Column(name="UPD_BY_ID" )
+ protected Long updatedByUserId;
+
+
+ /**
+ * Default constructor. This will set all the attributes to default value.
+ */
+ public XXDBBase ( ) {
+ }
+
+ public int getMyClassType( ) {
+ return AppConstants.CLASS_TYPE_NONE;
+ }
+
+ public String getMyDisplayValue() {
+ return null;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>id</b>.
+ * You cannot set null to the attribute.
+ * @param id Value to set member attribute <b>id</b>
+ */
+ public abstract void setId( Long id ) ;
+
+ /**
+ * Returns the value for the member attribute <b>id</b>
+ * @return Long - value of member attribute <b>id</b>.
+ */
+ public abstract Long getId( );
+
+ /**
+ * This method sets the value to the member attribute <b>createTime</b>.
+ * You cannot set null to the attribute.
+ * @param createTime Value to set member attribute <b>createTime</b>
+ */
+ public void setCreateTime( Date createTime ) {
+ this.createTime = createTime;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>createTime</b>
+ * @return Date - value of member attribute <b>createTime</b>.
+ */
+ public Date getCreateTime( ) {
+ return this.createTime;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>updateTime</b>.
+ * You cannot set null to the attribute.
+ * @param updateTime Value to set member attribute <b>updateTime</b>
+ */
+ public void setUpdateTime( Date updateTime ) {
+ this.updateTime = updateTime;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>updateTime</b>
+ * @return Date - value of member attribute <b>updateTime</b>.
+ */
+ public Date getUpdateTime( ) {
+ return this.updateTime;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>addedByUserId</b>.
+ * You cannot set null to the attribute.
+ * @param addedByUserId Value to set member attribute <b>addedByUserId</b>
+ */
+ public void setAddedByUserId( Long addedByUserId ) {
+ this.addedByUserId = addedByUserId;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>addedByUserId</b>
+ * @return Long - value of member attribute <b>addedByUserId</b>.
+ */
+ public Long getAddedByUserId( ) {
+ return this.addedByUserId;
+ }
+
+
+ /**
+ * This method sets the value to the member attribute <b>updatedByUserId</b>.
+ * You cannot set null to the attribute.
+ * @param updatedByUserId Value to set member attribute <b>updatedByUserId</b>
+ */
+ public void setUpdatedByUserId( Long updatedByUserId ) {
+ this.updatedByUserId = updatedByUserId;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>updatedByUserId</b>
+ * @return Long - value of member attribute <b>updatedByUserId</b>.
+ */
+ public Long getUpdatedByUserId( ) {
+ return this.updatedByUserId;
+ }
+
+
+ /**
+ * This return the bean content in string format
+ * @return formatedStr
+ */
+ @Override
+ public String toString( ) {
+ String str = "XXDBBase={";
+ //`str += "id={" + id + "} ";
+ str += "createTime={" + createTime + "} ";
+ str += "updateTime={" + updateTime + "} ";
+ str += "addedByUserId={" + addedByUserId + "} ";
+ str += "updatedByUserId={" + updatedByUserId + "} ";
+ str += "}";
+ return str;
+ }
+
+ /**
+ * Checks for all attributes except referenced db objects
+ * @return true if all attributes match
+ */
+ @Override
+ public boolean equals( Object obj) {
+ XXDBBase other = (XXDBBase) obj;
+// if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
+// return false;
+// }
+ if ((this.createTime == null && other.createTime != null) || (this.createTime != null && !this.createTime.equals(other.createTime))) {
+ return false;
+ }
+ if ((this.updateTime == null && other.updateTime != null) || (this.updateTime != null && !this.updateTime.equals(other.updateTime))) {
+ return false;
+ }
+ if ((this.addedByUserId == null && other.addedByUserId != null) || (this.addedByUserId != null && !this.addedByUserId.equals(other.addedByUserId))) {
+ return false;
+ }
+ if ((this.updatedByUserId == null && other.updatedByUserId != null) || (this.updatedByUserId != null && !this.updatedByUserId.equals(other.updatedByUserId))) {
+ return false;
+ }
+ return true;
+ }
+ public static String getEnumName(String fieldName ) {
+ //Later TODO
+ //return super.getEnumName(fieldName);
+ return null;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/entity/XXGroup.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXGroup.java b/security-admin/src/main/java/org/apache/ranger/entity/XXGroup.java
new file mode 100644
index 0000000..1e25eb6
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/entity/XXGroup.java
@@ -0,0 +1,275 @@
+/*
+ * 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.entity;
+
+/**
+ * Group
+ *
+ */
+
+import java.util.*;
+
+import javax.persistence.*;
+import javax.xml.bind.annotation.*;
+
+import org.apache.ranger.common.*;
+import org.apache.ranger.entity.*;
+
+
+@Entity
+@Table(name="x_group")
+@XmlRootElement
+public class XXGroup extends XXDBBase implements java.io.Serializable {
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @SequenceGenerator(name="X_GROUP_SEQ",sequenceName="X_GROUP_SEQ",allocationSize=1)
+ @GeneratedValue(strategy=GenerationType.AUTO,generator="X_GROUP_SEQ")
+ @Column(name="ID")
+ protected Long id;
+ @Override
+ public void setId(Long id) {
+ this.id=id;
+ }
+ @Override
+ public Long getId() {
+ return id;
+ }
+ /**
+ * Name
+ * <ul>
+ * <li>The maximum length for this attribute is <b>1024</b>.
+ * </ul>
+ *
+ */
+ @Column(name="GROUP_NAME" , nullable=false , length=1024)
+ protected String name;
+
+ /**
+ * Description
+ * <ul>
+ * <li>The maximum length for this attribute is <b>4000</b>.
+ * </ul>
+ *
+ */
+ @Column(name="DESCR" , nullable=false , length=4000)
+ protected String description;
+
+ /**
+ * Status
+ * <ul>
+ * <li>This attribute is of type enum CommonEnums::ActiveStatus
+ * </ul>
+ *
+ */
+ @Column(name="STATUS" , nullable=false )
+ protected int status = XAConstants.STATUS_DISABLED;
+
+ /**
+ * Type of group
+ * <ul>
+ * <li>This attribute is of type enum CommonEnums::XAGroupType
+ * </ul>
+ *
+ */
+ @Column(name="GROUP_TYPE" , nullable=false )
+ protected int groupType = AppConstants.XA_GROUP_UNKNOWN;
+
+ @Column(name="GROUP_SRC" , nullable=false )
+ protected int groupSource = XACommonEnums.GROUP_INTERNAL;
+
+ /**
+ * Id of the credential store
+ * <ul>
+ * </ul>
+ *
+ */
+ @Column(name="CRED_STORE_ID" )
+ protected Long credStoreId;
+
+
+ /**
+ * Default constructor. This will set all the attributes to default value.
+ */
+ public XXGroup ( ) {
+ status = XAConstants.STATUS_DISABLED;
+ groupType = AppConstants.XA_GROUP_UNKNOWN;
+ groupSource = XACommonEnums.GROUP_INTERNAL;
+ }
+
+ @Override
+ public int getMyClassType( ) {
+ return AppConstants.CLASS_TYPE_XA_GROUP;
+ }
+
+ @Override
+ public String getMyDisplayValue() {
+ return getDescription( );
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>name</b>.
+ * You cannot set null to the attribute.
+ * @param name Value to set member attribute <b>name</b>
+ */
+ public void setName( String name ) {
+ this.name = name;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>name</b>
+ * @return String - value of member attribute <b>name</b>.
+ */
+ public String getName( ) {
+ return this.name;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>description</b>.
+ * You cannot set null to the attribute.
+ * @param description Value to set member attribute <b>description</b>
+ */
+ public void setDescription( String description ) {
+ this.description = description;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>description</b>
+ * @return String - value of member attribute <b>description</b>.
+ */
+ public String getDescription( ) {
+ return this.description;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>status</b>.
+ * You cannot set null to the attribute.
+ * @param status Value to set member attribute <b>status</b>
+ */
+ public void setStatus( int status ) {
+ this.status = status;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>status</b>
+ * @return int - value of member attribute <b>status</b>.
+ */
+ public int getStatus( ) {
+ return this.status;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>groupType</b>.
+ * You cannot set null to the attribute.
+ * @param groupType Value to set member attribute <b>groupType</b>
+ */
+ public void setGroupType( int groupType ) {
+ this.groupType = groupType;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>groupType</b>
+ * @return int - value of member attribute <b>groupType</b>.
+ */
+ public int getGroupType( ) {
+ return this.groupType;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>credStoreId</b>.
+ * You cannot set null to the attribute.
+ * @param credStoreId Value to set member attribute <b>credStoreId</b>
+ */
+ public void setCredStoreId( Long credStoreId ) {
+ this.credStoreId = credStoreId;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>credStoreId</b>
+ * @return Long - value of member attribute <b>credStoreId</b>.
+ */
+ public Long getCredStoreId( ) {
+ return this.credStoreId;
+ }
+
+
+
+ /**
+ * This return the bean content in string format
+ * @return formatedStr
+ */
+ @Override
+ public String toString( ) {
+ String str = "XXGroup={";
+ str += super.toString();
+ str += "name={" + name + "} ";
+ str += "description={" + description + "} ";
+ str += "status={" + status + "} ";
+ str += "groupType={" + groupType + "} ";
+ str += "credStoreId={" + credStoreId + "} ";
+ str += "groupSrc={" + groupSource + "} ";
+ str += "}";
+ return str;
+ }
+
+ public int getGroupSource() {
+ return groupSource;
+ }
+
+ public void setGroupSource(int groupSource) {
+ this.groupSource = groupSource;
+ }
+
+ /**
+ * Checks for all attributes except referenced db objects
+ * @return true if all attributes match
+ */
+ @Override
+ public boolean equals( Object obj) {
+ if ( !super.equals(obj) ) {
+ return false;
+ }
+ XXGroup other = (XXGroup) obj;
+ if ((this.name == null && other.name != null) || (this.name != null && !this.name.equals(other.name))) {
+ return false;
+ }
+ if ((this.description == null && other.description != null) || (this.description != null && !this.description.equals(other.description))) {
+ return false;
+ }
+ if( this.status != other.status ) return false;
+ if( this.groupType != other.groupType ) return false;
+ if ((this.credStoreId == null && other.credStoreId != null) || (this.credStoreId != null && !this.credStoreId.equals(other.credStoreId))) {
+ return false;
+ }
+ return true;
+ }
+ public static String getEnumName(String fieldName ) {
+ if( fieldName.equals("status") ) {
+ return "CommonEnums.ActiveStatus";
+ }
+ if( fieldName.equals("groupType") ) {
+ return "CommonEnums.XAGroupType";
+ }
+ //Later TODO
+ //return super.getEnumName(fieldName);
+ return null;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/entity/XXGroupGroup.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXGroupGroup.java b/security-admin/src/main/java/org/apache/ranger/entity/XXGroupGroup.java
new file mode 100644
index 0000000..d7997cb
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/entity/XXGroupGroup.java
@@ -0,0 +1,196 @@
+/*
+ * 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.entity;
+
+/**
+ * Group of groups
+ *
+ */
+
+import java.util.*;
+
+import javax.persistence.*;
+import javax.xml.bind.annotation.*;
+
+import org.apache.ranger.common.*;
+import org.apache.ranger.entity.*;
+
+
+@Entity
+@Table(name="x_group_groups")
+@XmlRootElement
+public class XXGroupGroup extends XXDBBase implements java.io.Serializable {
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @SequenceGenerator(name="X_GROUP_GROUPS_SEQ",sequenceName="X_GROUP_GROUPS_SEQ",allocationSize=1)
+ @GeneratedValue(strategy=GenerationType.AUTO,generator="X_GROUP_GROUPS_SEQ")
+ @Column(name="ID")
+ protected Long id;
+ @Override
+ public void setId(Long id) {
+ this.id=id;
+ }
+ @Override
+ public Long getId() {
+ return id;
+ }
+ /**
+ * Name
+ * <ul>
+ * <li>The maximum length for this attribute is <b>1024</b>.
+ * </ul>
+ *
+ */
+ @Column(name="GROUP_NAME" , nullable=false , length=1024)
+ protected String name;
+
+ /**
+ * Id of the parent group
+ * <ul>
+ * </ul>
+ *
+ */
+ @Column(name="P_GROUP_ID" )
+ protected Long parentGroupId;
+
+
+ /**
+ * Id of the group
+ * <ul>
+ * </ul>
+ *
+ */
+ @Column(name="GROUP_ID" )
+ protected Long groupId;
+
+
+ /**
+ * Default constructor. This will set all the attributes to default value.
+ */
+ public XXGroupGroup ( ) {
+ }
+
+ @Override
+ public int getMyClassType( ) {
+ return AppConstants.CLASS_TYPE_XA_GROUP_GROUP;
+ }
+
+ @Override
+ public String getMyDisplayValue() {
+ return getName( );
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>name</b>.
+ * You cannot set null to the attribute.
+ * @param name Value to set member attribute <b>name</b>
+ */
+ public void setName( String name ) {
+ this.name = name;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>name</b>
+ * @return String - value of member attribute <b>name</b>.
+ */
+ public String getName( ) {
+ return this.name;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>parentGroupId</b>.
+ * You cannot set null to the attribute.
+ * @param parentGroupId Value to set member attribute <b>parentGroupId</b>
+ */
+ public void setParentGroupId( Long parentGroupId ) {
+ this.parentGroupId = parentGroupId;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>parentGroupId</b>
+ * @return Long - value of member attribute <b>parentGroupId</b>.
+ */
+ public Long getParentGroupId( ) {
+ return this.parentGroupId;
+ }
+
+
+ /**
+ * This method sets the value to the member attribute <b>groupId</b>.
+ * You cannot set null to the attribute.
+ * @param groupId Value to set member attribute <b>groupId</b>
+ */
+ public void setGroupId( Long groupId ) {
+ this.groupId = groupId;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>groupId</b>
+ * @return Long - value of member attribute <b>groupId</b>.
+ */
+ public Long getGroupId( ) {
+ return this.groupId;
+ }
+
+
+ /**
+ * This return the bean content in string format
+ * @return formatedStr
+ */
+ @Override
+ public String toString( ) {
+ String str = "XXGroupGroup={";
+ str += super.toString();
+ str += "name={" + name + "} ";
+ str += "parentGroupId={" + parentGroupId + "} ";
+ str += "groupId={" + groupId + "} ";
+ str += "}";
+ return str;
+ }
+
+ /**
+ * Checks for all attributes except referenced db objects
+ * @return true if all attributes match
+ */
+ @Override
+ public boolean equals( Object obj) {
+ if ( !super.equals(obj) ) {
+ return false;
+ }
+ XXGroupGroup other = (XXGroupGroup) obj;
+ if ((this.name == null && other.name != null) || (this.name != null && !this.name.equals(other.name))) {
+ return false;
+ }
+ if ((this.parentGroupId == null && other.parentGroupId != null) || (this.parentGroupId != null && !this.parentGroupId.equals(other.parentGroupId))) {
+ return false;
+ }
+ if ((this.groupId == null && other.groupId != null) || (this.groupId != null && !this.groupId.equals(other.groupId))) {
+ return false;
+ }
+ return true;
+ }
+ public static String getEnumName(String fieldName ) {
+ //Later TODO
+ //return super.getEnumName(fieldName);
+ return null;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/entity/XXGroupUser.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXGroupUser.java b/security-admin/src/main/java/org/apache/ranger/entity/XXGroupUser.java
new file mode 100644
index 0000000..0c05f15
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/entity/XXGroupUser.java
@@ -0,0 +1,199 @@
+/*
+ * 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.entity;
+
+/**
+ * Group of users
+ *
+ */
+
+import java.util.*;
+
+import javax.persistence.*;
+import javax.xml.bind.annotation.*;
+
+import org.apache.ranger.common.*;
+import org.apache.ranger.entity.*;
+
+
+@Entity
+@Table(name="x_group_users")
+@XmlRootElement
+public class XXGroupUser extends XXDBBase implements java.io.Serializable {
+ private static final long serialVersionUID = 1L;
+
+
+ @Id
+ @SequenceGenerator(name="X_GROUP_USERS_SEQ",sequenceName="X_GROUP_USERS_SEQ",allocationSize=1)
+ @GeneratedValue(strategy=GenerationType.AUTO,generator="X_GROUP_USERS_SEQ")
+ @Column(name="ID")
+ protected Long id;
+ @Override
+ public void setId(Long id) {
+ this.id=id;
+ }
+
+ @Override
+ public Long getId() {
+ return id;
+ }
+
+ /**
+ * Name
+ * <ul>
+ * <li>The maximum length for this attribute is <b>1024</b>.
+ * </ul>
+ *
+ */
+ @Column(name="GROUP_NAME" , nullable=false , length=1024)
+ protected String name;
+
+ /**
+ * Id of the group
+ * <ul>
+ * </ul>
+ *
+ */
+ @Column(name="P_GROUP_ID" )
+ protected Long parentGroupId;
+
+
+ /**
+ * Id of the user
+ * <ul>
+ * </ul>
+ *
+ */
+ @Column(name="USER_ID" )
+ protected Long userId;
+
+
+ /**
+ * Default constructor. This will set all the attributes to default value.
+ */
+ public XXGroupUser ( ) {
+ }
+
+ @Override
+ public int getMyClassType( ) {
+ return AppConstants.CLASS_TYPE_XA_GROUP_USER;
+ }
+
+ @Override
+ public String getMyDisplayValue() {
+ return getName( );
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>name</b>.
+ * You cannot set null to the attribute.
+ * @param name Value to set member attribute <b>name</b>
+ */
+ public void setName( String name ) {
+ this.name = name;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>name</b>
+ * @return String - value of member attribute <b>name</b>.
+ */
+ public String getName( ) {
+ return this.name;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>parentGroupId</b>.
+ * You cannot set null to the attribute.
+ * @param parentGroupId Value to set member attribute <b>parentGroupId</b>
+ */
+ public void setParentGroupId( Long parentGroupId ) {
+ this.parentGroupId = parentGroupId;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>parentGroupId</b>
+ * @return Long - value of member attribute <b>parentGroupId</b>.
+ */
+ public Long getParentGroupId( ) {
+ return this.parentGroupId;
+ }
+
+
+ /**
+ * This method sets the value to the member attribute <b>userId</b>.
+ * You cannot set null to the attribute.
+ * @param userId Value to set member attribute <b>userId</b>
+ */
+ public void setUserId( Long userId ) {
+ this.userId = userId;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>userId</b>
+ * @return Long - value of member attribute <b>userId</b>.
+ */
+ public Long getUserId( ) {
+ return this.userId;
+ }
+
+
+ /**
+ * This return the bean content in string format
+ * @return formatedStr
+ */
+ @Override
+ public String toString( ) {
+ String str = "XXGroupUser={";
+ str += super.toString();
+ str += "name={" + name + "} ";
+ str += "parentGroupId={" + parentGroupId + "} ";
+ str += "userId={" + userId + "} ";
+ str += "}";
+ return str;
+ }
+
+ /**
+ * Checks for all attributes except referenced db objects
+ * @return true if all attributes match
+ */
+ @Override
+ public boolean equals( Object obj) {
+ if ( !super.equals(obj) ) {
+ return false;
+ }
+ XXGroupUser other = (XXGroupUser) obj;
+ if ((this.name == null && other.name != null) || (this.name != null && !this.name.equals(other.name))) {
+ return false;
+ }
+ if ((this.parentGroupId == null && other.parentGroupId != null) || (this.parentGroupId != null && !this.parentGroupId.equals(other.parentGroupId))) {
+ return false;
+ }
+ if ((this.userId == null && other.userId != null) || (this.userId != null && !this.userId.equals(other.userId))) {
+ return false;
+ }
+ return true;
+ }
+ public static String getEnumName(String fieldName ) {
+ //Later TODO
+ //return super.getEnumName(fieldName);
+ return null;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/entity/XXPermMap.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPermMap.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPermMap.java
new file mode 100644
index 0000000..ecf22f7
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPermMap.java
@@ -0,0 +1,398 @@
+/*
+ * 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.entity;
+
+/**
+ * Permission map
+ *
+ */
+
+import java.util.*;
+
+import javax.persistence.*;
+import javax.xml.bind.annotation.*;
+
+import org.apache.ranger.common.*;
+import org.apache.ranger.entity.*;
+
+
+@Entity
+@Table(name="x_perm_map")
+@XmlRootElement
+public class XXPermMap extends XXDBBase implements java.io.Serializable {
+ private static final long serialVersionUID = 1L;
+
+
+ @Id
+ @SequenceGenerator(name="X_PERM_MAP_SEQ",sequenceName="X_PERM_MAP_SEQ",allocationSize=1)
+ @GeneratedValue(strategy=GenerationType.AUTO,generator="X_PERM_MAP_SEQ")
+ @Column(name="ID")
+ protected Long id;
+ @Override
+ public void setId(Long id) {
+ this.id=id;
+ }
+
+ @Override
+ public Long getId() {
+ return id;
+ }
+
+ /**
+ * Group to which the permission belongs to
+ * <ul>
+ * <li>The maximum length for this attribute is <b>1024</b>.
+ * </ul>
+ *
+ */
+ @Column(name="PERM_GROUP" , length=1024)
+ protected String permGroup;
+
+ /**
+ * Id of the resource
+ * <ul>
+ * </ul>
+ *
+ */
+ @Column(name="RES_ID" )
+ protected Long resourceId;
+
+
+ /**
+ * Id of the group
+ * <ul>
+ * </ul>
+ *
+ */
+ @Column(name="GROUP_ID" )
+ protected Long groupId;
+
+
+ /**
+ * Id of the user
+ * <ul>
+ * </ul>
+ *
+ */
+ @Column(name="USER_ID" )
+ protected Long userId;
+
+
+ /**
+ * Permission for user or group
+ * <ul>
+ * <li>This attribute is of type enum CommonEnums::XAPermForType
+ * </ul>
+ *
+ */
+ @Column(name="PERM_FOR" , nullable=false )
+ protected int permFor = AppConstants.XA_PERM_FOR_UNKNOWN;
+
+ /**
+ * Type of permission
+ * <ul>
+ * <li>This attribute is of type enum CommonEnums::XAPermType
+ * </ul>
+ *
+ */
+ @Column(name="PERM_TYPE" , nullable=false )
+ protected int permType = AppConstants.XA_PERM_TYPE_UNKNOWN;
+
+ /**
+ * Is recursive
+ * <ul>
+ * <li>This attribute is of type enum CommonEnums::BooleanValue
+ * </ul>
+ *
+ */
+ @Column(name="IS_RECURSIVE" , nullable=false )
+ protected int isRecursive = XAConstants.BOOL_NONE;
+
+ /**
+ * Is wild card
+ * <ul>
+ * </ul>
+ *
+ */
+ @Column(name="IS_WILD_CARD" , nullable=false )
+ protected boolean isWildCard = true;
+
+ /**
+ * Grant is true and revoke is false
+ * <ul>
+ * </ul>
+ *
+ */
+ @Column(name="GRANT_REVOKE" , nullable=false )
+ protected boolean grantOrRevoke = true;
+ /**
+ * IP address to which the group belongs to
+ * <ul>
+ * <li>The maximum length for this attribute is <b>1024</b>.
+ * </ul>
+ *
+ */
+ @Column(name="IP_ADDRESS" , length=1024)
+ protected String ipAddress;
+
+ /**
+ * Default constructor. This will set all the attributes to default value.
+ */
+ public XXPermMap ( ) {
+ permFor = AppConstants.XA_PERM_FOR_UNKNOWN;
+ permType = AppConstants.XA_PERM_TYPE_UNKNOWN;
+ isRecursive = XAConstants.BOOL_NONE;
+ }
+
+ @Override
+ public int getMyClassType( ) {
+ return AppConstants.CLASS_TYPE_XA_PERM_MAP;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>permGroup</b>.
+ * You cannot set null to the attribute.
+ * @param permGroup Value to set member attribute <b>permGroup</b>
+ */
+ public void setPermGroup( String permGroup ) {
+ this.permGroup = permGroup;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>permGroup</b>
+ * @return String - value of member attribute <b>permGroup</b>.
+ */
+ public String getPermGroup( ) {
+ return this.permGroup;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>resourceId</b>.
+ * You cannot set null to the attribute.
+ * @param resourceId Value to set member attribute <b>resourceId</b>
+ */
+ public void setResourceId( Long resourceId ) {
+ this.resourceId = resourceId;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>resourceId</b>
+ * @return Long - value of member attribute <b>resourceId</b>.
+ */
+ public Long getResourceId( ) {
+ return this.resourceId;
+ }
+
+
+ /**
+ * This method sets the value to the member attribute <b>groupId</b>.
+ * You cannot set null to the attribute.
+ * @param groupId Value to set member attribute <b>groupId</b>
+ */
+ public void setGroupId( Long groupId ) {
+ this.groupId = groupId;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>groupId</b>
+ * @return Long - value of member attribute <b>groupId</b>.
+ */
+ public Long getGroupId( ) {
+ return this.groupId;
+ }
+
+
+ /**
+ * This method sets the value to the member attribute <b>userId</b>.
+ * You cannot set null to the attribute.
+ * @param userId Value to set member attribute <b>userId</b>
+ */
+ public void setUserId( Long userId ) {
+ this.userId = userId;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>userId</b>
+ * @return Long - value of member attribute <b>userId</b>.
+ */
+ public Long getUserId( ) {
+ return this.userId;
+ }
+
+
+ /**
+ * This method sets the value to the member attribute <b>permFor</b>.
+ * You cannot set null to the attribute.
+ * @param permFor Value to set member attribute <b>permFor</b>
+ */
+ public void setPermFor( int permFor ) {
+ this.permFor = permFor;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>permFor</b>
+ * @return int - value of member attribute <b>permFor</b>.
+ */
+ public int getPermFor( ) {
+ return this.permFor;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>permType</b>.
+ * You cannot set null to the attribute.
+ * @param permType Value to set member attribute <b>permType</b>
+ */
+ public void setPermType( int permType ) {
+ this.permType = permType;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>permType</b>
+ * @return int - value of member attribute <b>permType</b>.
+ */
+ public int getPermType( ) {
+ return this.permType;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>isRecursive</b>.
+ * You cannot set null to the attribute.
+ * @param isRecursive Value to set member attribute <b>isRecursive</b>
+ */
+ public void setIsRecursive( int isRecursive ) {
+ this.isRecursive = isRecursive;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>isRecursive</b>
+ * @return int - value of member attribute <b>isRecursive</b>.
+ */
+ public int getIsRecursive( ) {
+ return this.isRecursive;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>isWildCard</b>.
+ * You cannot set null to the attribute.
+ * @param isWildCard Value to set member attribute <b>isWildCard</b>
+ */
+ public void setIsWildCard( boolean isWildCard ) {
+ this.isWildCard = isWildCard;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>isWildCard</b>
+ * @return boolean - value of member attribute <b>isWildCard</b>.
+ */
+ public boolean isIsWildCard( ) {
+ return this.isWildCard;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>grantOrRevoke</b>.
+ * You cannot set null to the attribute.
+ * @param grantOrRevoke Value to set member attribute <b>grantOrRevoke</b>
+ */
+ public void setGrantOrRevoke( boolean grantOrRevoke ) {
+ this.grantOrRevoke = grantOrRevoke;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>grantOrRevoke</b>
+ * @return boolean - value of member attribute <b>grantOrRevoke</b>.
+ */
+ public boolean isGrantOrRevoke( ) {
+ return this.grantOrRevoke;
+ }
+
+ public String getIpAddress() {
+ return ipAddress;
+ }
+
+ public void setIpAddress(String ipAddress) {
+ this.ipAddress = ipAddress;
+ }
+
+ /**
+ * This return the bean content in string format
+ * @return formatedStr
+ */
+ @Override
+ public String toString( ) {
+ String str = "XXPermMap={";
+ str += super.toString();
+ str += "permGroup={" + permGroup + "} ";
+ str += "resourceId={" + resourceId + "} ";
+ str += "groupId={" + groupId + "} ";
+ str += "userId={" + userId + "} ";
+ str += "permFor={" + permFor + "} ";
+ str += "permType={" + permType + "} ";
+ str += "isRecursive={" + isRecursive + "} ";
+ str += "isWildCard={" + isWildCard + "} ";
+ str += "grantOrRevoke={" + grantOrRevoke + "} ";
+ str += "}";
+ return str;
+ }
+
+ /**
+ * Checks for all attributes except referenced db objects
+ * @return true if all attributes match
+ */
+ @Override
+ public boolean equals( Object obj) {
+ if ( !super.equals(obj) ) {
+ return false;
+ }
+ XXPermMap other = (XXPermMap) obj;
+ if ((this.permGroup == null && other.permGroup != null) || (this.permGroup != null && !this.permGroup.equals(other.permGroup))) {
+ return false;
+ }
+ if ((this.resourceId == null && other.resourceId != null) || (this.resourceId != null && !this.resourceId.equals(other.resourceId))) {
+ return false;
+ }
+ if ((this.groupId == null && other.groupId != null) || (this.groupId != null && !this.groupId.equals(other.groupId))) {
+ return false;
+ }
+ if ((this.userId == null && other.userId != null) || (this.userId != null && !this.userId.equals(other.userId))) {
+ return false;
+ }
+ if( this.permFor != other.permFor ) return false;
+ if( this.permType != other.permType ) return false;
+ if( this.isRecursive != other.isRecursive ) return false;
+ if( this.isWildCard != other.isWildCard ) return false;
+ if( this.grantOrRevoke != other.grantOrRevoke ) return false;
+ return true;
+ }
+ public static String getEnumName(String fieldName ) {
+ if( fieldName.equals("permFor") ) {
+ return "CommonEnums.XAPermForType";
+ }
+ if( fieldName.equals("permType") ) {
+ return "CommonEnums.XAPermType";
+ }
+ if( fieldName.equals("isRecursive") ) {
+ return "CommonEnums.BooleanValue";
+ }
+ //Later TODO
+ //return super.getEnumName(fieldName);
+ return null;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyExportAudit.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyExportAudit.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyExportAudit.java
new file mode 100644
index 0000000..fe0e542
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyExportAudit.java
@@ -0,0 +1,312 @@
+/*
+ * 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.entity;
+
+/**
+ * Audit Log for Policy Export
+ *
+ */
+
+import java.util.*;
+
+import javax.persistence.*;
+import javax.xml.bind.annotation.*;
+
+import org.apache.ranger.common.*;
+import org.apache.ranger.entity.*;
+
+
+@Entity
+@Table(name="x_policy_export_audit")
+@XmlRootElement
+public class XXPolicyExportAudit extends XXDBBase implements java.io.Serializable {
+ private static final long serialVersionUID = 1L;
+
+
+ @Id
+ @SequenceGenerator(name="X_POLICY_EXPORT_SEQ",sequenceName="X_POLICY_EXPORT_SEQ",allocationSize=1)
+ @GeneratedValue(strategy=GenerationType.AUTO,generator="X_POLICY_EXPORT_SEQ")
+ @Column(name="ID")
+ protected Long id;
+ @Override
+ public void setId(Long id) {
+ this.id=id;
+ }
+
+ @Override
+ public Long getId() {
+ return id;
+ }
+
+ /**
+ * XA Agent IP Address
+ * <ul>
+ * <li>The maximum length for this attribute is <b>255</b>.
+ * </ul>
+ *
+ */
+ @Column(name="CLIENT_IP" , nullable=false , length=255)
+ protected String clientIP;
+
+ /**
+ * XA Agent Id
+ * <ul>
+ * <li>The maximum length for this attribute is <b>255</b>.
+ * </ul>
+ *
+ */
+ @Column(name="AGENT_ID" , length=255)
+ protected String agentId;
+
+ /**
+ * Last update timestamp in request
+ * <ul>
+ * </ul>
+ *
+ */
+ @Column(name="REQ_EPOCH" , nullable=false )
+ protected Long requestedEpoch;
+
+ /**
+ * Date and time of the last policy update
+ * <ul>
+ * </ul>
+ *
+ */
+ @Temporal(TemporalType.TIMESTAMP)
+ @Column(name="LAST_UPDATED" )
+ protected Date lastUpdated;
+
+ /**
+ * Name of the Asset
+ * <ul>
+ * <li>The maximum length for this attribute is <b>1024</b>.
+ * </ul>
+ *
+ */
+ @Column(name="REPOSITORY_NAME" , length=1024)
+ protected String repositoryName;
+
+ /**
+ * JSON of the policies exported
+ * <ul>
+ * <li>The maximum length for this attribute is <b>30000</b>.
+ * </ul>
+ *
+ */
+ @Column(name="EXPORTED_JSON" , length=30000)
+ protected String exportedJson;
+
+ /**
+ * HTTP Response Code
+ * <ul>
+ * </ul>
+ *
+ */
+ @Column(name="HTTP_RET_CODE" , nullable=false )
+ protected int httpRetCode;
+
+ /**
+ * Default constructor. This will set all the attributes to default value.
+ */
+ public XXPolicyExportAudit ( ) {
+ }
+
+ @Override
+ public int getMyClassType( ) {
+ return AppConstants.CLASS_TYPE_XA_POLICY_EXPORT_AUDIT;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>clientIP</b>.
+ * You cannot set null to the attribute.
+ * @param clientIP Value to set member attribute <b>clientIP</b>
+ */
+ public void setClientIP( String clientIP ) {
+ this.clientIP = clientIP;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>clientIP</b>
+ * @return String - value of member attribute <b>clientIP</b>.
+ */
+ public String getClientIP( ) {
+ return this.clientIP;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>agentId</b>.
+ * You cannot set null to the attribute.
+ * @param agentId Value to set member attribute <b>agentId</b>
+ */
+ public void setAgentId( String agentId ) {
+ this.agentId = agentId;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>agentId</b>
+ * @return String - value of member attribute <b>agentId</b>.
+ */
+ public String getAgentId( ) {
+ return this.agentId;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>requestedEpoch</b>.
+ * You cannot set null to the attribute.
+ * @param requestedEpoch Value to set member attribute <b>requestedEpoch</b>
+ */
+ public void setRequestedEpoch( Long requestedEpoch ) {
+ this.requestedEpoch = requestedEpoch;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>requestedEpoch</b>
+ * @return Long - value of member attribute <b>requestedEpoch</b>.
+ */
+ public Long getRequestedEpoch( ) {
+ return this.requestedEpoch;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>lastUpdated</b>.
+ * You cannot set null to the attribute.
+ * @param lastUpdated Value to set member attribute <b>lastUpdated</b>
+ */
+ public void setLastUpdated( Date lastUpdated ) {
+ this.lastUpdated = lastUpdated;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>lastUpdated</b>
+ * @return Date - value of member attribute <b>lastUpdated</b>.
+ */
+ public Date getLastUpdated( ) {
+ return this.lastUpdated;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>repositoryName</b>.
+ * You cannot set null to the attribute.
+ * @param repositoryName Value to set member attribute <b>repositoryName</b>
+ */
+ public void setRepositoryName( String repositoryName ) {
+ this.repositoryName = repositoryName;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>repositoryName</b>
+ * @return String - value of member attribute <b>repositoryName</b>.
+ */
+ public String getRepositoryName( ) {
+ return this.repositoryName;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>exportedJson</b>.
+ * You cannot set null to the attribute.
+ * @param exportedJson Value to set member attribute <b>exportedJson</b>
+ */
+ public void setExportedJson( String exportedJson ) {
+ this.exportedJson = exportedJson;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>exportedJson</b>
+ * @return String - value of member attribute <b>exportedJson</b>.
+ */
+ public String getExportedJson( ) {
+ return this.exportedJson;
+ }
+
+ /**
+ * This method sets the value to the member attribute <b>httpRetCode</b>.
+ * You cannot set null to the attribute.
+ * @param httpRetCode Value to set member attribute <b>httpRetCode</b>
+ */
+ public void setHttpRetCode( int httpRetCode ) {
+ this.httpRetCode = httpRetCode;
+ }
+
+ /**
+ * Returns the value for the member attribute <b>httpRetCode</b>
+ * @return int - value of member attribute <b>httpRetCode</b>.
+ */
+ public int getHttpRetCode( ) {
+ return this.httpRetCode;
+ }
+
+ /**
+ * This return the bean content in string format
+ * @return formatedStr
+ */
+ @Override
+ public String toString( ) {
+ String str = "XXPolicyExportAudit={";
+ str += super.toString();
+ str += "clientIP={" + clientIP + "} ";
+ str += "agentId={" + agentId + "} ";
+ str += "requestedEpoch={" + requestedEpoch + "} ";
+ str += "lastUpdated={" + lastUpdated + "} ";
+ str += "repositoryName={" + repositoryName + "} ";
+ str += "exportedJson={" + exportedJson + "} ";
+ str += "httpRetCode={" + httpRetCode + "} ";
+ str += "}";
+ return str;
+ }
+
+ /**
+ * Checks for all attributes except referenced db objects
+ * @return true if all attributes match
+ */
+ @Override
+ public boolean equals( Object obj) {
+ if ( !super.equals(obj) ) {
+ return false;
+ }
+ XXPolicyExportAudit other = (XXPolicyExportAudit) obj;
+ if ((this.clientIP == null && other.clientIP != null) || (this.clientIP != null && !this.clientIP.equals(other.clientIP))) {
+ return false;
+ }
+ if ((this.agentId == null && other.agentId != null) || (this.agentId != null && !this.agentId.equals(other.agentId))) {
+ return false;
+ }
+ if ((this.requestedEpoch == null && other.requestedEpoch != null) || (this.requestedEpoch != null && !this.requestedEpoch.equals(other.requestedEpoch))) {
+ return false;
+ }
+ if ((this.lastUpdated == null && other.lastUpdated != null) || (this.lastUpdated != null && !this.lastUpdated.equals(other.lastUpdated))) {
+ return false;
+ }
+ if ((this.repositoryName == null && other.repositoryName != null) || (this.repositoryName != null && !this.repositoryName.equals(other.repositoryName))) {
+ return false;
+ }
+ if ((this.exportedJson == null && other.exportedJson != null) || (this.exportedJson != null && !this.exportedJson.equals(other.exportedJson))) {
+ return false;
+ }
+ if( this.httpRetCode != other.httpRetCode ) return false;
+ return true;
+ }
+ public static String getEnumName(String fieldName ) {
+ //Later TODO
+ //return super.getEnumName(fieldName);
+ return null;
+ }
+
+}
[48/51] [partial] incubator-ranger git commit: RANGER-194: Rename
packages from xasecure to apache ranger
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXBaseAuditEvent.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXBaseAuditEvent.java b/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXBaseAuditEvent.java
new file mode 100644
index 0000000..9293c72
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXBaseAuditEvent.java
@@ -0,0 +1,228 @@
+/*
+ * 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.audit.entity;
+
+import java.io.Serializable;
+import java.util.Date;
+
+import javax.persistence.Column;
+import javax.persistence.DiscriminatorColumn;
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.SequenceGenerator;
+import javax.persistence.Table;
+import javax.persistence.Temporal;
+import javax.persistence.TemporalType;
+
+import org.apache.ranger.audit.model.AuditEventBase;
+
+/**
+ * Entity implementation class for Entity: XABaseAuditEvent
+ *
+ */
+@Entity
+@Inheritance
+@DiscriminatorColumn(name="audit_type", discriminatorType=javax.persistence.DiscriminatorType.INTEGER, length=2)
+@DiscriminatorValue("0")
+@Table(name="xa_access_audit")
+public class XXBaseAuditEvent implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ private long auditId;
+ private String agentId;
+ private String user;
+ private Date timeStamp;
+ private long policyId;
+ private String accessType;
+ private int accessResult;
+ private String resultReason;
+ private String aclEnforcer;
+ private int repositoryType;
+ private String repositoryName;
+ private String sessionId;
+ private String clientType;
+ private String clientIP;
+ private String action;
+
+ public XXBaseAuditEvent() {
+ super();
+ }
+
+ public XXBaseAuditEvent(AuditEventBase event) {
+ this.agentId = event.getAgentId();
+ this.user = event.getUser();
+ this.timeStamp = event.getEventTime();
+ this.policyId = event.getPolicyId();
+ this.accessType = event.getAccessType();
+ this.accessResult = event.getAccessResult();
+ this.resultReason = event.getResultReason();
+ this.aclEnforcer = event.getAclEnforcer();
+ this.repositoryType = event.getRepositoryType();
+ this.repositoryName = event.getRepositoryName();
+ this.sessionId = event.getSessionId();
+ this.clientType = event.getClientType();
+ this.clientIP = event.getClientIP();
+ this.action = event.getAction();
+ }
+
+ @Id
+ @SequenceGenerator(name="XA_ACCESS_AUDIT_SEQ",sequenceName="XA_ACCESS_AUDIT_SEQ",allocationSize=1)
+ @GeneratedValue(strategy=GenerationType.AUTO,generator="XA_ACCESS_AUDIT_SEQ")
+ @Column(name = "id", unique = true, nullable = false)
+ public long getAuditId() {
+ return this.auditId;
+ }
+
+ public void setAuditId(long auditId) {
+ this.auditId = auditId;
+ }
+
+ @Column(name = "agent_id")
+ public String getAgentId() {
+ return agentId;
+ }
+
+ public void setAgentId(String agentId) {
+ this.agentId = agentId;
+ }
+
+ @Column(name = "request_user")
+ public String getUser() {
+ return this.user;
+ }
+
+ public void setUser(String user) {
+ this.user = user;
+ }
+
+ @Temporal(TemporalType.TIMESTAMP)
+ @Column(name = "event_time")
+ public Date getTimeStamp() {
+ return this.timeStamp;
+ }
+
+ public void setTimeStamp(Date timeStamp) {
+ this.timeStamp = timeStamp;
+ }
+
+ @Column(name = "policy_id")
+ public long getPolicyId() {
+ return this.policyId;
+ }
+
+ public void setPolicyId(long policyId) {
+ this.policyId = policyId;
+ }
+
+ @Column(name = "access_type")
+ public String getAccessType() {
+ return this.accessType;
+ }
+
+ public void setAccessType(String accessType) {
+ this.accessType = accessType;
+ }
+
+ @Column(name = "access_result")
+ public int getAccessResult() {
+ return this.accessResult;
+ }
+
+ public void setAccessResult(int accessResult) {
+ this.accessResult = accessResult;
+ }
+
+ @Column(name = "result_reason")
+ public String getResultReason() {
+ return this.resultReason;
+ }
+
+ public void setResultReason(String resultReason) {
+ this.resultReason = resultReason;
+ }
+
+ @Column(name = "acl_enforcer")
+ public String getAclEnforcer() {
+ return this.aclEnforcer;
+ }
+
+ public void setAclEnforcer(String aclEnforcer) {
+ this.aclEnforcer = aclEnforcer;
+ }
+
+ @Column(name = "repo_type")
+ public int getRepositoryType() {
+ return this.repositoryType ;
+ }
+
+ public void setRepositoryType(int repositoryType) {
+ this.repositoryType = repositoryType;
+ }
+
+ @Column(name = "repo_name")
+ public String getRepositoryName() {
+ return this.repositoryName;
+ }
+
+ public void setRepositoryName(String repositoryName) {
+ this.repositoryName = repositoryName;
+ }
+
+ @Column(name = "session_id")
+ public String getSessionId() {
+ return this.sessionId;
+ }
+
+ public void setSessionId(String sessionId) {
+ this.sessionId = sessionId;
+ }
+
+ @Column(name = "client_type")
+ public String getClientType() {
+ return this.clientType;
+ }
+
+ public void setClientType(String clientType) {
+ this.clientType = clientType;
+ }
+
+ @Column(name = "client_ip")
+ public String getClientIP() {
+ return this.clientIP;
+ }
+
+ public void setClientIP(String clientIP) {
+ this.clientIP = clientIP;
+ }
+
+ @Column(name = "action")
+ public String getAction() {
+ return this.action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXBaseAuditEvent_.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXBaseAuditEvent_.java b/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXBaseAuditEvent_.java
new file mode 100644
index 0000000..1e33181
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXBaseAuditEvent_.java
@@ -0,0 +1,48 @@
+/*
+ * 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.audit.entity;
+
+import java.util.Date;
+
+import javax.annotation.Generated;
+import javax.persistence.metamodel.SingularAttribute;
+import javax.persistence.metamodel.StaticMetamodel;
+
+import org.apache.ranger.audit.model.EnumRepositoryType;
+
+@Generated(value="Dali", date="2014-02-04T07:25:42.940-0800")
+@StaticMetamodel(XXBaseAuditEvent.class)
+public class XXBaseAuditEvent_ {
+ public static volatile SingularAttribute<XXBaseAuditEvent, Long> auditId;
+ public static volatile SingularAttribute<XXBaseAuditEvent, String> agentId;
+ public static volatile SingularAttribute<XXBaseAuditEvent, String> user;
+ public static volatile SingularAttribute<XXBaseAuditEvent, Date> timeStamp;
+ public static volatile SingularAttribute<XXBaseAuditEvent, Long> policyId;
+ public static volatile SingularAttribute<XXBaseAuditEvent, String> accessType;
+ public static volatile SingularAttribute<XXBaseAuditEvent, Short> accessResult;
+ public static volatile SingularAttribute<XXBaseAuditEvent, String> resultReason;
+ public static volatile SingularAttribute<XXBaseAuditEvent, String> aclEnforcer;
+ public static volatile SingularAttribute<XXBaseAuditEvent, EnumRepositoryType> repositoryType;
+ public static volatile SingularAttribute<XXBaseAuditEvent, String> repositoryName;
+ public static volatile SingularAttribute<XXBaseAuditEvent, String> sessionId;
+ public static volatile SingularAttribute<XXBaseAuditEvent, String> clientType;
+ public static volatile SingularAttribute<XXBaseAuditEvent, String> clientIP;
+ public static volatile SingularAttribute<XXBaseAuditEvent, String> action;
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXHBaseAuditEvent.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXHBaseAuditEvent.java b/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXHBaseAuditEvent.java
new file mode 100644
index 0000000..efcb37b
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXHBaseAuditEvent.java
@@ -0,0 +1,84 @@
+/*
+ * 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.audit.entity;
+
+import java.io.Serializable;
+
+import javax.persistence.Column;
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Entity;
+
+import org.apache.ranger.audit.model.EnumRepositoryType;
+import org.apache.ranger.audit.model.HBaseAuditEvent;
+
+/**
+ * Entity implementation class for Entity: XAHBaseAuditEvent
+ *
+ */
+@Entity
+@DiscriminatorValue("1")
+public class XXHBaseAuditEvent extends XXBaseAuditEvent implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ private String resourcePath;
+ private String resourceType;
+ private String requestData;
+
+
+ public XXHBaseAuditEvent() {
+ super();
+ }
+
+ public XXHBaseAuditEvent(HBaseAuditEvent event) {
+ super(event);
+
+ this.resourcePath = event.getResourcePath();
+ this.resourceType = event.getResourceType();
+ this.requestData = event.getRequestData();
+ }
+
+ @Column(name = "resource_path")
+ public String getResourcePath() {
+ return this.resourcePath;
+ }
+
+ public void setResourcePath(String resourcePath) {
+ this.resourcePath = resourcePath;
+ }
+
+ @Column(name = "resource_type")
+ public String getResourceType() {
+ return this.resourceType;
+ }
+
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ @Column(name = "request_data")
+ public String getRequestData() {
+ return this.requestData;
+ }
+
+ public void setRequestData(String requestData) {
+ this.requestData = requestData;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXHBaseAuditEvent_.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXHBaseAuditEvent_.java b/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXHBaseAuditEvent_.java
new file mode 100644
index 0000000..bbab25b
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXHBaseAuditEvent_.java
@@ -0,0 +1,32 @@
+/*
+ * 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.audit.entity;
+
+import javax.annotation.Generated;
+import javax.persistence.metamodel.SingularAttribute;
+import javax.persistence.metamodel.StaticMetamodel;
+
+@Generated(value="Dali", date="2014-02-02T14:05:13.483-0800")
+@StaticMetamodel(XXHBaseAuditEvent.class)
+public class XXHBaseAuditEvent_ extends XXBaseAuditEvent_ {
+ public static volatile SingularAttribute<XXHBaseAuditEvent, String> resourcePath;
+ public static volatile SingularAttribute<XXHBaseAuditEvent, String> resourceType;
+ public static volatile SingularAttribute<XXHBaseAuditEvent, String> requestData;
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXHdfsAuditEvent.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXHdfsAuditEvent.java b/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXHdfsAuditEvent.java
new file mode 100644
index 0000000..1bcebbe
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXHdfsAuditEvent.java
@@ -0,0 +1,75 @@
+/*
+ * 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.audit.entity;
+
+import java.io.Serializable;
+
+import javax.persistence.Column;
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Entity;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.Table;
+
+import org.apache.ranger.audit.model.HdfsAuditEvent;
+
+/**
+ * Entity implementation class for Entity: XXHdfsAuditEvent
+ *
+ */
+@Entity
+@DiscriminatorValue("2")
+public class XXHdfsAuditEvent extends XXBaseAuditEvent implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ private String resourcePath;
+ private String resourceType;
+
+
+ public XXHdfsAuditEvent() {
+ super();
+ }
+
+ public XXHdfsAuditEvent(HdfsAuditEvent event) {
+ super(event);
+
+ this.resourcePath = event.getResourcePath();
+ this.resourceType = event.getResourceType();
+ }
+
+ @Column(name = "resource_path")
+ public String getResourcePath() {
+ return this.resourcePath;
+ }
+
+ public void setResourcePath(String resourcePath) {
+ this.resourcePath = resourcePath;
+ }
+
+ @Column(name = "resource_type")
+ public String getResourceType() {
+ return this.resourceType;
+ }
+
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXHdfsAuditEvent_.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXHdfsAuditEvent_.java b/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXHdfsAuditEvent_.java
new file mode 100644
index 0000000..4f7c85e
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXHdfsAuditEvent_.java
@@ -0,0 +1,31 @@
+/*
+ * 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.audit.entity;
+
+import javax.annotation.Generated;
+import javax.persistence.metamodel.SingularAttribute;
+import javax.persistence.metamodel.StaticMetamodel;
+
+@Generated(value="Dali", date="2014-02-02T14:05:13.489-0800")
+@StaticMetamodel(XXHdfsAuditEvent.class)
+public class XXHdfsAuditEvent_ extends XXBaseAuditEvent_ {
+ public static volatile SingularAttribute<XXHdfsAuditEvent, String> resourcePath;
+ public static volatile SingularAttribute<XXHdfsAuditEvent, String> resourceType;
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXHiveAuditEvent.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXHiveAuditEvent.java b/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXHiveAuditEvent.java
new file mode 100644
index 0000000..b539be8
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXHiveAuditEvent.java
@@ -0,0 +1,86 @@
+/*
+ * 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.audit.entity;
+
+import java.io.Serializable;
+
+import javax.persistence.Column;
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Entity;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.Table;
+
+import org.apache.ranger.audit.model.HiveAuditEvent;
+
+/**
+ * Entity implementation class for Entity: XXHiveAuditEvent
+ *
+ */
+@Entity
+@DiscriminatorValue("3")
+public class XXHiveAuditEvent extends XXBaseAuditEvent implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ private String resourcePath;
+ private String resourceType;
+ private String requestData;
+
+
+ public XXHiveAuditEvent() {
+ super();
+ }
+
+ public XXHiveAuditEvent(HiveAuditEvent event) {
+ super(event);
+
+ this.resourcePath = event.getResourcePath();
+ this.resourceType = event.getResourceType();
+ this.requestData = event.getRequestData();
+ }
+
+ @Column(name = "resource_path")
+ public String getResourcePath() {
+ return this.resourcePath;
+ }
+
+ public void setResourcePath(String resourcePath) {
+ this.resourcePath = resourcePath;
+ }
+
+ @Column(name = "resource_type")
+ public String getResourceType() {
+ return this.resourceType;
+ }
+
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ @Column(name = "request_data")
+ public String getRequestData() {
+ return this.requestData;
+ }
+
+ public void setRequestData(String requestData) {
+ this.requestData = requestData;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXHiveAuditEvent_.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXHiveAuditEvent_.java b/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXHiveAuditEvent_.java
new file mode 100644
index 0000000..2c4eea5
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXHiveAuditEvent_.java
@@ -0,0 +1,32 @@
+/*
+ * 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.audit.entity;
+
+import javax.annotation.Generated;
+import javax.persistence.metamodel.SingularAttribute;
+import javax.persistence.metamodel.StaticMetamodel;
+
+@Generated(value="Dali", date="2014-02-02T14:05:13.494-0800")
+@StaticMetamodel(XXHiveAuditEvent.class)
+public class XXHiveAuditEvent_ extends XXBaseAuditEvent_ {
+ public static volatile SingularAttribute<XXHiveAuditEvent, String> resourcePath;
+ public static volatile SingularAttribute<XXHiveAuditEvent, String> resourceType;
+ public static volatile SingularAttribute<XXHiveAuditEvent, String> requestData;
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXKnoxAuditEvent.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXKnoxAuditEvent.java b/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXKnoxAuditEvent.java
new file mode 100644
index 0000000..57fa105
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXKnoxAuditEvent.java
@@ -0,0 +1,82 @@
+/**
+ * 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.audit.entity;
+
+import java.io.Serializable;
+
+import javax.persistence.Column;
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Entity;
+
+import org.apache.ranger.audit.model.KnoxAuditEvent;
+
+/**
+ * Entity implementation class for Entity: XXHiveAuditEvent
+ *
+ */
+@Entity
+@DiscriminatorValue("4")
+public class XXKnoxAuditEvent extends XXBaseAuditEvent implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ private String resourcePath;
+ private String resourceType;
+ private String requestData;
+
+
+ public XXKnoxAuditEvent() {
+ super();
+ }
+
+ public XXKnoxAuditEvent(KnoxAuditEvent event) {
+ super(event);
+
+ this.resourcePath = event.getResourcePath();
+ this.resourceType = event.getResourceType();
+ this.requestData = event.getRequestData();
+ }
+
+ @Column(name = "resource_path")
+ public String getResourcePath() {
+ return this.resourcePath;
+ }
+
+ public void setResourcePath(String resourcePath) {
+ this.resourcePath = resourcePath;
+ }
+
+ @Column(name = "resource_type")
+ public String getResourceType() {
+ return this.resourceType;
+ }
+
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ @Column(name = "request_data")
+ public String getRequestData() {
+ return this.requestData;
+ }
+
+ public void setRequestData(String requestData) {
+ this.requestData = requestData;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXStormAuditEvent.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXStormAuditEvent.java b/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXStormAuditEvent.java
new file mode 100644
index 0000000..9ffc6fb
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/entity/XXStormAuditEvent.java
@@ -0,0 +1,82 @@
+/**
+ * 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.audit.entity;
+
+import java.io.Serializable;
+
+import javax.persistence.Column;
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Entity;
+
+import org.apache.ranger.audit.model.StormAuditEvent;
+
+/**
+ * Entity implementation class for Entity: XXHiveAuditEvent
+ *
+ */
+@Entity
+@DiscriminatorValue("5")
+public class XXStormAuditEvent extends XXBaseAuditEvent implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ private String resourcePath;
+ private String resourceType;
+ private String requestData;
+
+
+ public XXStormAuditEvent() {
+ super();
+ }
+
+ public XXStormAuditEvent(StormAuditEvent event) {
+ super(event);
+
+ this.resourcePath = event.getResourcePath();
+ this.resourceType = event.getResourceType();
+ this.requestData = event.getRequestData();
+ }
+
+ @Column(name = "resource_path")
+ public String getResourcePath() {
+ return this.resourcePath;
+ }
+
+ public void setResourcePath(String resourcePath) {
+ this.resourcePath = resourcePath;
+ }
+
+ @Column(name = "resource_type")
+ public String getResourceType() {
+ return this.resourceType;
+ }
+
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ @Column(name = "request_data")
+ public String getRequestData() {
+ return this.requestData;
+ }
+
+ public void setRequestData(String requestData) {
+ this.requestData = requestData;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/model/AuditEventBase.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/model/AuditEventBase.java b/agents-audit/src/main/java/org/apache/ranger/audit/model/AuditEventBase.java
new file mode 100644
index 0000000..0a5663e
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/model/AuditEventBase.java
@@ -0,0 +1,378 @@
+/*
+ * 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.audit.model;
+
+import java.util.Date;
+
+import org.apache.ranger.audit.dao.DaoManager;
+
+import com.google.gson.annotations.SerializedName;
+
+
+public abstract class AuditEventBase {
+ protected static String FIELD_SEPARATOR = ";";
+
+ protected static final int MAX_ACTION_FIELD_SIZE = 1800 ;
+ protected static final int MAX_REQUEST_DATA_FIELD_SIZE = 1800 ;
+
+
+ @SerializedName("agent")
+ protected String agentId = null;
+
+ @SerializedName("reqUser")
+ protected String user = null;
+
+ @SerializedName("evtTime")
+ protected Date eventTime = new Date();
+
+ @SerializedName("policy")
+ protected long policyId = 0;
+
+ @SerializedName("access")
+ protected String accessType = null;
+
+ @SerializedName("result")
+ protected short accessResult = 0; // 0 - DENIED; 1 - ALLOWED; HTTP return code
+
+ @SerializedName("reason")
+ protected String resultReason = null;
+
+ @SerializedName("enforcer")
+ protected String aclEnforcer = null;
+
+ @SerializedName("repoType")
+ protected int repositoryType = 0;
+
+ @SerializedName("repo")
+ protected String repositoryName = null;
+
+ @SerializedName("sess")
+ protected String sessionId = null;
+
+ @SerializedName("cliType")
+ protected String clientType = null;
+
+ @SerializedName("cliIP")
+ protected String clientIP = null;
+
+ @SerializedName("action")
+ protected String action = null;
+
+ @SerializedName("agentHost")
+ protected String agentHostname = null;
+
+ @SerializedName("logType")
+ protected String logType = null;
+
+ @SerializedName("id")
+ protected String eventId = null;
+
+ protected AuditEventBase() {
+ }
+
+ protected AuditEventBase(String agentId,
+ String user,
+ Date eventTime,
+ long policyId,
+ String accessType,
+ short accessResult,
+ String resultReason,
+ String aclEnforcer,
+ int repositoryType,
+ String repositoryName,
+ String sessionId,
+ String clientType,
+ String clientIP,
+ String action) {
+ this.agentId = agentId;
+ this.user = user;
+ this.eventTime = eventTime;
+ this.policyId = policyId;
+ this.accessType = accessType;
+ this.accessResult = accessResult;
+ this.resultReason = resultReason;
+ this.aclEnforcer = aclEnforcer;
+ this.repositoryType = repositoryType;
+ this.repositoryName = repositoryName;
+ this.sessionId = sessionId;
+ this.clientType = clientType;
+ this.clientIP = clientIP;
+ this.action = action;
+ }
+
+ /**
+ * @return the agentId
+ */
+ public String getAgentId() {
+ return agentId;
+ }
+
+ /**
+ * @param agentId the agentId to set
+ */
+ public void setAgentId(String agentId) {
+ this.agentId = agentId;
+ }
+
+ /**
+ * @return the user
+ */
+ public String getUser() {
+ return user;
+ }
+
+ /**
+ * @param user the user to set
+ */
+ public void setUser(String user) {
+ this.user = user;
+ }
+
+ /**
+ * @return the timeStamp
+ */
+ public Date getEventTime() {
+ return eventTime;
+ }
+
+ /**
+ * @param timeStamp the timeStamp to set
+ */
+ public void setEventTime(Date eventTime) {
+ this.eventTime = eventTime;
+ }
+
+ /**
+ * @return the policyId
+ */
+ public long getPolicyId() {
+ return policyId;
+ }
+
+ /**
+ * @param policyId the policyId to set
+ */
+ public void setPolicyId(long policyId) {
+ this.policyId = policyId;
+ }
+
+ /**
+ * @return the accessType
+ */
+ public String getAccessType() {
+ return accessType;
+ }
+
+ /**
+ * @param accessType the accessType to set
+ */
+ public void setAccessType(String accessType) {
+ this.accessType = accessType;
+ }
+
+ /**
+ * @return the accessResult
+ */
+ public short getAccessResult() {
+ return accessResult;
+ }
+
+ /**
+ * @param accessResult the accessResult to set
+ */
+ public void setAccessResult(short accessResult) {
+ this.accessResult = accessResult;
+ }
+
+ /**
+ * @return the resultReason
+ */
+ public String getResultReason() {
+ return resultReason;
+ }
+
+ /**
+ * @param resultReason the resultReason to set
+ */
+ public void setResultReason(String resultReason) {
+ this.resultReason = resultReason;
+ }
+
+ /**
+ * @return the aclEnforcer
+ */
+ public String getAclEnforcer() {
+ return aclEnforcer;
+ }
+
+ /**
+ * @param aclEnforcer the aclEnforcer to set
+ */
+ public void setAclEnforcer(String aclEnforcer) {
+ this.aclEnforcer = aclEnforcer;
+ }
+
+ /**
+ * @return the repositoryType
+ */
+ public int getRepositoryType() {
+ return repositoryType;
+ }
+
+ /**
+ * @param repositoryType the repositoryType to set
+ */
+ public void setRepositoryType(int repositoryType) {
+ this.repositoryType = repositoryType;
+ }
+
+ /**
+ * @return the repositoryName
+ */
+ public String getRepositoryName() {
+ return repositoryName;
+ }
+
+ /**
+ * @param repositoryName the repositoryName to set
+ */
+ public void setRepositoryName(String repositoryName) {
+ this.repositoryName = repositoryName;
+ }
+
+ /**
+ * @return the sessionId
+ */
+ public String getSessionId() {
+ return sessionId;
+ }
+
+ /**
+ * @param sessionId the sessionId to set
+ */
+ public void setSessionId(String sessionId) {
+ this.sessionId = sessionId;
+ }
+
+ /**
+ * @return the clientType
+ */
+ public String getClientType() {
+ return clientType;
+ }
+
+ /**
+ * @param clientType the clientType to set
+ */
+ public void setClientType(String clientType) {
+ this.clientType = clientType;
+ }
+
+ /**
+ * @return the clientIP
+ */
+ public String getClientIP() {
+ return clientIP;
+ }
+
+ /**
+ * @param clientIP the clientIP to set
+ */
+ public void setClientIP(String clientIP) {
+ this.clientIP = clientIP;
+ }
+
+ /**
+ * @return the action
+ */
+ public String getAction() {
+ return trim(action,MAX_ACTION_FIELD_SIZE) ;
+ }
+
+ /**
+ * @param action the action to set
+ */
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getAgentHostname() {
+ return agentHostname;
+ }
+
+ public void setAgentHostname(String agentHostname) {
+ this.agentHostname = agentHostname;
+ }
+
+ public String getLogType() {
+ return logType;
+ }
+
+ public void setLogType(String logType) {
+ this.logType = logType;
+ }
+
+ public String getEventId() {
+ return eventId;
+ }
+
+ public void setEventId(String eventId) {
+ this.eventId = eventId;
+ }
+
+ public abstract void persist(DaoManager daoManager);
+
+ @Override
+ public String toString() {
+ return toString(new StringBuilder()).toString();
+ }
+
+ protected StringBuilder toString(StringBuilder sb) {
+ sb.append("agentId=").append(agentId).append(FIELD_SEPARATOR)
+ .append("user=").append(user).append(FIELD_SEPARATOR)
+ .append("eventTime=").append(eventTime).append(FIELD_SEPARATOR)
+ .append("policyId=").append(policyId).append(FIELD_SEPARATOR)
+ .append("accessType=").append(accessType).append(FIELD_SEPARATOR)
+ .append("accessResult=").append(accessResult).append(FIELD_SEPARATOR)
+ .append("resultReason=").append(resultReason).append(FIELD_SEPARATOR)
+ .append("aclEnforcer=").append(aclEnforcer).append(FIELD_SEPARATOR)
+ .append("repositoryType=").append(repositoryType).append(FIELD_SEPARATOR)
+ .append("repositoryName=").append(repositoryName).append(FIELD_SEPARATOR)
+ .append("sessionId=").append(sessionId).append(FIELD_SEPARATOR)
+ .append("clientType=").append(clientType).append(FIELD_SEPARATOR)
+ .append("clientIP=").append(clientIP).append(FIELD_SEPARATOR)
+ .append("action=").append(action).append(FIELD_SEPARATOR)
+ .append("agentHostname=").append(agentHostname).append(FIELD_SEPARATOR)
+ .append("logType=").append(logType).append(FIELD_SEPARATOR)
+ .append("eventId=").append(eventId).append(FIELD_SEPARATOR)
+ ;
+ return sb;
+ }
+
+ protected String trim(String str, int len) {
+ String ret = str ;
+ if (str != null) {
+ if (str.length() > len) {
+ ret = str.substring(0,len) ;
+ }
+ }
+ return ret ;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/model/EnumRepositoryType.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/model/EnumRepositoryType.java b/agents-audit/src/main/java/org/apache/ranger/audit/model/EnumRepositoryType.java
new file mode 100644
index 0000000..92456a2
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/model/EnumRepositoryType.java
@@ -0,0 +1,37 @@
+/*
+ * 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.audit.model;
+
+public final class EnumRepositoryType {
+
+ public static final int HDFS = 1 ;
+
+ public static final int HBASE = 2 ;
+
+ public static final int HIVE = 3 ;
+
+ public static final int XAAGENT = 4 ;
+
+ public static final int KNOX = 5;
+
+ public static final int STORM = 6 ;
+
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/model/HBaseAuditEvent.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/model/HBaseAuditEvent.java b/agents-audit/src/main/java/org/apache/ranger/audit/model/HBaseAuditEvent.java
new file mode 100644
index 0000000..2a07fc0
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/model/HBaseAuditEvent.java
@@ -0,0 +1,128 @@
+/*
+ * 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.audit.model;
+
+import java.util.Date;
+
+import org.apache.ranger.audit.dao.DaoManager;
+import org.apache.ranger.audit.entity.XXHBaseAuditEvent;
+
+import com.google.gson.annotations.SerializedName;
+
+
+public class HBaseAuditEvent extends AuditEventBase {
+ @SerializedName("resource")
+ protected String resourcePath;
+
+ @SerializedName("resType")
+ protected String resourceType;
+
+ @SerializedName("reqData")
+ protected String requestData;
+
+ public HBaseAuditEvent() {
+ this.repositoryType = EnumRepositoryType.HBASE;
+ }
+
+ public HBaseAuditEvent(String agentId,
+ String user,
+ Date eventTime,
+ long policyId,
+ String accessType,
+ short accessResult,
+ String resultReason,
+ String aclEnforcer,
+ int repositoryType,
+ String repositoryName,
+ String sessionId,
+ String clientType,
+ String clientIP,
+ String resourcePath,
+ String resourceType,
+ String requestData,
+ String action) {
+ super(agentId, user, eventTime, policyId, accessType, accessResult, resultReason, aclEnforcer, repositoryType, repositoryName, sessionId, clientType, clientIP, action);
+
+ this.resourcePath = resourcePath;
+ this.resourceType = resourceType;
+ this.requestData = requestData;
+ }
+
+ /**
+ * @return the resourcePath
+ */
+ public String getResourcePath() {
+ return resourcePath;
+ }
+
+ /**
+ * @param resourcePath the resourcePath to set
+ */
+ public void setResourcePath(String resourcePath) {
+ this.resourcePath = resourcePath;
+ }
+
+ /**
+ * @return the resourceType
+ */
+ public String getResourceType() {
+ return resourceType;
+ }
+
+ /**
+ * @param resourceType the resourceType to set
+ */
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ /**
+ * @return the requestData
+ */
+ public String getRequestData() {
+ return trim(requestData,MAX_REQUEST_DATA_FIELD_SIZE) ;
+ }
+
+ /**
+ * @param requestData the requestData to set
+ */
+ public void setRequestData(String requestData) {
+ this.requestData = requestData;
+ }
+
+ @Override
+ public void persist(DaoManager daoManager) {
+ daoManager.getXAHBaseAuditEventDao().create(new XXHBaseAuditEvent(this));
+ }
+
+ @Override
+ protected StringBuilder toString(StringBuilder sb) {
+ sb.append("HBaseAuditEvent{");
+
+ super.toString(sb)
+ .append("resourcePath=").append(resourcePath).append(FIELD_SEPARATOR)
+ .append("resourceType=").append(resourceType).append(FIELD_SEPARATOR)
+ .append("requestData=").append(requestData).append(FIELD_SEPARATOR);
+
+ sb.append("}");
+
+ return sb;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/model/HdfsAuditEvent.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/model/HdfsAuditEvent.java b/agents-audit/src/main/java/org/apache/ranger/audit/model/HdfsAuditEvent.java
new file mode 100644
index 0000000..631c6a9
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/model/HdfsAuditEvent.java
@@ -0,0 +1,107 @@
+/*
+ * 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.audit.model;
+
+import java.util.Date;
+
+import org.apache.ranger.audit.dao.DaoManager;
+import org.apache.ranger.audit.entity.XXHdfsAuditEvent;
+
+import com.google.gson.annotations.SerializedName;
+
+public class HdfsAuditEvent extends AuditEventBase {
+ @SerializedName("resource")
+ protected String resourcePath;
+
+ @SerializedName("resType")
+ protected String resourceType;
+
+ public HdfsAuditEvent() {
+ this.repositoryType = EnumRepositoryType.HDFS;
+ }
+
+ public HdfsAuditEvent(String agentId,
+ String user,
+ Date eventTime,
+ long policyId,
+ String accessType,
+ short accessResult,
+ String resultReason,
+ String aclEnforcer,
+ int repositoryType,
+ String repositoryName,
+ String sessionId,
+ String clientType,
+ String clientIP,
+ String resourcePath,
+ String resourceType,
+ String action) {
+ super(agentId, user, eventTime, policyId, accessType, accessResult, resultReason, aclEnforcer, repositoryType, repositoryName, sessionId, clientType, clientIP, action);
+
+ this.resourcePath = resourcePath;
+ this.resourceType = resourceType;
+ }
+
+ /**
+ * @return the resourcePath
+ */
+ public String getResourcePath() {
+ return resourcePath;
+ }
+
+ /**
+ * @param resourcePath the resourcePath to set
+ */
+ public void setResourcePath(String resourcePath) {
+ this.resourcePath = resourcePath;
+ }
+
+ /**
+ * @return the resourceType
+ */
+ public String getResourceType() {
+ return resourceType;
+ }
+
+ /**
+ * @param resourceType the resourceType to set
+ */
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ @Override
+ public void persist(DaoManager daoManager) {
+ daoManager.getXAHdfsAuditEventDao().create(new XXHdfsAuditEvent(this));
+ }
+
+ @Override
+ protected StringBuilder toString(StringBuilder sb) {
+ sb.append("HdfsAuditEvent{");
+
+ super.toString(sb)
+ .append("resourcePath=").append(resourcePath).append(FIELD_SEPARATOR)
+ .append("resourceType=").append(resourceType).append(FIELD_SEPARATOR);
+
+ sb.append("}");
+
+ return sb;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/model/HiveAuditEvent.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/model/HiveAuditEvent.java b/agents-audit/src/main/java/org/apache/ranger/audit/model/HiveAuditEvent.java
new file mode 100644
index 0000000..2d3ffb1
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/model/HiveAuditEvent.java
@@ -0,0 +1,127 @@
+/*
+ * 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.audit.model;
+
+import java.util.Date;
+
+import org.apache.ranger.audit.dao.DaoManager;
+import org.apache.ranger.audit.entity.XXHiveAuditEvent;
+
+import com.google.gson.annotations.SerializedName;
+
+public class HiveAuditEvent extends AuditEventBase {
+ @SerializedName("resource")
+ protected String resourcePath;
+
+ @SerializedName("resType")
+ protected String resourceType;
+
+ @SerializedName("reqData")
+ protected String requestData;
+
+ public HiveAuditEvent() {
+ this.repositoryType = EnumRepositoryType.HIVE;
+ }
+
+ public HiveAuditEvent(String agentId,
+ String user,
+ Date eventTime,
+ long policyId,
+ String accessType,
+ short accessResult,
+ String resultReason,
+ String aclEnforcer,
+ int repositoryType,
+ String repositoryName,
+ String sessionId,
+ String clientType,
+ String clientIP,
+ String resourcePath,
+ String resourceType,
+ String requestData,
+ String action) {
+ super(agentId, user, eventTime, policyId, accessType, accessResult, resultReason, aclEnforcer, repositoryType, repositoryName, sessionId, clientType, clientIP, action);
+
+ this.resourcePath = resourcePath;
+ this.resourceType = resourceType;
+ this.requestData = requestData;
+ }
+
+ /**
+ * @return the resourcePath
+ */
+ public String getResourcePath() {
+ return resourcePath;
+ }
+
+ /**
+ * @param resourcePath the resourcePath to set
+ */
+ public void setResourcePath(String resourcePath) {
+ this.resourcePath = resourcePath;
+ }
+
+ /**
+ * @return the resourceType
+ */
+ public String getResourceType() {
+ return resourceType;
+ }
+
+ /**
+ * @param resourceType the resourceType to set
+ */
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ /**
+ * @return the requestData
+ */
+ public String getRequestData() {
+ return trim(requestData,MAX_REQUEST_DATA_FIELD_SIZE);
+ }
+
+ /**
+ * @param requestData the requestData to set
+ */
+ public void setRequestData(String requestData) {
+ this.requestData = requestData;
+ }
+
+ @Override
+ public void persist(DaoManager daoManager) {
+ daoManager.getXAHiveAuditEventDao().create(new XXHiveAuditEvent(this));
+ }
+
+ @Override
+ protected StringBuilder toString(StringBuilder sb) {
+ sb.append("HiveAuditEvent{");
+
+ super.toString(sb)
+ .append("resourcePath=").append(resourcePath).append(FIELD_SEPARATOR)
+ .append("resourceType=").append(resourceType).append(FIELD_SEPARATOR)
+ .append("requestData=").append(requestData).append(FIELD_SEPARATOR);
+
+ sb.append("}");
+
+ return sb;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/model/KnoxAuditEvent.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/model/KnoxAuditEvent.java b/agents-audit/src/main/java/org/apache/ranger/audit/model/KnoxAuditEvent.java
new file mode 100644
index 0000000..d4d6e0a
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/model/KnoxAuditEvent.java
@@ -0,0 +1,98 @@
+package org.apache.ranger.audit.model;
+
+import org.apache.ranger.audit.dao.DaoManager;
+import org.apache.ranger.audit.entity.XXKnoxAuditEvent;
+
+import com.google.gson.annotations.SerializedName;
+
+/**
+ * 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.
+ */
+
+public class KnoxAuditEvent extends AuditEventBase {
+ @SerializedName("resource")
+ protected String resourcePath;
+
+ @SerializedName("resType")
+ protected String resourceType;
+
+ @SerializedName("reqData")
+ protected String requestData;
+
+ public KnoxAuditEvent() {
+ this.repositoryType = EnumRepositoryType.KNOX;
+ }
+
+ /**
+ * @return the resourcePath
+ */
+ public String getResourcePath() {
+ return resourcePath;
+ }
+
+ /**
+ * @param resourcePath the resourcePath to set
+ */
+ public void setResourcePath(String resourcePath) {
+ this.resourcePath = resourcePath;
+ }
+
+ /**
+ * @return the resourceType
+ */
+ public String getResourceType() {
+ return resourceType;
+ }
+
+ /**
+ * @param resourceType the resourceType to set
+ */
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ /**
+ * @return the requestData
+ */
+ public String getRequestData() {
+ return trim(requestData, MAX_REQUEST_DATA_FIELD_SIZE);
+ }
+
+ /**
+ * @param requestData
+ * the requestData to set
+ */
+ public void setRequestData(String requestData) {
+ this.requestData = requestData;
+ }
+
+ @Override
+ public void persist(DaoManager daoManager) {
+ daoManager.getXAKnoxAuditEventDao().create(new XXKnoxAuditEvent(this));
+ }
+
+ @Override
+ protected StringBuilder toString(StringBuilder sb) {
+ sb.append("KnoxAuditEvent{");
+
+ super.toString(sb).append("requestData=")
+ .append(requestData).append(FIELD_SEPARATOR);
+
+ sb.append("}");
+
+ return sb;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/model/StormAuditEvent.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/model/StormAuditEvent.java b/agents-audit/src/main/java/org/apache/ranger/audit/model/StormAuditEvent.java
new file mode 100644
index 0000000..264b123
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/model/StormAuditEvent.java
@@ -0,0 +1,98 @@
+package org.apache.ranger.audit.model;
+
+import org.apache.ranger.audit.dao.DaoManager;
+import org.apache.ranger.audit.entity.XXStormAuditEvent;
+
+import com.google.gson.annotations.SerializedName;
+
+/**
+ * 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.
+ */
+
+public class StormAuditEvent extends AuditEventBase {
+ @SerializedName("resource")
+ protected String resourcePath;
+
+ @SerializedName("resType")
+ protected String resourceType;
+
+ @SerializedName("reqData")
+ protected String requestData;
+
+ public StormAuditEvent() {
+ this.repositoryType = EnumRepositoryType.STORM;
+ }
+
+ /**
+ * @return the resourcePath
+ */
+ public String getResourcePath() {
+ return resourcePath;
+ }
+
+ /**
+ * @param resourcePath the resourcePath to set
+ */
+ public void setResourcePath(String resourcePath) {
+ this.resourcePath = resourcePath;
+ }
+
+ /**
+ * @return the resourceType
+ */
+ public String getResourceType() {
+ return resourceType;
+ }
+
+ /**
+ * @param resourceType the resourceType to set
+ */
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ /**
+ * @return the requestData
+ */
+ public String getRequestData() {
+ return trim(requestData, MAX_REQUEST_DATA_FIELD_SIZE);
+ }
+
+ /**
+ * @param requestData
+ * the requestData to set
+ */
+ public void setRequestData(String requestData) {
+ this.requestData = requestData;
+ }
+
+ @Override
+ public void persist(DaoManager daoManager) {
+ daoManager.getXAStormAuditEventDao().create(new XXStormAuditEvent(this));
+ }
+
+ @Override
+ protected StringBuilder toString(StringBuilder sb) {
+ sb.append("StormAuditEvent{");
+
+ super.toString(sb).append("requestData=")
+ .append(requestData).append(FIELD_SEPARATOR);
+
+ sb.append("}");
+
+ return sb;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/provider/AsyncAuditProvider.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/AsyncAuditProvider.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/AsyncAuditProvider.java
new file mode 100644
index 0000000..2f90642
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/AsyncAuditProvider.java
@@ -0,0 +1,271 @@
+/*
+ * 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.audit.provider;
+
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.Properties;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.audit.model.AuditEventBase;
+
+public class AsyncAuditProvider extends MultiDestAuditProvider implements
+ Runnable {
+
+ private static final Log LOG = LogFactory.getLog(AsyncAuditProvider.class);
+
+ private static int sThreadCount = 0;
+
+ private BlockingQueue<AuditEventBase> mQueue = null;
+ private Thread mThread = null;
+ private boolean mStopThread = false;
+ private String mName = null;
+ private int mMaxQueueSize = 10 * 1024;
+ private int mMaxFlushInterval = 5000; // 5 seconds
+
+ // Summary of logs handled
+ private AtomicLong lifeTimeInLogCount = new AtomicLong(0); // Total count, including drop count
+ private AtomicLong lifeTimeOutLogCount = new AtomicLong(0);
+ private AtomicLong lifeTimeDropCount = new AtomicLong(0);
+ private AtomicLong intervalInLogCount = new AtomicLong(0);
+ private AtomicLong intervalOutLogCount = new AtomicLong(0);
+ private AtomicLong intervalDropCount = new AtomicLong(0);
+ private long lastIntervalLogTime = System.currentTimeMillis();
+ private int intervalLogDurationMS = 60000;
+
+ public AsyncAuditProvider(String name, int maxQueueSize, int maxFlushInterval) {
+ LOG.info("AsyncAuditProvider(" + name + "): creating..");
+
+ if(maxQueueSize < 1) {
+ LOG.warn("AsyncAuditProvider(" + name + "): invalid maxQueueSize=" + maxQueueSize + ". will use default " + mMaxQueueSize);
+
+ maxQueueSize = mMaxQueueSize;
+ }
+
+ mName = name;
+ mMaxQueueSize = maxQueueSize;
+ mMaxFlushInterval = maxFlushInterval;
+
+ mQueue = new ArrayBlockingQueue<AuditEventBase>(mMaxQueueSize);
+ }
+
+ public AsyncAuditProvider(String name, int maxQueueSize, int maxFlushInterval, AuditProvider provider) {
+ this(name, maxQueueSize, maxFlushInterval);
+
+ addAuditProvider(provider);
+ }
+
+ @Override
+ public void init(Properties props) {
+ LOG.info("AsyncAuditProvider(" + mName + ").init()");
+
+ super.init(props);
+ }
+
+ public int getIntervalLogDurationMS() {
+ return intervalLogDurationMS;
+ }
+
+ public void setIntervalLogDurationMS(int intervalLogDurationMS) {
+ this.intervalLogDurationMS = intervalLogDurationMS;
+ }
+
+ @Override
+ public void log(AuditEventBase event) {
+ LOG.debug("AsyncAuditProvider.logEvent(AuditEventBase)");
+
+ queueEvent(event);
+ }
+
+ @Override
+ public void start() {
+ mThread = new Thread(this, "AsyncAuditProvider" + (++sThreadCount));
+
+ mThread.setDaemon(true);
+ mThread.start();
+
+ super.start();
+ }
+
+ @Override
+ public void stop() {
+ mStopThread = true;
+
+ try {
+ mThread.join();
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ super.stop();
+ }
+
+ @Override
+ public void waitToComplete() {
+ waitToComplete(0);
+
+ super.waitToComplete();
+ }
+
+ @Override
+ public void run() {
+ LOG.info("==> AsyncAuditProvider.run()");
+
+ while (!mStopThread) {
+ AuditEventBase event = null;
+ try {
+ event = dequeueEvent();
+
+ if (event != null) {
+ super.log(event);
+ } else {
+ flush();
+ }
+ } catch (Exception excp) {
+ logFailedEvent(event, excp);
+ }
+ }
+
+ try {
+ flush();
+ } catch (Exception excp) {
+ LOG.error("AsyncAuditProvider.run()", excp);
+ }
+
+ LOG.info("<== AsyncAuditProvider.run()");
+ }
+
+ private void queueEvent(AuditEventBase event) {
+ // Increase counts
+ lifeTimeInLogCount.incrementAndGet();
+ intervalInLogCount.incrementAndGet();
+
+ if(! mQueue.offer(event)) {
+ lifeTimeDropCount.incrementAndGet();
+ intervalDropCount.incrementAndGet();
+ }
+ }
+
+ private AuditEventBase dequeueEvent() {
+ AuditEventBase ret = mQueue.poll();
+
+ try {
+ while(ret == null && !mStopThread) {
+ logSummaryIfRequired();
+
+ if (mMaxFlushInterval > 0 && isFlushPending()) {
+ long timeTillNextFlush = getTimeTillNextFlush();
+
+ if (timeTillNextFlush <= 0) {
+ break; // force flush
+ }
+
+ ret = mQueue.poll(timeTillNextFlush, TimeUnit.MILLISECONDS);
+ } else {
+ // Let's wake up for summary logging
+ long waitTime = intervalLogDurationMS - (System.currentTimeMillis() - lastIntervalLogTime);
+ waitTime = waitTime <= 0 ? intervalLogDurationMS : waitTime;
+
+ ret = mQueue.poll(waitTime, TimeUnit.MILLISECONDS);
+ }
+ }
+ } catch(InterruptedException excp) {
+ LOG.error("AsyncAuditProvider.dequeueEvent()", excp);
+ }
+
+ if(ret != null) {
+ lifeTimeOutLogCount.incrementAndGet();
+ intervalOutLogCount.incrementAndGet();
+ }
+
+ logSummaryIfRequired();
+
+ return ret;
+ }
+
+ private void logSummaryIfRequired() {
+ long intervalSinceLastLog = System.currentTimeMillis() - lastIntervalLogTime;
+
+ if (intervalSinceLastLog > intervalLogDurationMS) {
+ if (intervalInLogCount.get() > 0 || intervalOutLogCount.get() > 0 ) {
+ long queueSize = mQueue.size();
+
+ LOG.info("AsyncAuditProvider-stats:" + mName + ": past " + formatIntervalForLog(intervalSinceLastLog)
+ + ": inLogs=" + intervalInLogCount.get()
+ + ", outLogs=" + intervalOutLogCount.get()
+ + ", dropped=" + intervalDropCount.get()
+ + ", currentQueueSize=" + queueSize);
+
+ LOG.info("AsyncAuditProvider-stats:" + mName + ": process lifetime"
+ + ": inLogs=" + lifeTimeInLogCount.get()
+ + ", outLogs=" + lifeTimeOutLogCount.get()
+ + ", dropped=" + lifeTimeDropCount.get());
+ }
+
+ lastIntervalLogTime = System.currentTimeMillis();
+ intervalInLogCount.set(0);
+ intervalOutLogCount.set(0);
+ intervalDropCount.set(0);
+ }
+ }
+
+ private boolean isEmpty() {
+ return mQueue.isEmpty();
+ }
+
+ private void waitToComplete(long maxWaitSeconds) {
+ LOG.debug("==> AsyncAuditProvider.waitToComplete()");
+
+ for (long waitTime = 0; !isEmpty()
+ && (maxWaitSeconds <= 0 || maxWaitSeconds > waitTime); waitTime++) {
+ try {
+ Thread.sleep(1000);
+ } catch (Exception excp) {
+ // ignore
+ }
+ }
+
+ LOG.debug("<== AsyncAuditProvider.waitToComplete()");
+ }
+
+ private long getTimeTillNextFlush() {
+ long timeTillNextFlush = mMaxFlushInterval;
+
+ if (mMaxFlushInterval > 0) {
+ long lastFlushTime = getLastFlushTime();
+
+ if (lastFlushTime != 0) {
+ long timeSinceLastFlush = System.currentTimeMillis()
+ - lastFlushTime;
+
+ if (timeSinceLastFlush >= mMaxFlushInterval)
+ timeTillNextFlush = 0;
+ else
+ timeTillNextFlush = mMaxFlushInterval - timeSinceLastFlush;
+ }
+ }
+
+ return timeTillNextFlush;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/provider/AuditProvider.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/AuditProvider.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/AuditProvider.java
new file mode 100644
index 0000000..47c2d7f
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/AuditProvider.java
@@ -0,0 +1,36 @@
+/**
+ * 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.audit.provider;
+
+import java.util.Properties;
+
+import org.apache.ranger.audit.model.AuditEventBase;
+
+public interface AuditProvider {
+ public void log(AuditEventBase event);
+
+ public void init(Properties prop);
+ public void start();
+ public void stop();
+ public void waitToComplete();
+
+ public boolean isFlushPending();
+ public long getLastFlushTime();
+ public void flush();
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/provider/AuditProviderFactory.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/AuditProviderFactory.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/AuditProviderFactory.java
new file mode 100644
index 0000000..cddf546
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/AuditProviderFactory.java
@@ -0,0 +1,242 @@
+/**
+ * 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.audit.provider;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.audit.provider.hdfs.HdfsAuditProvider;
+
+
+/*
+ * TODO:
+ * 1) Flag to enable/disable audit logging
+ * 2) Failed path to be recorded
+ * 3) Repo name, repo type from configuration
+ */
+
+public class AuditProviderFactory {
+
+ public enum ApplicationType { Unknown, Hdfs, HiveCLI, HiveServer2, HBaseMaster, HBaseRegionalServer, Knox, Storm };
+
+ private static final Log LOG = LogFactory.getLog(AuditProviderFactory.class);
+
+ private static final String AUDIT_IS_ENABLED_PROP = "xasecure.audit.is.enabled" ;
+ private static final String AUDIT_DB_IS_ENABLED_PROP = "xasecure.audit.db.is.enabled" ;
+ private static final String AUDIT_HDFS_IS_ENABLED_PROP = "xasecure.audit.hdfs.is.enabled";
+ private static final String AUDIT_LOG4J_IS_ENABLED_PROP = "xasecure.audit.log4j.is.enabled" ;
+
+ private static final int AUDIT_ASYNC_MAX_QUEUE_SIZE_DEFAULT = 10 * 1024;
+ private static final int AUDIT_ASYNC_MAX_FLUSH_INTERVAL_DEFAULT = 5 * 1000;
+
+ private static AuditProviderFactory sFactory;
+
+ private AuditProvider mProvider = null;
+ private boolean mInitDone = false;
+
+ private AuditProviderFactory() {
+ LOG.info("AuditProviderFactory: creating..");
+
+ mProvider = getDefaultProvider();
+ }
+
+ public static AuditProviderFactory getInstance() {
+ if(sFactory == null) {
+ synchronized(AuditProviderFactory.class) {
+ if(sFactory == null) {
+ sFactory = new AuditProviderFactory();
+ }
+ }
+ }
+
+ return sFactory;
+ }
+
+ public static AuditProvider getAuditProvider() {
+ return AuditProviderFactory.getInstance().getProvider();
+ }
+
+ public AuditProvider getProvider() {
+ return mProvider;
+ }
+
+ public boolean isInitDone() {
+ return mInitDone;
+ }
+
+ public synchronized void init(Properties props, ApplicationType appType) {
+ LOG.info("AuditProviderFactory: initializing..");
+
+ if(mInitDone) {
+ LOG.warn("AuditProviderFactory.init(): already initialized!", new Exception());
+
+ return;
+ }
+ mInitDone = true;
+
+ setApplicationType(appType);
+
+ boolean isEnabled = BaseAuditProvider.getBooleanProperty(props, AUDIT_IS_ENABLED_PROP, false);
+ boolean isAuditToDbEnabled = BaseAuditProvider.getBooleanProperty(props, AUDIT_DB_IS_ENABLED_PROP, false);
+ boolean isAuditToHdfsEnabled = BaseAuditProvider.getBooleanProperty(props, AUDIT_HDFS_IS_ENABLED_PROP, false);
+ boolean isAuditToLog4jEnabled = BaseAuditProvider.getBooleanProperty(props, AUDIT_LOG4J_IS_ENABLED_PROP, false);
+
+ if(!isEnabled || !(isAuditToDbEnabled || isAuditToHdfsEnabled || isAuditToLog4jEnabled)) {
+ LOG.info("AuditProviderFactory: Audit not enabled..");
+
+ mProvider = getDefaultProvider();
+
+ return;
+ }
+
+ List<AuditProvider> providers = new ArrayList<AuditProvider>();
+
+ if(isAuditToDbEnabled) {
+ DbAuditProvider dbProvider = new DbAuditProvider();
+
+ boolean isAuditToDbAsync = BaseAuditProvider.getBooleanProperty(props, DbAuditProvider.AUDIT_DB_IS_ASYNC_PROP, false);
+
+ if(isAuditToDbAsync) {
+ int maxQueueSize = BaseAuditProvider.getIntProperty(props, DbAuditProvider.AUDIT_DB_MAX_QUEUE_SIZE_PROP, AUDIT_ASYNC_MAX_QUEUE_SIZE_DEFAULT);
+ int maxFlushInterval = BaseAuditProvider.getIntProperty(props, DbAuditProvider.AUDIT_DB_MAX_FLUSH_INTERVAL_PROP, AUDIT_ASYNC_MAX_FLUSH_INTERVAL_DEFAULT);
+
+ AsyncAuditProvider asyncProvider = new AsyncAuditProvider("DbAuditProvider", maxQueueSize, maxFlushInterval, dbProvider);
+
+ providers.add(asyncProvider);
+ } else {
+ providers.add(dbProvider);
+ }
+ }
+
+ if(isAuditToHdfsEnabled) {
+ HdfsAuditProvider hdfsProvider = new HdfsAuditProvider();
+
+ boolean isAuditToHdfsAsync = BaseAuditProvider.getBooleanProperty(props, HdfsAuditProvider.AUDIT_HDFS_IS_ASYNC_PROP, false);
+
+ if(isAuditToHdfsAsync) {
+ int maxQueueSize = BaseAuditProvider.getIntProperty(props, HdfsAuditProvider.AUDIT_HDFS_MAX_QUEUE_SIZE_PROP, AUDIT_ASYNC_MAX_QUEUE_SIZE_DEFAULT);
+ int maxFlushInterval = BaseAuditProvider.getIntProperty(props, HdfsAuditProvider.AUDIT_HDFS_MAX_FLUSH_INTERVAL_PROP, AUDIT_ASYNC_MAX_FLUSH_INTERVAL_DEFAULT);
+
+ AsyncAuditProvider asyncProvider = new AsyncAuditProvider("HdfsAuditProvider", maxQueueSize, maxFlushInterval, hdfsProvider);
+
+ providers.add(asyncProvider);
+ } else {
+ providers.add(hdfsProvider);
+ }
+ }
+
+ if(isAuditToLog4jEnabled) {
+ Log4jAuditProvider log4jProvider = new Log4jAuditProvider();
+
+ boolean isAuditToLog4jAsync = BaseAuditProvider.getBooleanProperty(props, Log4jAuditProvider.AUDIT_LOG4J_IS_ASYNC_PROP, false);
+
+ if(isAuditToLog4jAsync) {
+ int maxQueueSize = BaseAuditProvider.getIntProperty(props, Log4jAuditProvider.AUDIT_LOG4J_MAX_QUEUE_SIZE_PROP, AUDIT_ASYNC_MAX_QUEUE_SIZE_DEFAULT);
+ int maxFlushInterval = BaseAuditProvider.getIntProperty(props, Log4jAuditProvider.AUDIT_LOG4J_MAX_FLUSH_INTERVAL_PROP, AUDIT_ASYNC_MAX_FLUSH_INTERVAL_DEFAULT);
+
+ AsyncAuditProvider asyncProvider = new AsyncAuditProvider("Log4jAuditProvider", maxQueueSize, maxFlushInterval, log4jProvider);
+
+ providers.add(asyncProvider);
+ } else {
+ providers.add(log4jProvider);
+ }
+ }
+
+ if(providers.size() == 0) {
+ mProvider = getDefaultProvider();
+ } else if(providers.size() == 1) {
+ mProvider = providers.get(0);
+ } else {
+ MultiDestAuditProvider multiDestProvider = new MultiDestAuditProvider();
+
+ multiDestProvider.addAuditProviders(providers);
+
+ mProvider = multiDestProvider;
+ }
+
+ mProvider.init(props);
+ mProvider.start();
+
+ JVMShutdownHook jvmShutdownHook = new JVMShutdownHook(mProvider);
+
+ Runtime.getRuntime().addShutdownHook(jvmShutdownHook);
+ }
+
+ private static void setApplicationType(ApplicationType appType) {
+ String strAppType = null;
+
+ switch(appType) {
+ case Hdfs:
+ strAppType = "hdfs";
+ break;
+
+ case HiveCLI:
+ strAppType = "hiveCli";
+ break;
+
+ case HiveServer2:
+ strAppType = "hiveServer2";
+ break;
+
+ case HBaseMaster:
+ strAppType = "hbaseMaster";
+ break;
+
+ case HBaseRegionalServer:
+ strAppType = "hbaseRegional";
+ break;
+
+ case Knox:
+ strAppType = "knox";
+ break;
+
+ case Storm:
+ strAppType = "storm";
+ break;
+
+ case Unknown:
+ strAppType = "unknown";
+ break;
+ }
+
+ MiscUtil.setApplicationType(strAppType);
+ }
+
+ private AuditProvider getDefaultProvider() {
+ return new DummyAuditProvider();
+ }
+
+ private static class JVMShutdownHook extends Thread {
+ AuditProvider mProvider;
+
+ public JVMShutdownHook(AuditProvider provider) {
+ mProvider = provider;
+ }
+
+ public void run() {
+ mProvider.waitToComplete();
+ mProvider.stop();
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/provider/BaseAuditProvider.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/BaseAuditProvider.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/BaseAuditProvider.java
new file mode 100644
index 0000000..9a0cc45
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/BaseAuditProvider.java
@@ -0,0 +1,172 @@
+/*
+ * 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.audit.provider;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.audit.model.AuditEventBase;
+
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+public abstract class BaseAuditProvider implements AuditProvider {
+ private static final Log LOG = LogFactory.getLog(BaseAuditProvider.class);
+
+ private static final String AUDIT_LOG_FAILURE_REPORT_MIN_INTERVAL_PROP = "xasecure.audit.log.failure.report.min.interval.ms";
+
+ private int mLogFailureReportMinIntervalInMs = 60 * 1000;
+
+ private AtomicLong mFailedLogLastReportTime = new AtomicLong(0);
+ private AtomicLong mFailedLogCountSinceLastReport = new AtomicLong(0);
+ private AtomicLong mFailedLogCountLifeTime = new AtomicLong(0);
+
+
+ public BaseAuditProvider() {
+ }
+
+ @Override
+ public void init(Properties props) {
+ LOG.info("BaseAuditProvider.init()");
+
+ mLogFailureReportMinIntervalInMs = getIntProperty(props, AUDIT_LOG_FAILURE_REPORT_MIN_INTERVAL_PROP, 60 * 1000);
+ }
+
+ public void logFailedEvent(AuditEventBase event) {
+ logFailedEvent(event, null);
+ }
+
+ public void logFailedEvent(AuditEventBase event, Throwable excp) {
+ long now = System.currentTimeMillis();
+
+ long timeSinceLastReport = now - mFailedLogLastReportTime.get();
+ long countSinceLastReport = mFailedLogCountSinceLastReport.incrementAndGet();
+ long countLifeTime = mFailedLogCountLifeTime.incrementAndGet();
+
+ if(timeSinceLastReport >= mLogFailureReportMinIntervalInMs) {
+ mFailedLogLastReportTime.set(now);
+ mFailedLogCountSinceLastReport.set(0);
+
+ if(excp != null) {
+ LOG.warn("failed to log audit event: " + MiscUtil.stringify(event), excp);
+ } else {
+ LOG.warn("failed to log audit event: " + MiscUtil.stringify(event));
+ }
+
+ if(countLifeTime > 1) { // no stats to print for the 1st failure
+ LOG.warn("Log failure count: " + countSinceLastReport + " in past " + formatIntervalForLog(timeSinceLastReport) + "; " + countLifeTime + " during process lifetime");
+ }
+ }
+ }
+
+ public static Map<String, String> getPropertiesWithPrefix(Properties props, String prefix) {
+ Map<String, String> prefixedProperties = new HashMap<String, String>();
+
+ if(props != null && prefix != null) {
+ for(String key : props.stringPropertyNames()) {
+ if(key == null) {
+ continue;
+ }
+
+ String val = props.getProperty(key);
+
+ if(key.startsWith(prefix)) {
+ key = key.substring(prefix.length());
+
+ if(key == null) {
+ continue;
+ }
+
+ prefixedProperties.put(key, val);
+ }
+ }
+ }
+
+ return prefixedProperties;
+ }
+
+ public static boolean getBooleanProperty(Properties props, String propName, boolean defValue) {
+ boolean ret = defValue;
+
+ if(props != null && propName != null) {
+ String val = props.getProperty(propName);
+
+ if(val != null) {
+ ret = Boolean.valueOf(val);
+ }
+ }
+
+ return ret;
+ }
+
+ public static int getIntProperty(Properties props, String propName, int defValue) {
+ int ret = defValue;
+
+ if(props != null && propName != null) {
+ String val = props.getProperty(propName);
+
+ if(val != null) {
+ try {
+ ret = Integer.parseInt(val);
+ } catch(NumberFormatException excp) {
+ ret = defValue;
+ }
+ }
+ }
+
+ return ret;
+ }
+
+
+ public static String getStringProperty(Properties props, String propName) {
+ String ret = null;
+
+ if(props != null && propName != null) {
+ String val = props.getProperty(propName);
+ if ( val != null){
+ ret = val;
+ }
+ }
+
+ return ret;
+ }
+
+ public String getTimeDiffStr(long time1, long time2) {
+ long timeInMs = Math.abs(time1 - time2);
+ return formatIntervalForLog(timeInMs);
+ }
+
+ public String formatIntervalForLog(long timeInMs) {
+ long hours = timeInMs / (60 * 60 * 1000);
+ long minutes = (timeInMs / (60 * 1000)) % 60;
+ long seconds = (timeInMs % (60 * 1000)) / 1000;
+ long mSeconds = (timeInMs % (1000));
+
+ if (hours > 0)
+ return String.format("%02d:%02d:%02d.%03d hours", hours, minutes,
+ seconds, mSeconds);
+ else if (minutes > 0)
+ return String.format("%02d:%02d.%03d minutes", minutes, seconds,
+ mSeconds);
+ else if (seconds > 0)
+ return String.format("%02d.%03d seconds", seconds, mSeconds);
+ else
+ return String.format("%03d milli-seconds", mSeconds);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ranger/blob/413fcb68/agents-audit/src/main/java/org/apache/ranger/audit/provider/BufferedAuditProvider.java
----------------------------------------------------------------------
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/BufferedAuditProvider.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/BufferedAuditProvider.java
new file mode 100644
index 0000000..cb2b385
--- /dev/null
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/BufferedAuditProvider.java
@@ -0,0 +1,93 @@
+/**
+ * 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.audit.provider;
+
+import java.util.Properties;
+
+import org.apache.ranger.audit.model.AuditEventBase;
+
+public abstract class BufferedAuditProvider extends BaseAuditProvider {
+ private LogBuffer<AuditEventBase> mBuffer = null;
+ private LogDestination<AuditEventBase> mDestination = null;
+
+ @Override
+ public void init(Properties props) {
+ super.init(props);
+ }
+
+ @Override
+ public void log(AuditEventBase event) {
+ if(event.getAgentHostname() == null) {
+ event.setAgentHostname(MiscUtil.getHostname());
+ }
+
+ if(event.getLogType() == null) {
+ event.setLogType("RangerAudit");
+ }
+
+ if(event.getEventId() == null) {
+ event.setEventId(MiscUtil.generateUniqueId());
+ }
+
+ if(! mBuffer.add(event)) {
+ logFailedEvent(event);
+ }
+ }
+
+ @Override
+ public void start() {
+ mBuffer.start(mDestination);
+ }
+
+ @Override
+ public void stop() {
+ mBuffer.stop();
+ }
+
+ @Override
+ public void waitToComplete() {
+ }
+
+ @Override
+ public boolean isFlushPending() {
+ return false;
+ }
+
+ @Override
+ public long getLastFlushTime() {
+ return 0;
+ }
+
+ @Override
+ public void flush() {
+ }
+
+ protected LogBuffer<AuditEventBase> getBuffer() {
+ return mBuffer;
+ }
+
+ protected LogDestination<AuditEventBase> getDestination() {
+ return mDestination;
+ }
+
+ protected void setBufferAndDestination(LogBuffer<AuditEventBase> buffer,
+ LogDestination<AuditEventBase> destination) {
+ mBuffer = buffer;
+ mDestination = destination;
+ }
+}